xref: /titanic_51/usr/src/uts/common/io/sata/impl/sata.c (revision 945a00d8cdda9bddf8e8d4a185f30fb8d8caac33)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2010 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 
28 /*
29  * SATA Framework
30  * Generic SATA Host Adapter Implementation
31  */
32 
33 #include <sys/conf.h>
34 #include <sys/file.h>
35 #include <sys/ddi.h>
36 #include <sys/sunddi.h>
37 #include <sys/modctl.h>
38 #include <sys/cmn_err.h>
39 #include <sys/errno.h>
40 #include <sys/thread.h>
41 #include <sys/kstat.h>
42 #include <sys/note.h>
43 #include <sys/sysevent.h>
44 #include <sys/sysevent/eventdefs.h>
45 #include <sys/sysevent/dr.h>
46 #include <sys/taskq.h>
47 #include <sys/disp.h>
48 
49 #include <sys/sata/impl/sata.h>
50 #include <sys/sata/sata_hba.h>
51 #include <sys/sata/sata_defs.h>
52 #include <sys/sata/sata_cfgadm.h>
53 #include <sys/sata/sata_blacklist.h>
54 #include <sys/sata/sata_satl.h>
55 
56 #include <sys/scsi/impl/spc3_types.h>
57 
58 /* Debug flags - defined in sata.h */
59 int	sata_debug_flags = 0;
60 int	sata_msg = 0;
61 
62 /*
63  * Flags enabling selected SATA HBA framework functionality
64  */
65 #define	SATA_ENABLE_QUEUING		1
66 #define	SATA_ENABLE_NCQ			2
67 #define	SATA_ENABLE_PROCESS_EVENTS	4
68 #define	SATA_ENABLE_PMULT_FBS		8 /* FIS-Based Switching */
69 int sata_func_enable =
70 	SATA_ENABLE_PROCESS_EVENTS | SATA_ENABLE_QUEUING | SATA_ENABLE_NCQ;
71 
72 /*
73  * Global variable setting default maximum queue depth (NCQ or TCQ)
74  * Note:minimum queue depth is 1
75  */
76 int sata_max_queue_depth = SATA_MAX_QUEUE_DEPTH; /* max NCQ/TCQ queue depth */
77 
78 /*
79  * Currently used default NCQ/TCQ queue depth. It is set-up during the driver
80  * initialization, using value from sata_max_queue_depth
81  * It is adjusted to minimum supported by the controller and by the device,
82  * if queueing is enabled.
83  */
84 static	int sata_current_max_qdepth;
85 
86 /*
87  * Global variable determining the default behavior after device hotpluggin.
88  * If non-zero, the hotplugged device is onlined (if possible) without explicit
89  * IOCTL request (AP_CONFIGURE).
90  * If zero, hotplugged device is identified, but not onlined.
91  * Enabling (AP_CONNECT) device port with an attached device does not result
92  * in device onlining regardless of the flag setting
93  */
94 int sata_auto_online = 0;
95 
96 #ifdef SATA_DEBUG
97 
98 #define	SATA_LOG_D(args)	sata_log args
99 uint64_t mbuf_count = 0;
100 uint64_t mbuffail_count = 0;
101 
102 sata_atapi_cmd_t sata_atapi_trace[64];
103 uint32_t sata_atapi_trace_index = 0;
104 int sata_atapi_trace_save = 1;
105 static	void sata_save_atapi_trace(sata_pkt_txlate_t *, int);
106 #define	SATAATAPITRACE(spx, count)	if (sata_atapi_trace_save) \
107     sata_save_atapi_trace(spx, count);
108 
109 #else
110 #define	SATA_LOG_D(args)	sata_trace_log args
111 #define	SATAATAPITRACE(spx, count)
112 #endif
113 
114 #if 0
115 static void
116 sata_test_atapi_packet_command(sata_hba_inst_t *, int);
117 #endif
118 
119 #ifdef SATA_INJECT_FAULTS
120 
121 #define		SATA_INJECT_PKT_FAULT	1
122 uint32_t	sata_inject_fault = 0;
123 
124 uint32_t	sata_inject_fault_count = 0;
125 uint32_t	sata_inject_fault_pause_count = 0;
126 uint32_t	sata_fault_type = 0;
127 uint32_t	sata_fault_cmd = 0;
128 dev_info_t	*sata_fault_ctrl = NULL;
129 sata_device_t	sata_fault_device;
130 
131 static	void sata_inject_pkt_fault(sata_pkt_t *, int *, int);
132 
133 #endif
134 
135 #define	LEGACY_HWID_LEN	64	/* Model (40) + Serial (20) + pad */
136 
137 static char sata_rev_tag[] = {"1.46"};
138 
139 /*
140  * SATA cb_ops functions
141  */
142 static 	int sata_hba_open(dev_t *, int, int, cred_t *);
143 static 	int sata_hba_close(dev_t, int, int, cred_t *);
144 static 	int sata_hba_ioctl(dev_t, int, intptr_t, int, cred_t *,	int *);
145 
146 /*
147  * SCSA required entry points
148  */
149 static	int sata_scsi_tgt_init(dev_info_t *, dev_info_t *,
150     scsi_hba_tran_t *, struct scsi_device *);
151 static	int sata_scsi_tgt_probe(struct scsi_device *,
152     int (*callback)(void));
153 static void sata_scsi_tgt_free(dev_info_t *, dev_info_t *,
154     scsi_hba_tran_t *, struct scsi_device *);
155 static 	int sata_scsi_start(struct scsi_address *, struct scsi_pkt *);
156 static 	int sata_scsi_abort(struct scsi_address *, struct scsi_pkt *);
157 static 	int sata_scsi_reset(struct scsi_address *, int);
158 static 	int sata_scsi_getcap(struct scsi_address *, char *, int);
159 static 	int sata_scsi_setcap(struct scsi_address *, char *, int, int);
160 static 	struct scsi_pkt *sata_scsi_init_pkt(struct scsi_address *,
161     struct scsi_pkt *, struct buf *, int, int, int, int, int (*)(caddr_t),
162     caddr_t);
163 static 	void sata_scsi_destroy_pkt(struct scsi_address *, struct scsi_pkt *);
164 static 	void sata_scsi_dmafree(struct scsi_address *, struct scsi_pkt *);
165 static 	void sata_scsi_sync_pkt(struct scsi_address *, struct scsi_pkt *);
166 
167 /*
168  * SATA HBA interface functions are defined in sata_hba.h header file
169  */
170 
171 /* Event processing functions */
172 static	void sata_event_daemon(void *);
173 static	void sata_event_thread_control(int);
174 static	void sata_process_controller_events(sata_hba_inst_t *sata_hba_inst);
175 static	void sata_process_pmult_events(sata_hba_inst_t *, uint8_t);
176 static	void sata_process_device_reset(sata_hba_inst_t *, sata_address_t *);
177 static	void sata_process_pmdevice_reset(sata_hba_inst_t *, sata_address_t *);
178 static	void sata_process_port_failed_event(sata_hba_inst_t *,
179     sata_address_t *);
180 static	void sata_process_port_link_events(sata_hba_inst_t *,
181     sata_address_t *);
182 static	void sata_process_pmport_link_events(sata_hba_inst_t *,
183     sata_address_t *);
184 static	void sata_process_device_detached(sata_hba_inst_t *, sata_address_t *);
185 static	void sata_process_pmdevice_detached(sata_hba_inst_t *,
186     sata_address_t *);
187 static	void sata_process_device_attached(sata_hba_inst_t *, sata_address_t *);
188 static	void sata_process_pmdevice_attached(sata_hba_inst_t *,
189     sata_address_t *);
190 static	void sata_process_port_pwr_change(sata_hba_inst_t *, sata_address_t *);
191 static	void sata_process_cntrl_pwr_level_change(sata_hba_inst_t *);
192 static	void sata_process_target_node_cleanup(sata_hba_inst_t *,
193     sata_address_t *);
194 static	void sata_process_device_autoonline(sata_hba_inst_t *,
195     sata_address_t *saddr);
196 
197 /*
198  * Local translation functions
199  */
200 static	int sata_txlt_inquiry(sata_pkt_txlate_t *);
201 static	int sata_txlt_test_unit_ready(sata_pkt_txlate_t *);
202 static	int sata_txlt_start_stop_unit(sata_pkt_txlate_t *);
203 static	int sata_txlt_read_capacity(sata_pkt_txlate_t *);
204 static	int sata_txlt_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 (servicing_interrupt()) {
2443 				if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
2444 				    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
2445 				    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) ==
2446 				    NULL) {
2447 					return (TRAN_BUSY);
2448 				}
2449 			} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
2450 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
2451 			    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
2452 				/* Scheduling the callback failed */
2453 				return (TRAN_BUSY);
2454 			}
2455 			return (TRAN_ACCEPT);
2456 		}
2457 		/* No callback available */
2458 		return (TRAN_FATAL_ERROR);
2459 	}
2460 
2461 	if (sdinfo->satadrv_type & SATA_DTYPE_ATAPI) {
2462 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
2463 		rval = sata_txlt_atapi(spx);
2464 		SATADBG1(SATA_DBG_SCSI_IF, sata_hba_inst,
2465 		    "sata_scsi_start atapi: rval %d\n", rval);
2466 		return (rval);
2467 	}
2468 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
2469 
2470 	/*
2471 	 * Checking for power state, if it was on
2472 	 * STOPPED state, then the drive is not capable
2473 	 * of processing media access command.  And
2474 	 * TEST_UNIT_READY, REQUEST_SENSE has special handling
2475 	 * in the function for different power state.
2476 	 */
2477 	if (((sdinfo->satadrv_power_level == SATA_POWER_STANDBY) ||
2478 	    (sdinfo->satadrv_power_level == SATA_POWER_STOPPED)) &&
2479 	    (SATA_IS_MEDIUM_ACCESS_CMD(pkt->pkt_cdbp[0]))) {
2480 		return (sata_txlt_check_condition(spx, KEY_NOT_READY,
2481 		    SD_SCSI_ASC_LU_NOT_READY));
2482 	}
2483 
2484 	/* ATA Disk commands processing starts here */
2485 
2486 	bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
2487 
2488 	switch (pkt->pkt_cdbp[0]) {
2489 
2490 	case SCMD_INQUIRY:
2491 		/* Mapped to identify device */
2492 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2493 			bp_mapin(bp);
2494 		rval = sata_txlt_inquiry(spx);
2495 		break;
2496 
2497 	case SCMD_TEST_UNIT_READY:
2498 		/*
2499 		 * SAT "SATA to ATA Translation" doc specifies translation
2500 		 * to ATA CHECK POWER MODE.
2501 		 */
2502 		rval = sata_txlt_test_unit_ready(spx);
2503 		break;
2504 
2505 	case SCMD_START_STOP:
2506 		/* Mapping depends on the command */
2507 		rval = sata_txlt_start_stop_unit(spx);
2508 		break;
2509 
2510 	case SCMD_READ_CAPACITY:
2511 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2512 			bp_mapin(bp);
2513 		rval = sata_txlt_read_capacity(spx);
2514 		break;
2515 
2516 	case SCMD_REQUEST_SENSE:
2517 		/*
2518 		 * Always No Sense, since we force ARQ
2519 		 */
2520 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2521 			bp_mapin(bp);
2522 		rval = sata_txlt_request_sense(spx);
2523 		break;
2524 
2525 	case SCMD_LOG_SENSE_G1:
2526 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2527 			bp_mapin(bp);
2528 		rval = sata_txlt_log_sense(spx);
2529 		break;
2530 
2531 	case SCMD_LOG_SELECT_G1:
2532 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2533 			bp_mapin(bp);
2534 		rval = sata_txlt_log_select(spx);
2535 		break;
2536 
2537 	case SCMD_MODE_SENSE:
2538 	case SCMD_MODE_SENSE_G1:
2539 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2540 			bp_mapin(bp);
2541 		rval = sata_txlt_mode_sense(spx);
2542 		break;
2543 
2544 
2545 	case SCMD_MODE_SELECT:
2546 	case SCMD_MODE_SELECT_G1:
2547 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2548 			bp_mapin(bp);
2549 		rval = sata_txlt_mode_select(spx);
2550 		break;
2551 
2552 	case SCMD_SYNCHRONIZE_CACHE:
2553 	case SCMD_SYNCHRONIZE_CACHE_G1:
2554 		rval = sata_txlt_synchronize_cache(spx);
2555 		break;
2556 
2557 	case SCMD_READ:
2558 	case SCMD_READ_G1:
2559 	case SCMD_READ_G4:
2560 	case SCMD_READ_G5:
2561 		rval = sata_txlt_read(spx);
2562 		break;
2563 	case SCMD_WRITE_BUFFER:
2564 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2565 			bp_mapin(bp);
2566 		rval = sata_txlt_write_buffer(spx);
2567 		break;
2568 
2569 	case SCMD_WRITE:
2570 	case SCMD_WRITE_G1:
2571 	case SCMD_WRITE_G4:
2572 	case SCMD_WRITE_G5:
2573 		rval = sata_txlt_write(spx);
2574 		break;
2575 
2576 	case SCMD_SEEK:
2577 		rval = sata_txlt_nodata_cmd_immediate(spx);
2578 		break;
2579 
2580 	case SPC3_CMD_ATA_COMMAND_PASS_THROUGH12:
2581 	case SPC3_CMD_ATA_COMMAND_PASS_THROUGH16:
2582 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2583 			bp_mapin(bp);
2584 		rval = sata_txlt_ata_pass_thru(spx);
2585 		break;
2586 
2587 		/* Other cases will be filed later */
2588 		/* postponed until phase 2 of the development */
2589 	default:
2590 		rval = sata_txlt_invalid_command(spx);
2591 		break;
2592 	}
2593 
2594 	SATADBG1(SATA_DBG_SCSI_IF, sata_hba_inst,
2595 	    "sata_scsi_start: rval %d\n", rval);
2596 
2597 	return (rval);
2598 }
2599 
2600 /*
2601  * Implementation of scsi tran_abort.
2602  * Abort specific pkt or all packets.
2603  *
2604  * Returns 1 if one or more packets were aborted, returns 0 otherwise
2605  *
2606  * May be called from an interrupt level.
2607  */
2608 static int
2609 sata_scsi_abort(struct scsi_address *ap, struct scsi_pkt *scsi_pkt)
2610 {
2611 	sata_hba_inst_t *sata_hba_inst =
2612 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2613 	sata_device_t	sata_device;
2614 	sata_pkt_t	*sata_pkt;
2615 
2616 	SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
2617 	    "sata_scsi_abort: %s at target: 0x%x\n",
2618 	    scsi_pkt == NULL ? "all packets" : "one pkt", ap->a_target);
2619 
2620 	/* Validate address */
2621 	if (sata_validate_scsi_address(sata_hba_inst, ap, &sata_device) != 0)
2622 		/* Invalid address */
2623 		return (0);
2624 
2625 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2626 	    sata_device.satadev_addr.cport)));
2627 	if (sata_get_device_info(sata_hba_inst, &sata_device) == NULL) {
2628 		/* invalid address */
2629 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2630 		    sata_device.satadev_addr.cport)));
2631 		return (0);
2632 	}
2633 	if (scsi_pkt == NULL) {
2634 		/*
2635 		 * Abort all packets.
2636 		 * Although we do not have specific packet, we still need
2637 		 * dummy packet structure to pass device address to HBA.
2638 		 * Allocate one, without sleeping. Fail if pkt cannot be
2639 		 * allocated.
2640 		 */
2641 		sata_pkt = kmem_zalloc(sizeof (sata_pkt_t), KM_NOSLEEP);
2642 		if (sata_pkt == NULL) {
2643 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2644 			    sata_device.satadev_addr.cport)));
2645 			SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_pkt_abort: "
2646 			    "could not allocate sata_pkt"));
2647 			return (0);
2648 		}
2649 		sata_pkt->satapkt_rev = SATA_PKT_REV;
2650 		sata_pkt->satapkt_device = sata_device;
2651 		sata_pkt->satapkt_device.satadev_rev = SATA_DEVICE_REV;
2652 	} else {
2653 		if (scsi_pkt->pkt_ha_private == NULL) {
2654 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2655 			    sata_device.satadev_addr.cport)));
2656 			return (0); /* Bad scsi pkt */
2657 		}
2658 		/* extract pointer to sata pkt */
2659 		sata_pkt = ((sata_pkt_txlate_t *)scsi_pkt->pkt_ha_private)->
2660 		    txlt_sata_pkt;
2661 	}
2662 
2663 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2664 	    sata_device.satadev_addr.cport)));
2665 	/* Send abort request to HBA */
2666 	if ((*SATA_ABORT_FUNC(sata_hba_inst))
2667 	    (SATA_DIP(sata_hba_inst), sata_pkt,
2668 	    scsi_pkt == NULL ? SATA_ABORT_ALL_PACKETS : SATA_ABORT_PACKET) ==
2669 	    SATA_SUCCESS) {
2670 		if (scsi_pkt == NULL)
2671 			kmem_free(sata_pkt, sizeof (sata_pkt_t));
2672 		/* Success */
2673 		return (1);
2674 	}
2675 	/* Else, something did not go right */
2676 	if (scsi_pkt == NULL)
2677 		kmem_free(sata_pkt, sizeof (sata_pkt_t));
2678 	/* Failure */
2679 	return (0);
2680 }
2681 
2682 
2683 /*
2684  * Implementation of scsi tran_reset.
2685  * RESET_ALL request is translated into port reset.
2686  * RESET_TARGET requests is translated into a device reset,
2687  * RESET_LUN request is accepted only for LUN 0 and translated into
2688  * device reset.
2689  * The target reset should cause all HBA active and queued packets to
2690  * be terminated and returned with pkt reason SATA_PKT_RESET prior to
2691  * the return. HBA should report reset event for the device.
2692  *
2693  * Returns 1 upon success, 0 upon failure.
2694  */
2695 static int
2696 sata_scsi_reset(struct scsi_address *ap, int level)
2697 {
2698 	sata_hba_inst_t	*sata_hba_inst =
2699 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2700 	sata_device_t	sata_device;
2701 	int		val;
2702 
2703 	SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
2704 	    "sata_scsi_reset: level %d target: 0x%x\n",
2705 	    level, ap->a_target);
2706 
2707 	/* Validate address */
2708 	val = sata_validate_scsi_address(sata_hba_inst, ap, &sata_device);
2709 	if (val == -1)
2710 		/* Invalid address */
2711 		return (0);
2712 
2713 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2714 	    sata_device.satadev_addr.cport)));
2715 	if (sata_get_device_info(sata_hba_inst, &sata_device) == NULL) {
2716 		/* invalid address */
2717 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2718 		    sata_device.satadev_addr.cport)));
2719 		return (0);
2720 	}
2721 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2722 	    sata_device.satadev_addr.cport)));
2723 	if (level == RESET_ALL) {
2724 		/* port reset */
2725 		if (sata_device.satadev_addr.qual == SATA_ADDR_DCPORT)
2726 			sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
2727 		else
2728 			sata_device.satadev_addr.qual = SATA_ADDR_PMPORT;
2729 
2730 		if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))
2731 		    (SATA_DIP(sata_hba_inst), &sata_device) == SATA_SUCCESS)
2732 			return (1);
2733 		else
2734 			return (0);
2735 
2736 	} else if (val == 0 &&
2737 	    (level == RESET_TARGET || level == RESET_LUN)) {
2738 		/* reset device (device attached) */
2739 		if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))
2740 		    (SATA_DIP(sata_hba_inst), &sata_device) == SATA_SUCCESS)
2741 			return (1);
2742 		else
2743 			return (0);
2744 	}
2745 	return (0);
2746 }
2747 
2748 
2749 /*
2750  * Implementation of scsi tran_getcap (get transport/device capabilities).
2751  * Supported capabilities for SATA hard disks:
2752  * auto-rqsense		(always supported)
2753  * tagged-qing		(supported if HBA supports it)
2754  * untagged-qing	(could be supported if disk supports it, but because
2755  *			 caching behavior allowing untagged queuing actually
2756  *			 results in reduced performance.  sd tries to throttle
2757  *			 back to only 3 outstanding commands, which may
2758  *			 work for real SCSI disks, but with read ahead
2759  *			 caching, having more than 1 outstanding command
2760  *			 results in cache thrashing.)
2761  * sector_size
2762  * dma_max
2763  * interconnect-type	(INTERCONNECT_SATA)
2764  *
2765  * Supported capabilities for ATAPI CD/DVD devices:
2766  * auto-rqsense		(always supported)
2767  * sector_size
2768  * dma_max
2769  * max-cdb-length
2770  * interconnect-type	(INTERCONNECT_SATA)
2771  *
2772  * Supported capabilities for ATAPI TAPE devices:
2773  * auto-rqsense		(always supported)
2774  * dma_max
2775  * max-cdb-length
2776  *
2777  * Supported capabilities for SATA ATAPI hard disks:
2778  * auto-rqsense		(always supported)
2779  * interconnect-type	(INTERCONNECT_SATA)
2780  * max-cdb-length
2781  *
2782  * Request for other capabilities is rejected as unsupported.
2783  *
2784  * Returns supported capability value, or -1 if capability is unsuppported or
2785  * the address is invalid - no device.
2786  */
2787 
2788 static int
2789 sata_scsi_getcap(struct scsi_address *ap, char *cap, int whom)
2790 {
2791 
2792 	sata_hba_inst_t 	*sata_hba_inst =
2793 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2794 	sata_device_t		sata_device;
2795 	sata_drive_info_t	*sdinfo;
2796 	ddi_dma_attr_t		adj_dma_attr;
2797 	int 			rval;
2798 
2799 	SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
2800 	    "sata_scsi_getcap: target: 0x%x, cap: %s\n",
2801 	    ap->a_target, cap);
2802 
2803 	/*
2804 	 * We want to process the capabilities on per port granularity.
2805 	 * So, we are specifically restricting ourselves to whom != 0
2806 	 * to exclude the controller wide handling.
2807 	 */
2808 	if (cap == NULL || whom == 0)
2809 		return (-1);
2810 
2811 	if (sata_validate_scsi_address(sata_hba_inst, ap, &sata_device) != 0) {
2812 		/* Invalid address */
2813 		return (-1);
2814 	}
2815 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2816 	    sata_device.satadev_addr.cport)));
2817 	if ((sdinfo = sata_get_device_info(sata_hba_inst, &sata_device)) ==
2818 	    NULL) {
2819 		/* invalid address */
2820 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2821 		    sata_device.satadev_addr.cport)));
2822 		return (-1);
2823 	}
2824 
2825 	switch (scsi_hba_lookup_capstr(cap)) {
2826 	case SCSI_CAP_ARQ:
2827 		rval = 1;		/* ARQ supported, turned on */
2828 		break;
2829 
2830 	case SCSI_CAP_SECTOR_SIZE:
2831 		if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK)
2832 			rval = SATA_DISK_SECTOR_SIZE;	/* fixed size */
2833 		else if (sdinfo->satadrv_type == SATA_DTYPE_ATAPICD)
2834 			rval = SATA_ATAPI_SECTOR_SIZE;
2835 		else rval = -1;
2836 		break;
2837 
2838 	/*
2839 	 * untagged queuing cause a performance inversion because of
2840 	 * the way sd operates.  Because of this reason we do not
2841 	 * use it when available.
2842 	 */
2843 	case SCSI_CAP_UNTAGGED_QING:
2844 		if (sdinfo->satadrv_features_enabled &
2845 		    SATA_DEV_F_E_UNTAGGED_QING)
2846 			rval = 1;	/* Untagged queuing available */
2847 		else
2848 			rval = -1;	/* Untagged queuing not available */
2849 		break;
2850 
2851 	case SCSI_CAP_TAGGED_QING:
2852 		if ((sdinfo->satadrv_features_enabled &
2853 		    SATA_DEV_F_E_TAGGED_QING) &&
2854 		    (sdinfo->satadrv_max_queue_depth > 1))
2855 			rval = 1;	/* Tagged queuing available */
2856 		else
2857 			rval = -1;	/* Tagged queuing not available */
2858 		break;
2859 
2860 	case SCSI_CAP_DMA_MAX:
2861 		sata_adjust_dma_attr(sdinfo, SATA_DMA_ATTR(sata_hba_inst),
2862 		    &adj_dma_attr);
2863 		rval = (int)adj_dma_attr.dma_attr_maxxfer;
2864 		/* We rely on the fact that dma_attr_maxxfer < 0x80000000 */
2865 		break;
2866 
2867 	case SCSI_CAP_INTERCONNECT_TYPE:
2868 		rval = INTERCONNECT_SATA;	/* SATA interconnect type */
2869 		break;
2870 
2871 	case SCSI_CAP_CDB_LEN:
2872 		if (sdinfo->satadrv_type & SATA_DTYPE_ATAPI)
2873 			rval = sdinfo->satadrv_atapi_cdb_len;
2874 		else
2875 			rval = -1;
2876 		break;
2877 
2878 	default:
2879 		rval = -1;
2880 		break;
2881 	}
2882 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2883 	    sata_device.satadev_addr.cport)));
2884 	return (rval);
2885 }
2886 
2887 /*
2888  * Implementation of scsi tran_setcap
2889  *
2890  * Only SCSI_CAP_UNTAGGED_QING and  SCSI_CAP_TAGGED_QING are changeable.
2891  *
2892  */
2893 static int
2894 sata_scsi_setcap(struct scsi_address *ap, char *cap, int value, int whom)
2895 {
2896 	sata_hba_inst_t	*sata_hba_inst =
2897 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2898 	sata_device_t	sata_device;
2899 	sata_drive_info_t	*sdinfo;
2900 	int		rval;
2901 
2902 	SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
2903 	    "sata_scsi_setcap: target: 0x%x, cap: %s\n", ap->a_target, cap);
2904 
2905 	/*
2906 	 * We want to process the capabilities on per port granularity.
2907 	 * So, we are specifically restricting ourselves to whom != 0
2908 	 * to exclude the controller wide handling.
2909 	 */
2910 	if (cap == NULL || whom == 0) {
2911 		return (-1);
2912 	}
2913 
2914 	if (sata_validate_scsi_address(sata_hba_inst, ap, &sata_device) != 0) {
2915 		/* Invalid address */
2916 		return (-1);
2917 	}
2918 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2919 	    sata_device.satadev_addr.cport)));
2920 	if ((sdinfo = sata_get_device_info(sata_hba_inst,
2921 	    &sata_device)) == NULL) {
2922 		/* invalid address */
2923 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2924 		    sata_device.satadev_addr.cport)));
2925 		return (-1);
2926 	}
2927 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2928 	    sata_device.satadev_addr.cport)));
2929 
2930 	switch (scsi_hba_lookup_capstr(cap)) {
2931 	case SCSI_CAP_ARQ:
2932 	case SCSI_CAP_SECTOR_SIZE:
2933 	case SCSI_CAP_DMA_MAX:
2934 	case SCSI_CAP_INTERCONNECT_TYPE:
2935 		rval = 0;
2936 		break;
2937 	case SCSI_CAP_UNTAGGED_QING:
2938 		if (SATA_QDEPTH(sata_hba_inst) > 1) {
2939 			rval = 1;
2940 			if (value == 1) {
2941 				sdinfo->satadrv_features_enabled |=
2942 				    SATA_DEV_F_E_UNTAGGED_QING;
2943 			} else if (value == 0) {
2944 				sdinfo->satadrv_features_enabled &=
2945 				    ~SATA_DEV_F_E_UNTAGGED_QING;
2946 			} else {
2947 				rval = -1;
2948 			}
2949 		} else {
2950 			rval = 0;
2951 		}
2952 		break;
2953 	case SCSI_CAP_TAGGED_QING:
2954 		/* This can TCQ or NCQ */
2955 		if (sata_func_enable & SATA_ENABLE_QUEUING &&
2956 		    ((sdinfo->satadrv_features_support & SATA_DEV_F_TCQ &&
2957 		    SATA_FEATURES(sata_hba_inst) & SATA_CTLF_QCMD) ||
2958 		    (sata_func_enable & SATA_ENABLE_NCQ &&
2959 		    sdinfo->satadrv_features_support & SATA_DEV_F_NCQ &&
2960 		    SATA_FEATURES(sata_hba_inst) & SATA_CTLF_NCQ)) &&
2961 		    (sdinfo->satadrv_max_queue_depth > 1)) {
2962 			rval = 1;
2963 			if (value == 1) {
2964 				sdinfo->satadrv_features_enabled |=
2965 				    SATA_DEV_F_E_TAGGED_QING;
2966 			} else if (value == 0) {
2967 				sdinfo->satadrv_features_enabled &=
2968 				    ~SATA_DEV_F_E_TAGGED_QING;
2969 			} else {
2970 				rval = -1;
2971 			}
2972 		} else {
2973 			rval = 0;
2974 		}
2975 		break;
2976 	default:
2977 		rval = -1;
2978 		break;
2979 	}
2980 	return (rval);
2981 }
2982 
2983 /*
2984  * Implementations of scsi tran_destroy_pkt.
2985  * Free resources allocated by sata_scsi_init_pkt()
2986  */
2987 static void
2988 sata_scsi_destroy_pkt(struct scsi_address *ap, struct scsi_pkt *pkt)
2989 {
2990 	sata_pkt_txlate_t *spx;
2991 
2992 	spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
2993 
2994 	sata_common_free_dma_rsrcs(spx);
2995 
2996 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
2997 	sata_pkt_free(spx);
2998 
2999 	scsi_hba_pkt_free(ap, pkt);
3000 }
3001 
3002 /*
3003  * Implementation of scsi tran_dmafree.
3004  * Free DMA resources allocated by sata_scsi_init_pkt()
3005  */
3006 
3007 static void
3008 sata_scsi_dmafree(struct scsi_address *ap, struct scsi_pkt *pkt)
3009 {
3010 #ifndef __lock_lint
3011 	_NOTE(ARGUNUSED(ap))
3012 #endif
3013 	sata_pkt_txlate_t *spx;
3014 
3015 	ASSERT(pkt != NULL);
3016 	spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
3017 
3018 	sata_common_free_dma_rsrcs(spx);
3019 }
3020 
3021 /*
3022  * Implementation of scsi tran_sync_pkt.
3023  *
3024  * The assumption below is that pkt is unique - there is no need to check ap
3025  *
3026  * Synchronize DMA buffer and, if the intermediate buffer is used, copy data
3027  * into/from the real buffer.
3028  */
3029 static void
3030 sata_scsi_sync_pkt(struct scsi_address *ap, struct scsi_pkt *pkt)
3031 {
3032 #ifndef __lock_lint
3033 	_NOTE(ARGUNUSED(ap))
3034 #endif
3035 	int rval;
3036 	sata_pkt_txlate_t *spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
3037 	struct buf *bp;
3038 	int direction;
3039 
3040 	ASSERT(spx != NULL);
3041 	if (spx->txlt_buf_dma_handle != NULL) {
3042 		direction = spx->txlt_sata_pkt->
3043 		    satapkt_cmd.satacmd_flags.sata_data_direction;
3044 		if (spx->txlt_sata_pkt != NULL &&
3045 		    direction != SATA_DIR_NODATA_XFER) {
3046 			if (spx->txlt_tmp_buf != NULL) {
3047 				/* Intermediate DMA buffer used */
3048 				bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
3049 
3050 				if (direction & SATA_DIR_WRITE) {
3051 					bcopy(bp->b_un.b_addr,
3052 					    spx->txlt_tmp_buf, bp->b_bcount);
3053 				}
3054 			}
3055 			/* Sync the buffer for device or for CPU */
3056 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle,   0, 0,
3057 			    (direction & SATA_DIR_WRITE) ?
3058 			    DDI_DMA_SYNC_FORDEV :  DDI_DMA_SYNC_FORCPU);
3059 			ASSERT(rval == DDI_SUCCESS);
3060 			if (spx->txlt_tmp_buf != NULL &&
3061 			    !(direction & SATA_DIR_WRITE)) {
3062 				/* Intermediate DMA buffer used for read */
3063 				bcopy(spx->txlt_tmp_buf,
3064 				    bp->b_un.b_addr, bp->b_bcount);
3065 			}
3066 
3067 		}
3068 	}
3069 }
3070 
3071 
3072 
3073 /* *******************  SATA - SCSI Translation functions **************** */
3074 /*
3075  * SCSI to SATA pkt and command translation and SATA to SCSI status/error
3076  * translation.
3077  */
3078 
3079 /*
3080  * Checks if a device exists and can be access and translates common
3081  * scsi_pkt data to sata_pkt data.
3082  *
3083  * Flag argument indicates that a non-read/write ATA command may be sent
3084  * to HBA in arbitrary SYNC mode to execute this packet.
3085  *
3086  * Returns TRAN_ACCEPT and scsi pkt_reason CMD_CMPLT if device exists and
3087  * sata_pkt was set-up.
3088  * Returns TRAN_ACCEPT and scsi pkt_reason CMD_DEV_GONE if device does not
3089  * exist and pkt_comp callback was scheduled.
3090  * Returns other TRAN_XXXXX values when error occured and command should be
3091  * rejected with the returned TRAN_XXXXX value.
3092  *
3093  * This function should be called with port mutex held.
3094  */
3095 static int
3096 sata_txlt_generic_pkt_info(sata_pkt_txlate_t *spx, int *reason, int flag)
3097 {
3098 	sata_drive_info_t *sdinfo;
3099 	sata_device_t sata_device;
3100 	const struct sata_cmd_flags sata_initial_cmd_flags = {
3101 		SATA_DIR_NODATA_XFER,
3102 		/* all other values to 0/FALSE */
3103 	};
3104 	/*
3105 	 * Pkt_reason has to be set if the pkt_comp callback is invoked,
3106 	 * and that implies TRAN_ACCEPT return value. Any other returned value
3107 	 * indicates that the scsi packet was not accepted (the reason will not
3108 	 * be checked by the scsi target driver).
3109 	 * To make debugging easier, we set pkt_reason to know value here.
3110 	 * It may be changed later when different completion reason is
3111 	 * determined.
3112 	 */
3113 	spx->txlt_scsi_pkt->pkt_reason = CMD_TRAN_ERR;
3114 	*reason = CMD_TRAN_ERR;
3115 
3116 	/* Validate address */
3117 	switch (sata_validate_scsi_address(spx->txlt_sata_hba_inst,
3118 	    &spx->txlt_scsi_pkt->pkt_address, &sata_device)) {
3119 
3120 	case -1:
3121 		/* Invalid address or invalid device type */
3122 		return (TRAN_BADPKT);
3123 	case 2:
3124 		/*
3125 		 * Valid address but device type is unknown - Chack if it is
3126 		 * in the reset state and therefore in an indeterminate state.
3127 		 */
3128 		sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3129 		    &spx->txlt_sata_pkt->satapkt_device);
3130 		if (sdinfo != NULL && (sdinfo->satadrv_event_flags &
3131 		    (SATA_EVNT_DEVICE_RESET |
3132 		    SATA_EVNT_INPROC_DEVICE_RESET)) != 0) {
3133 			if (!ddi_in_panic()) {
3134 				spx->txlt_scsi_pkt->pkt_reason = CMD_INCOMPLETE;
3135 				*reason = CMD_INCOMPLETE;
3136 				SATADBG1(SATA_DBG_SCSI_IF,
3137 				    spx->txlt_sata_hba_inst,
3138 				    "sata_scsi_start: rejecting command "
3139 				    "because of device reset state\n", NULL);
3140 				return (TRAN_BUSY);
3141 			}
3142 		}
3143 		/* FALLTHROUGH */
3144 	case 1:
3145 		/* valid address but no valid device - it has disappeared */
3146 		spx->txlt_scsi_pkt->pkt_reason = CMD_DEV_GONE;
3147 		*reason = CMD_DEV_GONE;
3148 		/*
3149 		 * The sd target driver is checking CMD_DEV_GONE pkt_reason
3150 		 * only in callback function (for normal requests) and
3151 		 * in the dump code path.
3152 		 * So, if the callback is available, we need to do
3153 		 * the callback rather than returning TRAN_FATAL_ERROR here.
3154 		 */
3155 		if (spx->txlt_scsi_pkt->pkt_comp != NULL) {
3156 			/* scsi callback required */
3157 			if (servicing_interrupt()) {
3158 				if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3159 				    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3160 				    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) ==
3161 				    NULL) {
3162 					return (TRAN_BUSY);
3163 				}
3164 			} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3165 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3166 			    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
3167 				/* Scheduling the callback failed */
3168 				return (TRAN_BUSY);
3169 			}
3170 
3171 			return (TRAN_ACCEPT);
3172 		}
3173 		return (TRAN_FATAL_ERROR);
3174 	default:
3175 		/* all OK; pkt reason will be overwritten later */
3176 		break;
3177 	}
3178 	/*
3179 	 * If pkt is to be executed in polling mode and a command will not be
3180 	 * emulated in SATA module (requires sending a non-read/write ATA
3181 	 * command to HBA driver in arbitrary SYNC mode) and we are in the
3182 	 * interrupt context and not in the panic dump, then reject the packet
3183 	 * to avoid a possible interrupt stack overrun or hang caused by
3184 	 * a potentially blocked interrupt.
3185 	 */
3186 	if (((spx->txlt_scsi_pkt->pkt_flags & FLAG_NOINTR) != 0 || flag != 0) &&
3187 	    servicing_interrupt() && !ddi_in_panic()) {
3188 		SATADBG1(SATA_DBG_INTR_CTX, spx->txlt_sata_hba_inst,
3189 		    "sata_scsi_start: rejecting synchronous command because "
3190 		    "of interrupt context\n", NULL);
3191 		return (TRAN_BUSY);
3192 	}
3193 
3194 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3195 	    &spx->txlt_sata_pkt->satapkt_device);
3196 
3197 	/*
3198 	 * If device is in reset condition, reject the packet with
3199 	 * TRAN_BUSY, unless:
3200 	 * 1. system is panicking (dumping)
3201 	 * In such case only one thread is running and there is no way to
3202 	 * process reset.
3203 	 * 2. cfgadm operation is is progress (internal APCTL lock is set)
3204 	 * Some cfgadm operations involve drive commands, so reset condition
3205 	 * needs to be ignored for IOCTL operations.
3206 	 */
3207 	if ((sdinfo->satadrv_event_flags &
3208 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) != 0) {
3209 
3210 		if (!ddi_in_panic() &&
3211 		    ((SATA_CPORT_EVENT_FLAGS(spx->txlt_sata_hba_inst,
3212 		    sata_device.satadev_addr.cport) &
3213 		    SATA_APCTL_LOCK_PORT_BUSY) == 0)) {
3214 			spx->txlt_scsi_pkt->pkt_reason = CMD_INCOMPLETE;
3215 			*reason = CMD_INCOMPLETE;
3216 			SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3217 			    "sata_scsi_start: rejecting command because "
3218 			    "of device reset state\n", NULL);
3219 			return (TRAN_BUSY);
3220 		}
3221 	}
3222 
3223 	/*
3224 	 * Fix the dev_type in the sata_pkt->satapkt_device. It was not set by
3225 	 * sata_scsi_pkt_init() because pkt init had to work also with
3226 	 * non-existing devices.
3227 	 * Now we know that the packet was set-up for a real device, so its
3228 	 * type is known.
3229 	 */
3230 	spx->txlt_sata_pkt->satapkt_device.satadev_type = sdinfo->satadrv_type;
3231 
3232 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags = sata_initial_cmd_flags;
3233 	if ((SATA_CPORT_INFO(spx->txlt_sata_hba_inst,
3234 	    sata_device.satadev_addr.cport)->cport_event_flags &
3235 	    SATA_APCTL_LOCK_PORT_BUSY) != 0) {
3236 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.
3237 		    sata_ignore_dev_reset = B_TRUE;
3238 	}
3239 	/*
3240 	 * At this point the generic translation routine determined that the
3241 	 * scsi packet should be accepted. Packet completion reason may be
3242 	 * changed later when a different completion reason is determined.
3243 	 */
3244 	spx->txlt_scsi_pkt->pkt_reason = CMD_CMPLT;
3245 	*reason = CMD_CMPLT;
3246 
3247 	if ((spx->txlt_scsi_pkt->pkt_flags & FLAG_NOINTR) != 0) {
3248 		/* Synchronous execution */
3249 		spx->txlt_sata_pkt->satapkt_op_mode = SATA_OPMODE_SYNCH |
3250 		    SATA_OPMODE_POLLING;
3251 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.
3252 		    sata_ignore_dev_reset = ddi_in_panic();
3253 	} else {
3254 		/* Asynchronous execution */
3255 		spx->txlt_sata_pkt->satapkt_op_mode = SATA_OPMODE_ASYNCH |
3256 		    SATA_OPMODE_INTERRUPTS;
3257 	}
3258 	/* Convert queuing information */
3259 	if (spx->txlt_scsi_pkt->pkt_flags & FLAG_STAG)
3260 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.sata_queue_stag =
3261 		    B_TRUE;
3262 	else if (spx->txlt_scsi_pkt->pkt_flags &
3263 	    (FLAG_OTAG | FLAG_HTAG | FLAG_HEAD))
3264 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.sata_queue_otag =
3265 		    B_TRUE;
3266 
3267 	/* Always limit pkt time */
3268 	if (spx->txlt_scsi_pkt->pkt_time == 0)
3269 		spx->txlt_sata_pkt->satapkt_time = sata_default_pkt_time;
3270 	else
3271 		/* Pass on scsi_pkt time */
3272 		spx->txlt_sata_pkt->satapkt_time =
3273 		    spx->txlt_scsi_pkt->pkt_time;
3274 
3275 	return (TRAN_ACCEPT);
3276 }
3277 
3278 
3279 /*
3280  * Translate ATA Identify Device data to SCSI Inquiry data.
3281  * This function may be called only for ATA devices.
3282  * This function should not be called for ATAPI devices - they
3283  * respond directly to SCSI Inquiry command.
3284  *
3285  * SATA Identify Device data has to be valid in sata_drive_info.
3286  * Buffer has to accomodate the inquiry length (36 bytes).
3287  *
3288  * This function should be called with a port mutex held.
3289  */
3290 static	void
3291 sata_identdev_to_inquiry(sata_hba_inst_t *sata_hba_inst,
3292     sata_drive_info_t *sdinfo, uint8_t *buf)
3293 {
3294 
3295 	struct scsi_inquiry *inq = (struct scsi_inquiry *)buf;
3296 	struct sata_id *sid = &sdinfo->satadrv_id;
3297 
3298 	/* Start with a nice clean slate */
3299 	bzero((void *)inq, sizeof (struct scsi_inquiry));
3300 
3301 	/*
3302 	 * Rely on the dev_type for setting paripheral qualifier.
3303 	 * Assume that  DTYPE_RODIRECT applies to CD/DVD R/W devices.
3304 	 * It could be that DTYPE_OPTICAL could also qualify in the future.
3305 	 * ATAPI Inquiry may provide more data to the target driver.
3306 	 */
3307 	inq->inq_dtype = sdinfo->satadrv_type == SATA_DTYPE_ATADISK ?
3308 	    DTYPE_DIRECT : DTYPE_RODIRECT; /* DTYPE_UNKNOWN; */
3309 
3310 	/* CFA type device is not a removable media device */
3311 	inq->inq_rmb = ((sid->ai_config != SATA_CFA_TYPE) &&
3312 	    (sid->ai_config & SATA_REM_MEDIA)) ? 1 : 0;
3313 	inq->inq_qual = 0;	/* Device type qualifier (obsolete in SCSI3? */
3314 	inq->inq_iso = 0;	/* ISO version */
3315 	inq->inq_ecma = 0;	/* ECMA version */
3316 	inq->inq_ansi = 3;	/* ANSI version - SCSI 3 */
3317 	inq->inq_aenc = 0;	/* Async event notification cap. */
3318 	inq->inq_trmiop = 0;	/* Supports TERMINATE I/O PROC msg - NO */
3319 	inq->inq_normaca = 0;	/* setting NACA bit supported - NO */
3320 	inq->inq_rdf = RDF_SCSI2; /* Response data format- SPC-3 */
3321 	inq->inq_len = 31;	/* Additional length */
3322 	inq->inq_dualp = 0;	/* dual port device - NO */
3323 	inq->inq_reladdr = 0;	/* Supports relative addressing - NO */
3324 	inq->inq_sync = 0;	/* Supports synchronous data xfers - NO */
3325 	inq->inq_linked = 0;	/* Supports linked commands - NO */
3326 				/*
3327 				 * Queuing support - controller has to
3328 				 * support some sort of command queuing.
3329 				 */
3330 	if (SATA_QDEPTH(sata_hba_inst) > 1)
3331 		inq->inq_cmdque = 1; /* Supports command queueing - YES */
3332 	else
3333 		inq->inq_cmdque = 0; /* Supports command queueing - NO */
3334 	inq->inq_sftre = 0;	/* Supports Soft Reset option - NO ??? */
3335 	inq->inq_wbus32 = 0;	/* Supports 32 bit wide data xfers - NO */
3336 	inq->inq_wbus16 = 0;	/* Supports 16 bit wide data xfers - NO */
3337 
3338 #ifdef	_LITTLE_ENDIAN
3339 	/* Swap text fields to match SCSI format */
3340 	bcopy("ATA     ", inq->inq_vid, 8);		/* Vendor ID */
3341 	swab(sid->ai_model, inq->inq_pid, 16);		/* Product ID */
3342 	if (strncmp(&sid->ai_fw[4], "    ", 4) == 0)
3343 		swab(sid->ai_fw, inq->inq_revision, 4);	/* Revision level */
3344 	else
3345 		swab(&sid->ai_fw[4], inq->inq_revision, 4);	/* Rev. level */
3346 #else	/* _LITTLE_ENDIAN */
3347 	bcopy("ATA     ", inq->inq_vid, 8);		/* Vendor ID */
3348 	bcopy(sid->ai_model, inq->inq_pid, 16);		/* Product ID */
3349 	if (strncmp(&sid->ai_fw[4], "    ", 4) == 0)
3350 		bcopy(sid->ai_fw, inq->inq_revision, 4); /* Revision level */
3351 	else
3352 		bcopy(&sid->ai_fw[4], inq->inq_revision, 4); /* Rev. level */
3353 #endif	/* _LITTLE_ENDIAN */
3354 }
3355 
3356 
3357 /*
3358  * Scsi response set up for invalid command (command not supported)
3359  *
3360  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3361  */
3362 static int
3363 sata_txlt_invalid_command(sata_pkt_txlate_t *spx)
3364 {
3365 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3366 	struct scsi_extended_sense *sense;
3367 
3368 	scsipkt->pkt_reason = CMD_CMPLT;
3369 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3370 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3371 
3372 	*scsipkt->pkt_scbp = STATUS_CHECK;
3373 
3374 	sense = sata_arq_sense(spx);
3375 	sense->es_key = KEY_ILLEGAL_REQUEST;
3376 	sense->es_add_code = SD_SCSI_ASC_INVALID_COMMAND_CODE;
3377 
3378 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3379 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
3380 
3381 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3382 	    scsipkt->pkt_comp != NULL) {
3383 		/* scsi callback required */
3384 		if (servicing_interrupt()) {
3385 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3386 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3387 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
3388 				return (TRAN_BUSY);
3389 			}
3390 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3391 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3392 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
3393 			/* Scheduling the callback failed */
3394 			return (TRAN_BUSY);
3395 		}
3396 	}
3397 	return (TRAN_ACCEPT);
3398 }
3399 
3400 /*
3401  * Scsi response set up for check condition with special sense key
3402  * and additional sense code.
3403  *
3404  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3405  */
3406 static int
3407 sata_txlt_check_condition(sata_pkt_txlate_t *spx, uchar_t key, uchar_t code)
3408 {
3409 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
3410 	int cport = SATA_TXLT_CPORT(spx);
3411 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3412 	struct scsi_extended_sense *sense;
3413 
3414 	mutex_enter(&SATA_CPORT_MUTEX(shi, cport));
3415 	scsipkt->pkt_reason = CMD_CMPLT;
3416 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3417 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3418 
3419 	*scsipkt->pkt_scbp = STATUS_CHECK;
3420 
3421 	sense = sata_arq_sense(spx);
3422 	sense->es_key = key;
3423 	sense->es_add_code = code;
3424 
3425 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
3426 
3427 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3428 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
3429 
3430 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3431 	    scsipkt->pkt_comp != NULL) {
3432 		/* scsi callback required */
3433 		if (servicing_interrupt()) {
3434 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3435 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3436 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
3437 				return (TRAN_BUSY);
3438 			}
3439 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3440 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3441 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
3442 			/* Scheduling the callback failed */
3443 			return (TRAN_BUSY);
3444 		}
3445 	}
3446 	return (TRAN_ACCEPT);
3447 }
3448 
3449 /*
3450  * Scsi response setup for
3451  * emulated non-data command that requires no action/return data
3452  *
3453  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3454  */
3455 static	int
3456 sata_txlt_nodata_cmd_immediate(sata_pkt_txlate_t *spx)
3457 {
3458 	int rval;
3459 	int reason;
3460 
3461 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3462 
3463 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
3464 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3465 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3466 		return (rval);
3467 	}
3468 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3469 
3470 	spx->txlt_scsi_pkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3471 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3472 	spx->txlt_scsi_pkt->pkt_reason = CMD_CMPLT;
3473 	*(spx->txlt_scsi_pkt->pkt_scbp) = STATUS_GOOD;
3474 
3475 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3476 	    "Scsi_pkt completion reason %x\n",
3477 	    spx->txlt_scsi_pkt->pkt_reason);
3478 
3479 	if ((spx->txlt_scsi_pkt->pkt_flags & FLAG_NOINTR) == 0 &&
3480 	    spx->txlt_scsi_pkt->pkt_comp != NULL) {
3481 		/* scsi callback required */
3482 		if (servicing_interrupt()) {
3483 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3484 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3485 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
3486 				return (TRAN_BUSY);
3487 			}
3488 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3489 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3490 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
3491 			/* Scheduling the callback failed */
3492 			return (TRAN_BUSY);
3493 		}
3494 	}
3495 	return (TRAN_ACCEPT);
3496 }
3497 
3498 
3499 /*
3500  * SATA translate command: Inquiry / Identify Device
3501  * Use cached Identify Device data for now, rather than issuing actual
3502  * Device Identify cmd request. If device is detached and re-attached,
3503  * asynchronous event processing should fetch and refresh Identify Device
3504  * data.
3505  * Two VPD pages are supported now:
3506  * Vital Product Data page
3507  * Unit Serial Number page
3508  *
3509  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3510  */
3511 
3512 #define	EVPD			1	/* Extended Vital Product Data flag */
3513 #define	CMDDT			2	/* Command Support Data - Obsolete */
3514 #define	INQUIRY_SUP_VPD_PAGE	0	/* Supported VDP Pages Page COde */
3515 #define	INQUIRY_USN_PAGE	0x80	/* Unit Serial Number Page Code */
3516 #define	INQUIRY_DEV_IDENTIFICATION_PAGE 0x83 /* Not needed yet */
3517 
3518 static int
3519 sata_txlt_inquiry(sata_pkt_txlate_t *spx)
3520 {
3521 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3522 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
3523 	sata_drive_info_t *sdinfo;
3524 	struct scsi_extended_sense *sense;
3525 	int count;
3526 	uint8_t *p;
3527 	int i, j;
3528 	uint8_t page_buf[0xff]; /* Max length */
3529 	int rval, reason;
3530 
3531 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3532 
3533 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
3534 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3535 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3536 		return (rval);
3537 	}
3538 
3539 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3540 	    &spx->txlt_sata_pkt->satapkt_device);
3541 
3542 	ASSERT(sdinfo != NULL);
3543 
3544 	scsipkt->pkt_reason = CMD_CMPLT;
3545 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3546 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3547 
3548 	/* Reject not supported request */
3549 	if (scsipkt->pkt_cdbp[1] & CMDDT) { /* No support for this bit */
3550 		*scsipkt->pkt_scbp = STATUS_CHECK;
3551 		sense = sata_arq_sense(spx);
3552 		sense->es_key = KEY_ILLEGAL_REQUEST;
3553 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
3554 		goto done;
3555 	}
3556 
3557 	/* Valid Inquiry request */
3558 	*scsipkt->pkt_scbp = STATUS_GOOD;
3559 
3560 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
3561 
3562 		/*
3563 		 * Because it is fully emulated command storing data
3564 		 * programatically in the specified buffer, release
3565 		 * preallocated DMA resources before storing data in the buffer,
3566 		 * so no unwanted DMA sync would take place.
3567 		 */
3568 		sata_scsi_dmafree(NULL, scsipkt);
3569 
3570 		if (!(scsipkt->pkt_cdbp[1] & EVPD)) {
3571 			/* Standard Inquiry Data request */
3572 			struct scsi_inquiry inq;
3573 			unsigned int bufsize;
3574 
3575 			sata_identdev_to_inquiry(spx->txlt_sata_hba_inst,
3576 			    sdinfo, (uint8_t *)&inq);
3577 			/* Copy no more than requested */
3578 			count = MIN(bp->b_bcount,
3579 			    sizeof (struct scsi_inquiry));
3580 			bufsize = scsipkt->pkt_cdbp[4];
3581 			bufsize |= scsipkt->pkt_cdbp[3] << 8;
3582 			count = MIN(count, bufsize);
3583 			bcopy(&inq, bp->b_un.b_addr, count);
3584 
3585 			scsipkt->pkt_state |= STATE_XFERRED_DATA;
3586 			scsipkt->pkt_resid = scsipkt->pkt_cdbp[4] > count ?
3587 			    bufsize - count : 0;
3588 		} else {
3589 			/*
3590 			 * peripheral_qualifier = 0;
3591 			 *
3592 			 * We are dealing only with HD and will be
3593 			 * dealing with CD/DVD devices soon
3594 			 */
3595 			uint8_t peripheral_device_type =
3596 			    sdinfo->satadrv_type == SATA_DTYPE_ATADISK ?
3597 			    DTYPE_DIRECT : DTYPE_RODIRECT;
3598 
3599 			switch ((uint_t)scsipkt->pkt_cdbp[2]) {
3600 			case INQUIRY_SUP_VPD_PAGE:
3601 				/*
3602 				 * Request for suported Vital Product Data
3603 				 * pages - assuming only 2 page codes
3604 				 * supported.
3605 				 */
3606 				page_buf[0] = peripheral_device_type;
3607 				page_buf[1] = INQUIRY_SUP_VPD_PAGE;
3608 				page_buf[2] = 0;
3609 				page_buf[3] = 2; /* page length */
3610 				page_buf[4] = INQUIRY_SUP_VPD_PAGE;
3611 				page_buf[5] = INQUIRY_USN_PAGE;
3612 				/* Copy no more than requested */
3613 				count = MIN(bp->b_bcount, 6);
3614 				bcopy(page_buf, bp->b_un.b_addr, count);
3615 				break;
3616 
3617 			case INQUIRY_USN_PAGE:
3618 				/*
3619 				 * Request for Unit Serial Number page.
3620 				 * Set-up the page.
3621 				 */
3622 				page_buf[0] = peripheral_device_type;
3623 				page_buf[1] = INQUIRY_USN_PAGE;
3624 				page_buf[2] = 0;
3625 				/* remaining page length */
3626 				page_buf[3] = SATA_ID_SERIAL_LEN;
3627 
3628 				/*
3629 				 * Copy serial number from Identify Device data
3630 				 * words into the inquiry page and swap bytes
3631 				 * when necessary.
3632 				 */
3633 				p = (uint8_t *)(sdinfo->satadrv_id.ai_drvser);
3634 #ifdef	_LITTLE_ENDIAN
3635 				swab(p, &page_buf[4], SATA_ID_SERIAL_LEN);
3636 #else
3637 				bcopy(p, &page_buf[4], SATA_ID_SERIAL_LEN);
3638 #endif
3639 				/*
3640 				 * Least significant character of the serial
3641 				 * number shall appear as the last byte,
3642 				 * according to SBC-3 spec.
3643 				 * Count trailing spaces to determine the
3644 				 * necessary shift length.
3645 				 */
3646 				p = &page_buf[SATA_ID_SERIAL_LEN + 4 - 1];
3647 				for (j = 0; j < SATA_ID_SERIAL_LEN; j++) {
3648 					if (*(p - j) != '\0' &&
3649 					    *(p - j) != '\040')
3650 						break;
3651 				}
3652 
3653 				/*
3654 				 * Shift SN string right, so that the last
3655 				 * non-blank character would appear in last
3656 				 * byte of SN field in the page.
3657 				 * 'j' is the shift length.
3658 				 */
3659 				for (i = 0;
3660 				    i < (SATA_ID_SERIAL_LEN - j) && j != 0;
3661 				    i++, p--)
3662 					*p = *(p - j);
3663 
3664 				/*
3665 				 * Add leading spaces - same number as the
3666 				 * shift size
3667 				 */
3668 				for (; j > 0; j--)
3669 					page_buf[4 + j - 1] = '\040';
3670 
3671 				count = MIN(bp->b_bcount,
3672 				    SATA_ID_SERIAL_LEN + 4);
3673 				bcopy(page_buf, bp->b_un.b_addr, count);
3674 				break;
3675 
3676 			case INQUIRY_DEV_IDENTIFICATION_PAGE:
3677 				/*
3678 				 * We may want to implement this page, when
3679 				 * identifiers are common for SATA devices
3680 				 * But not now.
3681 				 */
3682 				/*FALLTHROUGH*/
3683 
3684 			default:
3685 				/* Request for unsupported VPD page */
3686 				*scsipkt->pkt_scbp = STATUS_CHECK;
3687 				sense = sata_arq_sense(spx);
3688 				sense->es_key = KEY_ILLEGAL_REQUEST;
3689 				sense->es_add_code =
3690 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
3691 				goto done;
3692 			}
3693 		}
3694 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
3695 		scsipkt->pkt_resid = scsipkt->pkt_cdbp[4] > count ?
3696 		    scsipkt->pkt_cdbp[4] - count : 0;
3697 	}
3698 done:
3699 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3700 
3701 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3702 	    "Scsi_pkt completion reason %x\n",
3703 	    scsipkt->pkt_reason);
3704 
3705 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3706 	    scsipkt->pkt_comp != NULL) {
3707 		/* scsi callback required */
3708 		if (servicing_interrupt()) {
3709 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3710 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3711 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
3712 				return (TRAN_BUSY);
3713 			}
3714 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3715 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3716 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
3717 			/* Scheduling the callback failed */
3718 			return (TRAN_BUSY);
3719 		}
3720 	}
3721 	return (TRAN_ACCEPT);
3722 }
3723 
3724 /*
3725  * SATA translate command: Request Sense.
3726  *
3727  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3728  * At the moment this is an emulated command (ATA version for SATA hard disks).
3729  * May be translated into Check Power Mode command in the future.
3730  *
3731  * Note: There is a mismatch between already implemented Informational
3732  * Exception Mode Select page 0x1C and this function.
3733  * When MRIE bit is set in page 0x1C, Request Sense is supposed to return
3734  * NO SENSE and set additional sense code to the exception code - this is not
3735  * implemented here.
3736  */
3737 static int
3738 sata_txlt_request_sense(sata_pkt_txlate_t *spx)
3739 {
3740 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3741 	struct scsi_extended_sense sense;
3742 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
3743 	sata_drive_info_t *sdinfo;
3744 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
3745 	int rval, reason, power_state = 0;
3746 
3747 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3748 
3749 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
3750 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3751 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3752 		return (rval);
3753 	}
3754 
3755 	scsipkt->pkt_reason = CMD_CMPLT;
3756 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3757 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3758 	*scsipkt->pkt_scbp = STATUS_GOOD;
3759 
3760 	/*
3761 	 * when CONTROL field's NACA bit == 1
3762 	 * return ILLEGAL_REQUEST
3763 	 */
3764 	if (scsipkt->pkt_cdbp[5] & CTL_BYTE_NACA_MASK) {
3765 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3766 		return (sata_txlt_check_condition(spx, KEY_ILLEGAL_REQUEST,
3767 		    SD_SCSI_ASC_CMD_SEQUENCE_ERR));
3768 	}
3769 
3770 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3771 	    &spx->txlt_sata_pkt->satapkt_device);
3772 	ASSERT(sdinfo != NULL);
3773 
3774 	spx->txlt_sata_pkt->satapkt_op_mode |= SATA_OPMODE_SYNCH;
3775 
3776 	sata_build_generic_cmd(scmd, SATAC_CHECK_POWER_MODE);
3777 	scmd->satacmd_flags.sata_copy_out_sec_count_lsb = B_TRUE;
3778 	scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
3779 	if (sata_hba_start(spx, &rval) != 0) {
3780 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3781 		return (rval);
3782 	} else {
3783 		if (scmd->satacmd_error_reg != 0) {
3784 			mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3785 			return (sata_txlt_check_condition(spx, KEY_NO_SENSE,
3786 			    SD_SCSI_ASC_NO_ADD_SENSE));
3787 		}
3788 	}
3789 
3790 	switch (scmd->satacmd_sec_count_lsb) {
3791 	case SATA_PWRMODE_STANDBY: /* device in standby mode */
3792 		if (sdinfo->satadrv_power_level == SATA_POWER_STOPPED)
3793 			power_state = SATA_POWER_STOPPED;
3794 		else {
3795 			power_state = SATA_POWER_STANDBY;
3796 			sdinfo->satadrv_power_level = SATA_POWER_STANDBY;
3797 		}
3798 		break;
3799 	case SATA_PWRMODE_IDLE: /* device in idle mode */
3800 		power_state = SATA_POWER_IDLE;
3801 		sdinfo->satadrv_power_level = SATA_POWER_IDLE;
3802 		break;
3803 	case SATA_PWRMODE_ACTIVE: /* device in active or idle mode */
3804 	default:		  /* 0x40, 0x41 active mode */
3805 		if (sdinfo->satadrv_power_level == SATA_POWER_IDLE)
3806 			power_state = SATA_POWER_IDLE;
3807 		else {
3808 			power_state = SATA_POWER_ACTIVE;
3809 			sdinfo->satadrv_power_level = SATA_POWER_ACTIVE;
3810 		}
3811 		break;
3812 	}
3813 
3814 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3815 
3816 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
3817 		/*
3818 		 * Because it is fully emulated command storing data
3819 		 * programatically in the specified buffer, release
3820 		 * preallocated DMA resources before storing data in the buffer,
3821 		 * so no unwanted DMA sync would take place.
3822 		 */
3823 		int count = MIN(bp->b_bcount,
3824 		    sizeof (struct scsi_extended_sense));
3825 		sata_scsi_dmafree(NULL, scsipkt);
3826 		bzero(&sense, sizeof (struct scsi_extended_sense));
3827 		sense.es_valid = 0;	/* Valid LBA */
3828 		sense.es_class = 7;	/* Response code 0x70 - current err */
3829 		sense.es_key = KEY_NO_SENSE;
3830 		sense.es_add_len = 6;	/* Additional length */
3831 		/* Copy no more than requested */
3832 		bcopy(&sense, bp->b_un.b_addr, count);
3833 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
3834 		scsipkt->pkt_resid = 0;
3835 		switch (power_state) {
3836 		case SATA_POWER_IDLE:
3837 		case SATA_POWER_STANDBY:
3838 			sense.es_add_code =
3839 			    SD_SCSI_ASC_LOW_POWER_CONDITION_ON;
3840 			break;
3841 		case SATA_POWER_STOPPED:
3842 			sense.es_add_code = SD_SCSI_ASC_NO_ADD_SENSE;
3843 			break;
3844 		case SATA_POWER_ACTIVE:
3845 		default:
3846 			break;
3847 		}
3848 	}
3849 
3850 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3851 	    "Scsi_pkt completion reason %x\n",
3852 	    scsipkt->pkt_reason);
3853 
3854 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3855 	    scsipkt->pkt_comp != NULL) {
3856 		/* scsi callback required */
3857 		if (servicing_interrupt()) {
3858 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3859 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3860 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
3861 				return (TRAN_BUSY);
3862 			}
3863 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3864 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3865 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
3866 			/* Scheduling the callback failed */
3867 			return (TRAN_BUSY);
3868 		}
3869 	}
3870 	return (TRAN_ACCEPT);
3871 }
3872 
3873 /*
3874  * SATA translate command: Test Unit Ready
3875  * (ATA version for SATA hard disks).
3876  * It is translated into the Check Power Mode command.
3877  *
3878  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3879  */
3880 static int
3881 sata_txlt_test_unit_ready(sata_pkt_txlate_t *spx)
3882 {
3883 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3884 	struct scsi_extended_sense *sense;
3885 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
3886 	sata_drive_info_t *sdinfo;
3887 	int power_state;
3888 	int rval, reason;
3889 
3890 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3891 
3892 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
3893 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3894 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3895 		return (rval);
3896 	}
3897 
3898 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3899 	    &spx->txlt_sata_pkt->satapkt_device);
3900 	ASSERT(sdinfo != NULL);
3901 
3902 	spx->txlt_sata_pkt->satapkt_op_mode |= SATA_OPMODE_SYNCH;
3903 
3904 	/* send CHECK POWER MODE command */
3905 	sata_build_generic_cmd(scmd, SATAC_CHECK_POWER_MODE);
3906 	scmd->satacmd_flags.sata_copy_out_sec_count_lsb = B_TRUE;
3907 	scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
3908 	if (sata_hba_start(spx, &rval) != 0) {
3909 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3910 		return (rval);
3911 	} else {
3912 		if (scmd->satacmd_error_reg != 0) {
3913 			mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3914 			return (sata_txlt_check_condition(spx, KEY_NOT_READY,
3915 			    SD_SCSI_ASC_LU_NOT_RESPONSE));
3916 		}
3917 	}
3918 
3919 	power_state = scmd->satacmd_sec_count_lsb;
3920 
3921 	/*
3922 	 * return NOT READY when device in STOPPED mode
3923 	 */
3924 	if (power_state == SATA_PWRMODE_STANDBY &&
3925 	    sdinfo->satadrv_power_level == SATA_POWER_STOPPED) {
3926 		*scsipkt->pkt_scbp = STATUS_CHECK;
3927 		sense = sata_arq_sense(spx);
3928 		sense->es_key = KEY_NOT_READY;
3929 		sense->es_add_code = SD_SCSI_ASC_LU_NOT_READY;
3930 	} else {
3931 		/*
3932 		 * For other power mode, return GOOD status
3933 		 */
3934 		*scsipkt->pkt_scbp = STATUS_GOOD;
3935 	}
3936 
3937 	scsipkt->pkt_reason = CMD_CMPLT;
3938 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3939 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3940 
3941 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3942 
3943 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3944 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
3945 
3946 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3947 	    scsipkt->pkt_comp != NULL) {
3948 		/* scsi callback required */
3949 		if (servicing_interrupt()) {
3950 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3951 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3952 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
3953 				return (TRAN_BUSY);
3954 			}
3955 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3956 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3957 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
3958 			/* Scheduling the callback failed */
3959 			return (TRAN_BUSY);
3960 		}
3961 	}
3962 
3963 	return (TRAN_ACCEPT);
3964 }
3965 
3966 /*
3967  * SATA translate command: Start Stop Unit
3968  * Translation depends on a command:
3969  *
3970  * Power condition bits will be supported
3971  * and the power level should be maintained by SATL,
3972  * When SATL received a command, it will check the
3973  * power level firstly, and return the status according
3974  * to SAT2 v2.6 and SAT-2 Standby Modifications
3975  *
3976  * SPC-4/SBC-3      SATL    ATA power condition  SATL      SPC/SBC
3977  * -----------------------------------------------------------------------
3978  * SSU_PC1 Active   <==>     ATA  Active         <==>     SSU:start_bit =1
3979  * SSU_PC2 Idle     <==>     ATA  Idle           <==>     N/A
3980  * SSU_PC3 Standby  <==>     ATA  Standby        <==>     N/A
3981  * SSU_PC4 Stopped  <==>     ATA  Standby        <==>     SSU:start_bit = 0
3982  *
3983  *	Unload Media / NOT SUPPORTED YET
3984  *	Load Media / NOT SUPPROTED YET
3985  *	Immediate bit / NOT SUPPORTED YET (deferred error)
3986  *
3987  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
3988  * appropriate values in scsi_pkt fields.
3989  */
3990 static int
3991 sata_txlt_start_stop_unit(sata_pkt_txlate_t *spx)
3992 {
3993 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3994 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
3995 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
3996 	int cport = SATA_TXLT_CPORT(spx);
3997 	int rval, reason;
3998 	sata_drive_info_t *sdinfo;
3999 	sata_id_t *sata_id;
4000 
4001 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4002 	    "sata_txlt_start_stop_unit: %d\n", scsipkt->pkt_scbp[4] & 1);
4003 
4004 	mutex_enter(&SATA_CPORT_MUTEX(shi, cport));
4005 
4006 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
4007 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
4008 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4009 		return (rval);
4010 	}
4011 
4012 	if (scsipkt->pkt_cdbp[1] & START_STOP_IMMED_MASK) {
4013 		/* IMMED bit - not supported */
4014 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4015 		return (sata_txlt_check_condition(spx, KEY_ILLEGAL_REQUEST,
4016 		    SD_SCSI_ASC_INVALID_FIELD_IN_CDB));
4017 	}
4018 
4019 	spx->txlt_sata_pkt->satapkt_op_mode |= SATA_OPMODE_SYNCH;
4020 	spx->txlt_sata_pkt->satapkt_comp = NULL;
4021 
4022 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
4023 	    &spx->txlt_sata_pkt->satapkt_device);
4024 	ASSERT(sdinfo != NULL);
4025 	sata_id = &sdinfo->satadrv_id;
4026 
4027 	switch ((scsipkt->pkt_cdbp[4] & START_STOP_POWER_COND_MASK) >> 4) {
4028 	case 0:
4029 		if (scsipkt->pkt_cdbp[4] & START_STOP_LOEJ_MASK) {
4030 			/* Load/Unload Media - invalid request */
4031 			goto err_out;
4032 		}
4033 		if (scsipkt->pkt_cdbp[4] & START_STOP_START_MASK) {
4034 			/* Start Unit */
4035 			sata_build_read_verify_cmd(scmd, 1, 5);
4036 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4037 			/* Transfer command to HBA */
4038 			if (sata_hba_start(spx, &rval) != 0) {
4039 				/* Pkt not accepted for execution */
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 			sdinfo->satadrv_power_level = SATA_POWER_ACTIVE;
4048 		} else {
4049 			/* Stop Unit */
4050 			sata_build_generic_cmd(scmd, SATAC_FLUSH_CACHE);
4051 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4052 			if (sata_hba_start(spx, &rval) != 0) {
4053 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4054 				return (rval);
4055 			} else {
4056 				if (scmd->satacmd_error_reg != 0) {
4057 					goto err_out;
4058 				}
4059 			}
4060 			/* ata standby immediate command */
4061 			sata_build_generic_cmd(scmd, SATAC_STANDBY_IM);
4062 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4063 			if (sata_hba_start(spx, &rval) != 0) {
4064 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4065 				return (rval);
4066 			} else {
4067 				if (scmd->satacmd_error_reg != 0) {
4068 					goto err_out;
4069 				}
4070 			}
4071 			sdinfo->satadrv_power_level = SATA_POWER_STOPPED;
4072 		}
4073 		break;
4074 	case 0x1:
4075 		sata_build_generic_cmd(scmd, SATAC_IDLE);
4076 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4077 		if (sata_hba_start(spx, &rval) != 0) {
4078 			mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4079 			return (rval);
4080 		} else {
4081 			if (scmd->satacmd_error_reg != 0) {
4082 				goto err_out;
4083 			}
4084 		}
4085 		sata_build_read_verify_cmd(scmd, 1, 5);
4086 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4087 		/* Transfer command to HBA */
4088 		if (sata_hba_start(spx, &rval) != 0) {
4089 			/* Pkt not accepted for execution */
4090 			mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4091 			return (rval);
4092 		} else {
4093 			if (scmd->satacmd_error_reg != 0) {
4094 				goto err_out;
4095 			}
4096 		}
4097 		sdinfo->satadrv_power_level = SATA_POWER_ACTIVE;
4098 		break;
4099 	case 0x2:
4100 		sata_build_generic_cmd(scmd, SATAC_FLUSH_CACHE);
4101 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4102 		if (!(scsipkt->pkt_cdbp[4] & START_STOP_NOFLUSH_MASK)) {
4103 			if (sata_hba_start(spx, &rval) != 0) {
4104 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4105 				return (rval);
4106 			} else {
4107 				if (scmd->satacmd_error_reg != 0) {
4108 					goto err_out;
4109 				}
4110 			}
4111 		}
4112 		sata_build_generic_cmd(scmd, SATAC_IDLE);
4113 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4114 		if (sata_hba_start(spx, &rval) != 0) {
4115 			mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4116 			return (rval);
4117 		} else {
4118 			if (scmd->satacmd_error_reg != 0) {
4119 				goto err_out;
4120 			}
4121 		}
4122 		if ((scsipkt->pkt_cdbp[3] & START_STOP_MODIFIER_MASK)) {
4123 			/*
4124 			 *  POWER CONDITION MODIFIER bit set
4125 			 *  to 0x1 or larger it will be handled
4126 			 *  on the same way as bit = 0x1
4127 			 */
4128 			if (!(sata_id->ai_cmdset84 &
4129 			    SATA_IDLE_UNLOAD_SUPPORTED)) {
4130 				sdinfo->satadrv_power_level = SATA_POWER_IDLE;
4131 				break;
4132 			}
4133 			sata_build_generic_cmd(scmd, SATAC_IDLE_IM);
4134 			scmd->satacmd_features_reg = 0x44;
4135 			scmd->satacmd_lba_low_lsb = 0x4c;
4136 			scmd->satacmd_lba_mid_lsb = 0x4e;
4137 			scmd->satacmd_lba_high_lsb = 0x55;
4138 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4139 			if (sata_hba_start(spx, &rval) != 0) {
4140 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4141 				return (rval);
4142 			} else {
4143 				if (scmd->satacmd_error_reg != 0) {
4144 					goto err_out;
4145 				}
4146 			}
4147 		}
4148 		sdinfo->satadrv_power_level = SATA_POWER_IDLE;
4149 		break;
4150 	case 0x3:
4151 		sata_build_generic_cmd(scmd, SATAC_FLUSH_CACHE);
4152 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4153 		if (!(scsipkt->pkt_cdbp[4] & START_STOP_NOFLUSH_MASK)) {
4154 			if (sata_hba_start(spx, &rval) != 0) {
4155 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4156 				return (rval);
4157 			} else {
4158 				if (scmd->satacmd_error_reg != 0) {
4159 					goto err_out;
4160 				}
4161 			}
4162 		}
4163 		sata_build_generic_cmd(scmd, SATAC_STANDBY);
4164 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4165 		if (sata_hba_start(spx, &rval) != 0) {
4166 			mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4167 			return (rval);
4168 		} else {
4169 			if (scmd->satacmd_error_reg != 0) {
4170 				goto err_out;
4171 			}
4172 		}
4173 		sdinfo->satadrv_power_level = SATA_POWER_STANDBY;
4174 		break;
4175 	case 0x7:
4176 		sata_build_generic_cmd(scmd, SATAC_CHECK_POWER_MODE);
4177 		scmd->satacmd_flags.sata_copy_out_sec_count_lsb = B_TRUE;
4178 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4179 		if (sata_hba_start(spx, &rval) != 0) {
4180 			mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4181 			return (rval);
4182 		} else {
4183 			if (scmd->satacmd_error_reg != 0) {
4184 				goto err_out;
4185 			}
4186 		}
4187 		switch (scmd->satacmd_sec_count_lsb) {
4188 		case SATA_PWRMODE_STANDBY:
4189 			sata_build_generic_cmd(scmd, SATAC_STANDBY);
4190 			scmd->satacmd_sec_count_msb = sata_get_standby_timer(
4191 			    sdinfo->satadrv_standby_timer);
4192 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
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 			break;
4202 		case SATA_PWRMODE_IDLE:
4203 			sata_build_generic_cmd(scmd, SATAC_IDLE);
4204 			scmd->satacmd_sec_count_msb = sata_get_standby_timer(
4205 			    sdinfo->satadrv_standby_timer);
4206 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4207 			if (sata_hba_start(spx, &rval) != 0) {
4208 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4209 				return (rval);
4210 			} else {
4211 				if (scmd->satacmd_error_reg != 0) {
4212 					goto err_out;
4213 				}
4214 			}
4215 			break;
4216 		case SATA_PWRMODE_ACTIVE_SPINDOWN:
4217 		case SATA_PWRMODE_ACTIVE_SPINUP:
4218 		case SATA_PWRMODE_ACTIVE:
4219 			sata_build_generic_cmd(scmd, SATAC_IDLE);
4220 			scmd->satacmd_sec_count_msb = sata_get_standby_timer(
4221 			    sdinfo->satadrv_standby_timer);
4222 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4223 			if (sata_hba_start(spx, &rval) != 0) {
4224 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4225 				return (rval);
4226 			} else {
4227 				if (scmd->satacmd_error_reg != 0) {
4228 					goto err_out;
4229 				}
4230 			}
4231 			sata_build_read_verify_cmd(scmd, 1, 5);
4232 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4233 			if (sata_hba_start(spx, &rval) != 0) {
4234 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4235 				return (rval);
4236 			} else {
4237 				if (scmd->satacmd_error_reg != 0) {
4238 					goto err_out;
4239 				}
4240 			}
4241 			break;
4242 		default:
4243 			goto err_out;
4244 		}
4245 		break;
4246 	case 0xb:
4247 		if ((sata_get_standby_timer(sdinfo->satadrv_standby_timer) ==
4248 		    0) || (!(sata_id->ai_cap & SATA_STANDBYTIMER))) {
4249 			mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4250 			return (sata_txlt_check_condition(spx,
4251 			    KEY_ILLEGAL_REQUEST,
4252 			    SD_SCSI_ASC_INVALID_FIELD_IN_CDB));
4253 		}
4254 		sata_build_generic_cmd(scmd, SATAC_FLUSH_CACHE);
4255 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4256 		if (!(scsipkt->pkt_cdbp[4] & START_STOP_NOFLUSH_MASK)) {
4257 			if (sata_hba_start(spx, &rval) != 0) {
4258 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4259 				return (rval);
4260 			} else {
4261 				if (scmd->satacmd_error_reg != 0) {
4262 					goto err_out;
4263 				}
4264 			}
4265 			sata_build_generic_cmd(scmd, SATAC_STANDBY_IM);
4266 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4267 			if (sata_hba_start(spx, &rval) != 0) {
4268 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4269 				return (rval);
4270 			} else {
4271 				if (scmd->satacmd_error_reg != 0) {
4272 					goto err_out;
4273 				}
4274 			}
4275 		}
4276 		bzero(sdinfo->satadrv_standby_timer, sizeof (uchar_t) * 4);
4277 		break;
4278 	default:
4279 err_out:
4280 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4281 		return (sata_txlt_check_condition(spx, KEY_ILLEGAL_REQUEST,
4282 		    SD_SCSI_ASC_INVALID_FIELD_IN_CDB));
4283 	}
4284 
4285 	/*
4286 	 * Since it was a synchronous command,
4287 	 * a callback function will be called directly.
4288 	 */
4289 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4290 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4291 	    "synchronous execution status %x\n",
4292 	    spx->txlt_sata_pkt->satapkt_reason);
4293 
4294 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4295 	    scsipkt->pkt_comp != NULL) {
4296 		sata_set_arq_data(spx->txlt_sata_pkt);
4297 		if (servicing_interrupt()) {
4298 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4299 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
4300 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
4301 				return (TRAN_BUSY);
4302 			}
4303 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4304 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
4305 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
4306 			/* Scheduling the callback failed */
4307 			return (TRAN_BUSY);
4308 		}
4309 	}
4310 	else
4311 
4312 		sata_txlt_nodata_cmd_completion(spx->txlt_sata_pkt);
4313 
4314 	return (TRAN_ACCEPT);
4315 
4316 }
4317 
4318 /*
4319  * SATA translate command:  Read Capacity.
4320  * Emulated command for SATA disks.
4321  * Capacity is retrieved from cached Idenifty Device data.
4322  * Identify Device data shows effective disk capacity, not the native
4323  * capacity, which may be limitted by Set Max Address command.
4324  * This is ATA version for SATA hard disks.
4325  *
4326  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
4327  */
4328 static int
4329 sata_txlt_read_capacity(sata_pkt_txlate_t *spx)
4330 {
4331 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
4332 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
4333 	sata_drive_info_t *sdinfo;
4334 	uint64_t val;
4335 	uchar_t *rbuf;
4336 	int rval, reason;
4337 
4338 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4339 	    "sata_txlt_read_capacity: ", NULL);
4340 
4341 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4342 
4343 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
4344 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
4345 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4346 		return (rval);
4347 	}
4348 
4349 	scsipkt->pkt_reason = CMD_CMPLT;
4350 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
4351 	    STATE_SENT_CMD | STATE_GOT_STATUS;
4352 	*scsipkt->pkt_scbp = STATUS_GOOD;
4353 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
4354 		/*
4355 		 * Because it is fully emulated command storing data
4356 		 * programatically in the specified buffer, release
4357 		 * preallocated DMA resources before storing data in the buffer,
4358 		 * so no unwanted DMA sync would take place.
4359 		 */
4360 		sata_scsi_dmafree(NULL, scsipkt);
4361 
4362 		sdinfo = sata_get_device_info(
4363 		    spx->txlt_sata_hba_inst,
4364 		    &spx->txlt_sata_pkt->satapkt_device);
4365 		/* Last logical block address */
4366 		val = sdinfo->satadrv_capacity - 1;
4367 		rbuf = (uchar_t *)bp->b_un.b_addr;
4368 		/* Need to swap endians to match scsi format */
4369 		rbuf[0] = (val >> 24) & 0xff;
4370 		rbuf[1] = (val >> 16) & 0xff;
4371 		rbuf[2] = (val >> 8) & 0xff;
4372 		rbuf[3] = val & 0xff;
4373 		/* block size - always 512 bytes, for now */
4374 		rbuf[4] = 0;
4375 		rbuf[5] = 0;
4376 		rbuf[6] = 0x02;
4377 		rbuf[7] = 0;
4378 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
4379 		scsipkt->pkt_resid = 0;
4380 
4381 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst, "%d\n",
4382 		    sdinfo->satadrv_capacity -1);
4383 	}
4384 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4385 	/*
4386 	 * If a callback was requested, do it now.
4387 	 */
4388 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4389 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
4390 
4391 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4392 	    scsipkt->pkt_comp != NULL) {
4393 		/* scsi callback required */
4394 		if (servicing_interrupt()) {
4395 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4396 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
4397 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
4398 				return (TRAN_BUSY);
4399 			}
4400 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4401 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
4402 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
4403 			/* Scheduling the callback failed */
4404 			return (TRAN_BUSY);
4405 		}
4406 	}
4407 
4408 	return (TRAN_ACCEPT);
4409 }
4410 
4411 /*
4412  * SATA translate command: Mode Sense.
4413  * Translated into appropriate SATA command or emulated.
4414  * Saved Values Page Control (03) are not supported.
4415  *
4416  * NOTE: only caching mode sense page is currently implemented.
4417  *
4418  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
4419  */
4420 
4421 #define	LLBAA	0x10	/* Long LBA Accepted */
4422 
4423 static int
4424 sata_txlt_mode_sense(sata_pkt_txlate_t *spx)
4425 {
4426 	struct scsi_pkt	*scsipkt = spx->txlt_scsi_pkt;
4427 	struct buf	*bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
4428 	sata_drive_info_t *sdinfo;
4429 	sata_id_t *sata_id;
4430 	struct scsi_extended_sense *sense;
4431 	int 		len, bdlen, count, alc_len;
4432 	int		pc;	/* Page Control code */
4433 	uint8_t		*buf;	/* mode sense buffer */
4434 	int		rval, reason;
4435 
4436 	SATADBG2(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4437 	    "sata_txlt_mode_sense, pc %x page code 0x%02x\n",
4438 	    spx->txlt_scsi_pkt->pkt_cdbp[2] >> 6,
4439 	    spx->txlt_scsi_pkt->pkt_cdbp[2] & 0x3f);
4440 
4441 	if (servicing_interrupt()) {
4442 		buf = kmem_zalloc(1024, KM_NOSLEEP);
4443 		if (buf == NULL) {
4444 			return (TRAN_BUSY);
4445 		}
4446 	} else {
4447 		buf = kmem_zalloc(1024, KM_SLEEP);
4448 	}
4449 
4450 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4451 
4452 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
4453 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
4454 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4455 		kmem_free(buf, 1024);
4456 		return (rval);
4457 	}
4458 
4459 	scsipkt->pkt_reason = CMD_CMPLT;
4460 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
4461 	    STATE_SENT_CMD | STATE_GOT_STATUS;
4462 
4463 	pc = scsipkt->pkt_cdbp[2] >> 6;
4464 
4465 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
4466 		/*
4467 		 * Because it is fully emulated command storing data
4468 		 * programatically in the specified buffer, release
4469 		 * preallocated DMA resources before storing data in the buffer,
4470 		 * so no unwanted DMA sync would take place.
4471 		 */
4472 		sata_scsi_dmafree(NULL, scsipkt);
4473 
4474 		len = 0;
4475 		bdlen = 0;
4476 		if (!(scsipkt->pkt_cdbp[1] & 8)) {
4477 			if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SENSE_G1 &&
4478 			    (scsipkt->pkt_cdbp[1] & LLBAA))
4479 				bdlen = 16;
4480 			else
4481 				bdlen = 8;
4482 		}
4483 		/* Build mode parameter header */
4484 		if (spx->txlt_scsi_pkt->pkt_cdbp[0] == SCMD_MODE_SENSE) {
4485 			/* 4-byte mode parameter header */
4486 			buf[len++] = 0;		/* mode data length */
4487 			buf[len++] = 0;		/* medium type */
4488 			buf[len++] = 0;		/* dev-specific param */
4489 			buf[len++] = bdlen;	/* Block Descriptor length */
4490 		} else {
4491 			/* 8-byte mode parameter header */
4492 			buf[len++] = 0;		/* mode data length */
4493 			buf[len++] = 0;
4494 			buf[len++] = 0;		/* medium type */
4495 			buf[len++] = 0;		/* dev-specific param */
4496 			if (bdlen == 16)
4497 				buf[len++] = 1;	/* long lba descriptor */
4498 			else
4499 				buf[len++] = 0;
4500 			buf[len++] = 0;
4501 			buf[len++] = 0;		/* Block Descriptor length */
4502 			buf[len++] = bdlen;
4503 		}
4504 
4505 		sdinfo = sata_get_device_info(
4506 		    spx->txlt_sata_hba_inst,
4507 		    &spx->txlt_sata_pkt->satapkt_device);
4508 
4509 		/* Build block descriptor only if not disabled (DBD) */
4510 		if ((scsipkt->pkt_cdbp[1] & 0x08) == 0) {
4511 			/* Block descriptor - direct-access device format */
4512 			if (bdlen == 8) {
4513 				/* build regular block descriptor */
4514 				buf[len++] =
4515 				    (sdinfo->satadrv_capacity >> 24) & 0xff;
4516 				buf[len++] =
4517 				    (sdinfo->satadrv_capacity >> 16) & 0xff;
4518 				buf[len++] =
4519 				    (sdinfo->satadrv_capacity >> 8) & 0xff;
4520 				buf[len++] = sdinfo->satadrv_capacity & 0xff;
4521 				buf[len++] = 0; /* density code */
4522 				buf[len++] = 0;
4523 				if (sdinfo->satadrv_type ==
4524 				    SATA_DTYPE_ATADISK)
4525 					buf[len++] = 2;
4526 				else
4527 					/* ATAPI */
4528 					buf[len++] = 8;
4529 				buf[len++] = 0;
4530 			} else if (bdlen == 16) {
4531 				/* Long LBA Accepted */
4532 				/* build long lba block descriptor */
4533 #ifndef __lock_lint
4534 				buf[len++] =
4535 				    (sdinfo->satadrv_capacity >> 56) & 0xff;
4536 				buf[len++] =
4537 				    (sdinfo->satadrv_capacity >> 48) & 0xff;
4538 				buf[len++] =
4539 				    (sdinfo->satadrv_capacity >> 40) & 0xff;
4540 				buf[len++] =
4541 				    (sdinfo->satadrv_capacity >> 32) & 0xff;
4542 #endif
4543 				buf[len++] =
4544 				    (sdinfo->satadrv_capacity >> 24) & 0xff;
4545 				buf[len++] =
4546 				    (sdinfo->satadrv_capacity >> 16) & 0xff;
4547 				buf[len++] =
4548 				    (sdinfo->satadrv_capacity >> 8) & 0xff;
4549 				buf[len++] = sdinfo->satadrv_capacity & 0xff;
4550 				buf[len++] = 0;
4551 				buf[len++] = 0; /* density code */
4552 				buf[len++] = 0;
4553 				buf[len++] = 0;
4554 				if (sdinfo->satadrv_type ==
4555 				    SATA_DTYPE_ATADISK)
4556 					buf[len++] = 2;
4557 				else
4558 					/* ATAPI */
4559 					buf[len++] = 8;
4560 				buf[len++] = 0;
4561 			}
4562 		}
4563 
4564 		sata_id = &sdinfo->satadrv_id;
4565 
4566 		/*
4567 		 * Add requested pages.
4568 		 * Page 3 and 4 are obsolete and we are not supporting them.
4569 		 * We deal now with:
4570 		 * caching (read/write cache control).
4571 		 * We should eventually deal with following mode pages:
4572 		 * error recovery  (0x01),
4573 		 * power condition (0x1a),
4574 		 * exception control page (enables SMART) (0x1c),
4575 		 * enclosure management (ses),
4576 		 * protocol-specific port mode (port control).
4577 		 */
4578 		switch (scsipkt->pkt_cdbp[2] & 0x3f) {
4579 		case MODEPAGE_RW_ERRRECOV:
4580 			/* DAD_MODE_ERR_RECOV */
4581 			/* R/W recovery */
4582 			len += sata_build_msense_page_1(sdinfo, pc, buf+len);
4583 			break;
4584 		case MODEPAGE_CACHING:
4585 			/* DAD_MODE_CACHE */
4586 			/* Reject not supported request for saved parameters */
4587 			if (pc == 3) {
4588 				*scsipkt->pkt_scbp = STATUS_CHECK;
4589 				sense = sata_arq_sense(spx);
4590 				sense->es_key = KEY_ILLEGAL_REQUEST;
4591 				sense->es_add_code =
4592 				    SD_SCSI_ASC_SAVING_PARAMS_NOT_SUPPORTED;
4593 				goto done;
4594 			}
4595 
4596 			/* caching */
4597 			len += sata_build_msense_page_8(sdinfo, pc, buf+len);
4598 			break;
4599 		case MODEPAGE_INFO_EXCPT:
4600 			/* exception cntrl */
4601 			if (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED) {
4602 				len += sata_build_msense_page_1c(sdinfo, pc,
4603 				    buf+len);
4604 			}
4605 			else
4606 				goto err;
4607 			break;
4608 		case MODEPAGE_POWER_COND:
4609 			/* DAD_MODE_POWER_COND */
4610 			/* power condition */
4611 			len += sata_build_msense_page_1a(sdinfo, pc, buf+len);
4612 			break;
4613 
4614 		case MODEPAGE_ACOUSTIC_MANAG:
4615 			/* acoustic management */
4616 			len += sata_build_msense_page_30(sdinfo, pc, buf+len);
4617 			break;
4618 		case MODEPAGE_ALLPAGES:
4619 			/* all pages */
4620 			len += sata_build_msense_page_1(sdinfo, pc, buf+len);
4621 			len += sata_build_msense_page_8(sdinfo, pc, buf+len);
4622 			len += sata_build_msense_page_1a(sdinfo, pc, buf+len);
4623 			if (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED) {
4624 				len += sata_build_msense_page_1c(sdinfo, pc,
4625 				    buf+len);
4626 			}
4627 			len += sata_build_msense_page_30(sdinfo, pc, buf+len);
4628 			break;
4629 		default:
4630 		err:
4631 			/* Invalid request */
4632 			*scsipkt->pkt_scbp = STATUS_CHECK;
4633 			sense = sata_arq_sense(spx);
4634 			sense->es_key = KEY_ILLEGAL_REQUEST;
4635 			sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
4636 			goto done;
4637 		}
4638 
4639 		/* fix total mode data length */
4640 		if (spx->txlt_scsi_pkt->pkt_cdbp[0] == SCMD_MODE_SENSE) {
4641 			/* 4-byte mode parameter header */
4642 			buf[0] = len - 1;	/* mode data length */
4643 		} else {
4644 			buf[0] = (len -2) >> 8;
4645 			buf[1] = (len -2) & 0xff;
4646 		}
4647 
4648 
4649 		/* Check allocation length */
4650 		if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SENSE) {
4651 			alc_len = scsipkt->pkt_cdbp[4];
4652 		} else {
4653 			alc_len = scsipkt->pkt_cdbp[7];
4654 			alc_len = (len << 8) | scsipkt->pkt_cdbp[8];
4655 		}
4656 		/*
4657 		 * We do not check for possible parameters truncation
4658 		 * (alc_len < len) assuming that the target driver works
4659 		 * correctly. Just avoiding overrun.
4660 		 * Copy no more than requested and possible, buffer-wise.
4661 		 */
4662 		count = MIN(alc_len, len);
4663 		count = MIN(bp->b_bcount, count);
4664 		bcopy(buf, bp->b_un.b_addr, count);
4665 
4666 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
4667 		scsipkt->pkt_resid = alc_len > count ? alc_len - count : 0;
4668 	}
4669 	*scsipkt->pkt_scbp = STATUS_GOOD;
4670 done:
4671 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4672 	(void) kmem_free(buf, 1024);
4673 
4674 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4675 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
4676 
4677 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4678 	    scsipkt->pkt_comp != NULL) {
4679 		/* scsi callback required */
4680 		if (servicing_interrupt()) {
4681 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4682 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
4683 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
4684 				return (TRAN_BUSY);
4685 			}
4686 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4687 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
4688 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
4689 			/* Scheduling the callback failed */
4690 			return (TRAN_BUSY);
4691 		}
4692 	}
4693 
4694 	return (TRAN_ACCEPT);
4695 }
4696 
4697 
4698 /*
4699  * SATA translate command: Mode Select.
4700  * Translated into appropriate SATA command or emulated.
4701  * Saving parameters is not supported.
4702  * Changing device capacity is not supported (although theoretically
4703  * possible by executing SET FEATURES/SET MAX ADDRESS)
4704  *
4705  * Assumption is that the target driver is working correctly.
4706  *
4707  * More than one SATA command may be executed to perform operations specified
4708  * by mode select pages. The first error terminates further execution.
4709  * Operations performed successully are not backed-up in such case.
4710  *
4711  * NOTE: Implemented pages:
4712  * - caching page
4713  * - informational exception page
4714  * - acoustic management page
4715  * - power condition page
4716  * Caching setup is remembered so it could be re-stored in case of
4717  * an unexpected device reset.
4718  *
4719  * Returns TRAN_XXXX.
4720  * If TRAN_ACCEPT is returned, appropriate values are set in scsi_pkt fields.
4721  */
4722 
4723 static int
4724 sata_txlt_mode_select(sata_pkt_txlate_t *spx)
4725 {
4726 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
4727 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
4728 	struct scsi_extended_sense *sense;
4729 	int len, pagelen, count, pllen;
4730 	uint8_t *buf;	/* mode select buffer */
4731 	int rval, stat, reason;
4732 	uint_t nointr_flag;
4733 	int dmod = 0;
4734 
4735 	SATADBG2(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4736 	    "sata_txlt_mode_select, pc %x page code 0x%02x\n",
4737 	    spx->txlt_scsi_pkt->pkt_cdbp[2] >> 6,
4738 	    spx->txlt_scsi_pkt->pkt_cdbp[2] & 0x3f);
4739 
4740 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4741 
4742 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
4743 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
4744 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4745 		return (rval);
4746 	}
4747 
4748 	rval = TRAN_ACCEPT;
4749 
4750 	scsipkt->pkt_reason = CMD_CMPLT;
4751 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
4752 	    STATE_SENT_CMD | STATE_GOT_STATUS;
4753 	nointr_flag = scsipkt->pkt_flags & FLAG_NOINTR;
4754 
4755 	/* Reject not supported request */
4756 	if (! (scsipkt->pkt_cdbp[1] & 0x10)) { /* No support for PF bit = 0 */
4757 		*scsipkt->pkt_scbp = STATUS_CHECK;
4758 		sense = sata_arq_sense(spx);
4759 		sense->es_key = KEY_ILLEGAL_REQUEST;
4760 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
4761 		goto done;
4762 	}
4763 
4764 	if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SELECT) {
4765 		pllen = scsipkt->pkt_cdbp[4];
4766 	} else {
4767 		pllen = scsipkt->pkt_cdbp[7];
4768 		pllen = (pllen << 8) | scsipkt->pkt_cdbp[7];
4769 	}
4770 
4771 	*scsipkt->pkt_scbp = STATUS_GOOD;	/* Presumed outcome */
4772 
4773 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount && pllen != 0) {
4774 		buf = (uint8_t *)bp->b_un.b_addr;
4775 		count = MIN(bp->b_bcount, pllen);
4776 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
4777 		scsipkt->pkt_resid = 0;
4778 		pllen = count;
4779 
4780 		/*
4781 		 * Check the header to skip the block descriptor(s) - we
4782 		 * do not support setting device capacity.
4783 		 * Existing macros do not recognize long LBA dscriptor,
4784 		 * hence manual calculation.
4785 		 */
4786 		if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SELECT) {
4787 			/* 6-bytes CMD, 4 bytes header */
4788 			if (count <= 4)
4789 				goto done;		/* header only */
4790 			len = buf[3] + 4;
4791 		} else {
4792 			/* 10-bytes CMD, 8 bytes header */
4793 			if (count <= 8)
4794 				goto done;		/* header only */
4795 			len = buf[6];
4796 			len = (len << 8) + buf[7] + 8;
4797 		}
4798 		if (len >= count)
4799 			goto done;	/* header + descriptor(s) only */
4800 
4801 		pllen -= len;		/* remaining data length */
4802 
4803 		/*
4804 		 * We may be executing SATA command and want to execute it
4805 		 * in SYNCH mode, regardless of scsi_pkt setting.
4806 		 * Save scsi_pkt setting and indicate SYNCH mode
4807 		 */
4808 		if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4809 		    scsipkt->pkt_comp != NULL) {
4810 			scsipkt->pkt_flags |= FLAG_NOINTR;
4811 		}
4812 		spx->txlt_sata_pkt->satapkt_op_mode = SATA_OPMODE_SYNCH;
4813 
4814 		/*
4815 		 * len is now the offset to a first mode select page
4816 		 * Process all pages
4817 		 */
4818 		while (pllen > 0) {
4819 			switch ((int)buf[len]) {
4820 			case MODEPAGE_CACHING:
4821 				/* No support for SP (saving) */
4822 				if (scsipkt->pkt_cdbp[1] & 0x01) {
4823 					*scsipkt->pkt_scbp = STATUS_CHECK;
4824 					sense = sata_arq_sense(spx);
4825 					sense->es_key = KEY_ILLEGAL_REQUEST;
4826 					sense->es_add_code =
4827 					    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
4828 					goto done;
4829 				}
4830 				stat = sata_mode_select_page_8(spx,
4831 				    (struct mode_cache_scsi3 *)&buf[len],
4832 				    pllen, &pagelen, &rval, &dmod);
4833 				/*
4834 				 * The pagelen value indicates the number of
4835 				 * parameter bytes already processed.
4836 				 * The rval is the return value from
4837 				 * sata_tran_start().
4838 				 * The stat indicates the overall status of
4839 				 * the operation(s).
4840 				 */
4841 				if (stat != SATA_SUCCESS)
4842 					/*
4843 					 * Page processing did not succeed -
4844 					 * all error info is already set-up,
4845 					 * just return
4846 					 */
4847 					pllen = 0; /* this breaks the loop */
4848 				else {
4849 					len += pagelen;
4850 					pllen -= pagelen;
4851 				}
4852 				break;
4853 
4854 			case MODEPAGE_INFO_EXCPT:
4855 				stat = sata_mode_select_page_1c(spx,
4856 				    (struct mode_info_excpt_page *)&buf[len],
4857 				    pllen, &pagelen, &rval, &dmod);
4858 				/*
4859 				 * The pagelen value indicates the number of
4860 				 * parameter bytes already processed.
4861 				 * The rval is the return value from
4862 				 * sata_tran_start().
4863 				 * The stat indicates the overall status of
4864 				 * the operation(s).
4865 				 */
4866 				if (stat != SATA_SUCCESS)
4867 					/*
4868 					 * Page processing did not succeed -
4869 					 * all error info is already set-up,
4870 					 * just return
4871 					 */
4872 					pllen = 0; /* this breaks the loop */
4873 				else {
4874 					len += pagelen;
4875 					pllen -= pagelen;
4876 				}
4877 				break;
4878 
4879 			case MODEPAGE_ACOUSTIC_MANAG:
4880 				stat = sata_mode_select_page_30(spx,
4881 				    (struct mode_acoustic_management *)
4882 				    &buf[len], pllen, &pagelen, &rval, &dmod);
4883 				/*
4884 				 * The pagelen value indicates the number of
4885 				 * parameter bytes already processed.
4886 				 * The rval is the return value from
4887 				 * sata_tran_start().
4888 				 * The stat indicates the overall status of
4889 				 * the operation(s).
4890 				 */
4891 				if (stat != SATA_SUCCESS)
4892 					/*
4893 					 * Page processing did not succeed -
4894 					 * all error info is already set-up,
4895 					 * just return
4896 					 */
4897 					pllen = 0; /* this breaks the loop */
4898 				else {
4899 					len += pagelen;
4900 					pllen -= pagelen;
4901 				}
4902 
4903 				break;
4904 			case MODEPAGE_POWER_COND:
4905 				stat = sata_mode_select_page_1a(spx,
4906 				    (struct mode_info_power_cond *)&buf[len],
4907 				    pllen, &pagelen, &rval, &dmod);
4908 				/*
4909 				 * The pagelen value indicates the number of
4910 				 * parameter bytes already processed.
4911 				 * The rval is the return value from
4912 				 * sata_tran_start().
4913 				 * The stat indicates the overall status of
4914 				 * the operation(s).
4915 				 */
4916 				if (stat != SATA_SUCCESS)
4917 					/*
4918 					 * Page processing did not succeed -
4919 					 * all error info is already set-up,
4920 					 * just return
4921 					 */
4922 					pllen = 0; /* this breaks the loop */
4923 				else {
4924 					len += pagelen;
4925 					pllen -= pagelen;
4926 				}
4927 				break;
4928 			default:
4929 				*scsipkt->pkt_scbp = STATUS_CHECK;
4930 				sense = sata_arq_sense(spx);
4931 				sense->es_key = KEY_ILLEGAL_REQUEST;
4932 				sense->es_add_code =
4933 				    SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
4934 				goto done;
4935 			}
4936 		}
4937 	}
4938 done:
4939 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4940 	/*
4941 	 * If device parameters were modified, fetch and store the new
4942 	 * Identify Device data. Since port mutex could have been released
4943 	 * for accessing HBA driver, we need to re-check device existence.
4944 	 */
4945 	if (dmod != 0) {
4946 		sata_drive_info_t new_sdinfo, *sdinfo;
4947 		int rv = 0;
4948 
4949 		/*
4950 		 * Following statement has to be changed if this function is
4951 		 * used for devices other than SATA hard disks.
4952 		 */
4953 		new_sdinfo.satadrv_type = SATA_DTYPE_ATADISK;
4954 
4955 		new_sdinfo.satadrv_addr =
4956 		    spx->txlt_sata_pkt->satapkt_device.satadev_addr;
4957 		rv = sata_fetch_device_identify_data(spx->txlt_sata_hba_inst,
4958 		    &new_sdinfo);
4959 
4960 		mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4961 		/*
4962 		 * Since port mutex could have been released when
4963 		 * accessing HBA driver, we need to re-check that the
4964 		 * framework still holds the device info structure.
4965 		 */
4966 		sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
4967 		    &spx->txlt_sata_pkt->satapkt_device);
4968 		if (sdinfo != NULL) {
4969 			/*
4970 			 * Device still has info structure in the
4971 			 * sata framework. Copy newly fetched info
4972 			 */
4973 			if (rv == 0) {
4974 				sdinfo->satadrv_id = new_sdinfo.satadrv_id;
4975 				sata_save_drive_settings(sdinfo);
4976 			} else {
4977 				/*
4978 				 * Could not fetch new data - invalidate
4979 				 * sata_drive_info. That makes device
4980 				 * unusable.
4981 				 */
4982 				sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
4983 				sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
4984 			}
4985 		}
4986 		if (rv != 0 || sdinfo == NULL) {
4987 			/*
4988 			 * This changes the overall mode select completion
4989 			 * reason to a failed one !!!!!
4990 			 */
4991 			*scsipkt->pkt_scbp = STATUS_CHECK;
4992 			sense = sata_arq_sense(spx);
4993 			scsipkt->pkt_reason = CMD_INCOMPLETE;
4994 			rval = TRAN_ACCEPT;
4995 		}
4996 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4997 	}
4998 	/* Restore the scsi pkt flags */
4999 	scsipkt->pkt_flags &= ~FLAG_NOINTR;
5000 	scsipkt->pkt_flags |= nointr_flag;
5001 
5002 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5003 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
5004 
5005 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
5006 	    scsipkt->pkt_comp != NULL) {
5007 		/* scsi callback required */
5008 		if (servicing_interrupt()) {
5009 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
5010 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
5011 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
5012 				return (TRAN_BUSY);
5013 			}
5014 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
5015 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
5016 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
5017 			/* Scheduling the callback failed */
5018 			return (TRAN_BUSY);
5019 		}
5020 	}
5021 
5022 	return (rval);
5023 }
5024 
5025 /*
5026  * Translate command: ATA Pass Through
5027  * Incomplete implementation.  Only supports No-Data, PIO Data-In, and
5028  * PIO Data-Out protocols.  Also supports CK_COND bit.
5029  *
5030  * Mapping of the incoming CDB bytes to the outgoing satacmd bytes is
5031  * described in Table 111 of SAT-2 (Draft 9).
5032  */
5033 static  int
5034 sata_txlt_ata_pass_thru(sata_pkt_txlate_t *spx)
5035 {
5036 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5037 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
5038 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
5039 	int extend;
5040 	uint64_t lba;
5041 	uint16_t feature, sec_count;
5042 	int t_len, synch;
5043 	int rval, reason;
5044 
5045 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
5046 
5047 	rval = sata_txlt_generic_pkt_info(spx, &reason, 1);
5048 	if ((rval != TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
5049 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5050 		return (rval);
5051 	}
5052 
5053 	/* T_DIR bit */
5054 	if (scsipkt->pkt_cdbp[2] & SATL_APT_BM_T_DIR)
5055 		scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
5056 	else
5057 		scmd->satacmd_flags.sata_data_direction = SATA_DIR_WRITE;
5058 
5059 	/* MULTIPLE_COUNT field.  If non-zero, invalid command (for now). */
5060 	if (((scsipkt->pkt_cdbp[1] >> 5) & 0x7) != 0) {
5061 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5062 		return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5063 	}
5064 
5065 	/* OFFLINE field. If non-zero, invalid command (for now). */
5066 	if (((scsipkt->pkt_cdbp[2] >> 6) & 0x3) != 0) {
5067 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5068 		return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5069 	}
5070 
5071 	/* PROTOCOL field */
5072 	switch ((scsipkt->pkt_cdbp[1] >> 1) & 0xf) {
5073 	case SATL_APT_P_HW_RESET:
5074 	case SATL_APT_P_SRST:
5075 	case SATL_APT_P_DMA:
5076 	case SATL_APT_P_DMA_QUEUED:
5077 	case SATL_APT_P_DEV_DIAG:
5078 	case SATL_APT_P_DEV_RESET:
5079 	case SATL_APT_P_UDMA_IN:
5080 	case SATL_APT_P_UDMA_OUT:
5081 	case SATL_APT_P_FPDMA:
5082 	case SATL_APT_P_RET_RESP:
5083 		/* Not yet implemented */
5084 	default:
5085 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5086 		return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5087 
5088 	case SATL_APT_P_NON_DATA:
5089 		scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
5090 		break;
5091 
5092 	case SATL_APT_P_PIO_DATA_IN:
5093 		/* If PROTOCOL disagrees with T_DIR, invalid command */
5094 		if (scmd->satacmd_flags.sata_data_direction == SATA_DIR_WRITE) {
5095 			mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5096 			return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5097 		}
5098 
5099 		/* if there is a buffer, release its DMA resources */
5100 		if ((bp != NULL) && bp->b_un.b_addr && bp->b_bcount) {
5101 			sata_scsi_dmafree(NULL, scsipkt);
5102 		} else {
5103 			/* if there is no buffer, how do you PIO in? */
5104 			mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5105 			return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5106 		}
5107 
5108 		break;
5109 
5110 	case SATL_APT_P_PIO_DATA_OUT:
5111 		/* If PROTOCOL disagrees with T_DIR, invalid command */
5112 		if (scmd->satacmd_flags.sata_data_direction == SATA_DIR_READ) {
5113 			mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5114 			return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5115 		}
5116 
5117 		/* if there is a buffer, release its DMA resources */
5118 		if ((bp != NULL) && bp->b_un.b_addr && bp->b_bcount) {
5119 			sata_scsi_dmafree(NULL, scsipkt);
5120 		} else {
5121 			/* if there is no buffer, how do you PIO out? */
5122 			mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5123 			return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5124 		}
5125 
5126 		break;
5127 	}
5128 
5129 	/* Parse the ATA cmd fields, transfer some straight to the satacmd */
5130 	switch ((uint_t)scsipkt->pkt_cdbp[0]) {
5131 	case SPC3_CMD_ATA_COMMAND_PASS_THROUGH12:
5132 		feature = scsipkt->pkt_cdbp[3];
5133 
5134 		sec_count = scsipkt->pkt_cdbp[4];
5135 
5136 		lba = scsipkt->pkt_cdbp[8] & 0xf;
5137 		lba = (lba << 8) | scsipkt->pkt_cdbp[7];
5138 		lba = (lba << 8) | scsipkt->pkt_cdbp[6];
5139 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5140 
5141 		scmd->satacmd_device_reg = scsipkt->pkt_cdbp[13] & 0xf0;
5142 		scmd->satacmd_cmd_reg = scsipkt->pkt_cdbp[9];
5143 
5144 		break;
5145 
5146 	case SPC3_CMD_ATA_COMMAND_PASS_THROUGH16:
5147 		if (scsipkt->pkt_cdbp[1] & SATL_APT_BM_EXTEND) {
5148 			extend = 1;
5149 
5150 			feature = scsipkt->pkt_cdbp[3];
5151 			feature = (feature << 8) | scsipkt->pkt_cdbp[4];
5152 
5153 			sec_count = scsipkt->pkt_cdbp[5];
5154 			sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[6];
5155 
5156 			lba = scsipkt->pkt_cdbp[11];
5157 			lba = (lba << 8) | scsipkt->pkt_cdbp[12];
5158 			lba = (lba << 8) | scsipkt->pkt_cdbp[9];
5159 			lba = (lba << 8) | scsipkt->pkt_cdbp[10];
5160 			lba = (lba << 8) | scsipkt->pkt_cdbp[7];
5161 			lba = (lba << 8) | scsipkt->pkt_cdbp[8];
5162 
5163 			scmd->satacmd_device_reg = scsipkt->pkt_cdbp[13];
5164 			scmd->satacmd_cmd_reg = scsipkt->pkt_cdbp[14];
5165 		} else {
5166 			feature = scsipkt->pkt_cdbp[3];
5167 
5168 			sec_count = scsipkt->pkt_cdbp[5];
5169 
5170 			lba = scsipkt->pkt_cdbp[13] & 0xf;
5171 			lba = (lba << 8) | scsipkt->pkt_cdbp[12];
5172 			lba = (lba << 8) | scsipkt->pkt_cdbp[10];
5173 			lba = (lba << 8) | scsipkt->pkt_cdbp[8];
5174 
5175 			scmd->satacmd_device_reg = scsipkt->pkt_cdbp[13] &
5176 			    0xf0;
5177 			scmd->satacmd_cmd_reg = scsipkt->pkt_cdbp[14];
5178 		}
5179 
5180 		break;
5181 	}
5182 
5183 	/* CK_COND bit */
5184 	if (scsipkt->pkt_cdbp[2] & SATL_APT_BM_CK_COND) {
5185 		if (extend) {
5186 			scmd->satacmd_flags.sata_copy_out_sec_count_msb = 1;
5187 			scmd->satacmd_flags.sata_copy_out_lba_low_msb = 1;
5188 			scmd->satacmd_flags.sata_copy_out_lba_mid_msb = 1;
5189 			scmd->satacmd_flags.sata_copy_out_lba_high_msb = 1;
5190 		}
5191 
5192 		scmd->satacmd_flags.sata_copy_out_sec_count_lsb = 1;
5193 		scmd->satacmd_flags.sata_copy_out_lba_low_lsb = 1;
5194 		scmd->satacmd_flags.sata_copy_out_lba_mid_lsb = 1;
5195 		scmd->satacmd_flags.sata_copy_out_lba_high_lsb = 1;
5196 		scmd->satacmd_flags.sata_copy_out_device_reg = 1;
5197 		scmd->satacmd_flags.sata_copy_out_error_reg = 1;
5198 	}
5199 
5200 	/* Transfer remaining parsed ATA cmd values to the satacmd */
5201 	if (extend) {
5202 		scmd->satacmd_addr_type = ATA_ADDR_LBA48;
5203 
5204 		scmd->satacmd_features_reg_ext = (feature >> 8) & 0xff;
5205 		scmd->satacmd_sec_count_msb = (sec_count >> 8) & 0xff;
5206 		scmd->satacmd_lba_low_msb = (lba >> 8) & 0xff;
5207 		scmd->satacmd_lba_mid_msb = (lba >> 8) & 0xff;
5208 		scmd->satacmd_lba_high_msb = lba >> 40;
5209 	} else {
5210 		scmd->satacmd_addr_type = ATA_ADDR_LBA28;
5211 
5212 		scmd->satacmd_features_reg_ext = 0;
5213 		scmd->satacmd_sec_count_msb = 0;
5214 		scmd->satacmd_lba_low_msb = 0;
5215 		scmd->satacmd_lba_mid_msb = 0;
5216 		scmd->satacmd_lba_high_msb = 0;
5217 	}
5218 
5219 	scmd->satacmd_features_reg = feature & 0xff;
5220 	scmd->satacmd_sec_count_lsb = sec_count & 0xff;
5221 	scmd->satacmd_lba_low_lsb = lba & 0xff;
5222 	scmd->satacmd_lba_mid_lsb = (lba >> 8) & 0xff;
5223 	scmd->satacmd_lba_high_lsb = (lba >> 16) & 0xff;
5224 
5225 	/* Determine transfer length */
5226 	switch (scsipkt->pkt_cdbp[2] & 0x3) {		/* T_LENGTH field */
5227 	case 1:
5228 		t_len = feature;
5229 		break;
5230 	case 2:
5231 		t_len = sec_count;
5232 		break;
5233 	default:
5234 		t_len = 0;
5235 		break;
5236 	}
5237 
5238 	/* Adjust transfer length for the Byte Block bit */
5239 	if ((scsipkt->pkt_cdbp[2] >> 2) & 1)
5240 		t_len *= SATA_DISK_SECTOR_SIZE;
5241 
5242 	/* Start processing command */
5243 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
5244 		spx->txlt_sata_pkt->satapkt_comp = sata_txlt_apt_completion;
5245 		synch = FALSE;
5246 	} else {
5247 		synch = TRUE;
5248 	}
5249 
5250 	if (sata_hba_start(spx, &rval) != 0) {
5251 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5252 		return (rval);
5253 	}
5254 
5255 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5256 
5257 	if (synch) {
5258 		sata_txlt_apt_completion(spx->txlt_sata_pkt);
5259 	}
5260 
5261 	return (TRAN_ACCEPT);
5262 }
5263 
5264 /*
5265  * Translate command: Log Sense
5266  */
5267 static 	int
5268 sata_txlt_log_sense(sata_pkt_txlate_t *spx)
5269 {
5270 	struct scsi_pkt	*scsipkt = spx->txlt_scsi_pkt;
5271 	struct buf	*bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
5272 	sata_drive_info_t *sdinfo;
5273 	struct scsi_extended_sense *sense;
5274 	int 		len, count, alc_len;
5275 	int		pc;	/* Page Control code */
5276 	int		page_code;	/* Page code */
5277 	uint8_t		*buf;	/* log sense buffer */
5278 	int		rval, reason;
5279 #define	MAX_LOG_SENSE_PAGE_SIZE	512
5280 
5281 	SATADBG2(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5282 	    "sata_txlt_log_sense, pc 0x%x, page code 0x%x\n",
5283 	    spx->txlt_scsi_pkt->pkt_cdbp[2] >> 6,
5284 	    spx->txlt_scsi_pkt->pkt_cdbp[2] & 0x3f);
5285 
5286 	if (servicing_interrupt()) {
5287 		buf = kmem_zalloc(MAX_LOG_SENSE_PAGE_SIZE, KM_NOSLEEP);
5288 		if (buf == NULL) {
5289 			return (TRAN_BUSY);
5290 		}
5291 	} else {
5292 		buf = kmem_zalloc(MAX_LOG_SENSE_PAGE_SIZE, KM_SLEEP);
5293 	}
5294 
5295 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
5296 
5297 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
5298 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
5299 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5300 		kmem_free(buf, MAX_LOG_SENSE_PAGE_SIZE);
5301 		return (rval);
5302 	}
5303 
5304 	scsipkt->pkt_reason = CMD_CMPLT;
5305 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
5306 	    STATE_SENT_CMD | STATE_GOT_STATUS;
5307 
5308 	pc = scsipkt->pkt_cdbp[2] >> 6;
5309 	page_code = scsipkt->pkt_cdbp[2] & 0x3f;
5310 
5311 	/* Reject not supported request for all but cumulative values */
5312 	switch (pc) {
5313 	case PC_CUMULATIVE_VALUES:
5314 		break;
5315 	default:
5316 		*scsipkt->pkt_scbp = STATUS_CHECK;
5317 		sense = sata_arq_sense(spx);
5318 		sense->es_key = KEY_ILLEGAL_REQUEST;
5319 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5320 		goto done;
5321 	}
5322 
5323 	switch (page_code) {
5324 	case PAGE_CODE_GET_SUPPORTED_LOG_PAGES:
5325 	case PAGE_CODE_SELF_TEST_RESULTS:
5326 	case PAGE_CODE_INFORMATION_EXCEPTIONS:
5327 	case PAGE_CODE_SMART_READ_DATA:
5328 	case PAGE_CODE_START_STOP_CYCLE_COUNTER:
5329 		break;
5330 	default:
5331 		*scsipkt->pkt_scbp = STATUS_CHECK;
5332 		sense = sata_arq_sense(spx);
5333 		sense->es_key = KEY_ILLEGAL_REQUEST;
5334 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5335 		goto done;
5336 	}
5337 
5338 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
5339 		/*
5340 		 * Because log sense uses local buffers for data retrieval from
5341 		 * the devices and sets the data programatically in the
5342 		 * original specified buffer, release preallocated DMA
5343 		 * resources before storing data in the original buffer,
5344 		 * so no unwanted DMA sync would take place.
5345 		 */
5346 		sata_id_t *sata_id;
5347 
5348 		sata_scsi_dmafree(NULL, scsipkt);
5349 
5350 		len = 0;
5351 
5352 		/* Build log parameter header */
5353 		buf[len++] = page_code;	/* page code as in the CDB */
5354 		buf[len++] = 0;		/* reserved */
5355 		buf[len++] = 0;		/* Zero out page length for now (MSB) */
5356 		buf[len++] = 0;		/* (LSB) */
5357 
5358 		sdinfo = sata_get_device_info(
5359 		    spx->txlt_sata_hba_inst,
5360 		    &spx->txlt_sata_pkt->satapkt_device);
5361 
5362 		/*
5363 		 * Add requested pages.
5364 		 */
5365 		switch (page_code) {
5366 		case PAGE_CODE_GET_SUPPORTED_LOG_PAGES:
5367 			len = sata_build_lsense_page_0(sdinfo, buf + len);
5368 			break;
5369 		case PAGE_CODE_SELF_TEST_RESULTS:
5370 			sata_id = &sdinfo->satadrv_id;
5371 			if ((! (sata_id->ai_cmdset84 &
5372 			    SATA_SMART_SELF_TEST_SUPPORTED)) ||
5373 			    (! (sata_id->ai_features87 &
5374 			    SATA_SMART_SELF_TEST_SUPPORTED))) {
5375 				*scsipkt->pkt_scbp = STATUS_CHECK;
5376 				sense = sata_arq_sense(spx);
5377 				sense->es_key = KEY_ILLEGAL_REQUEST;
5378 				sense->es_add_code =
5379 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5380 
5381 				goto done;
5382 			}
5383 			len = sata_build_lsense_page_10(sdinfo, buf + len,
5384 			    spx->txlt_sata_hba_inst);
5385 			break;
5386 		case PAGE_CODE_INFORMATION_EXCEPTIONS:
5387 			sata_id = &sdinfo->satadrv_id;
5388 			if (! (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED)) {
5389 				*scsipkt->pkt_scbp = STATUS_CHECK;
5390 				sense = sata_arq_sense(spx);
5391 				sense->es_key = KEY_ILLEGAL_REQUEST;
5392 				sense->es_add_code =
5393 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5394 
5395 				goto done;
5396 			}
5397 			if (! (sata_id->ai_features85 & SATA_SMART_ENABLED)) {
5398 				*scsipkt->pkt_scbp = STATUS_CHECK;
5399 				sense = sata_arq_sense(spx);
5400 				sense->es_key = KEY_ABORTED_COMMAND;
5401 				sense->es_add_code =
5402 				    SCSI_ASC_ATA_DEV_FEAT_NOT_ENABLED;
5403 				sense->es_qual_code =
5404 				    SCSI_ASCQ_ATA_DEV_FEAT_NOT_ENABLED;
5405 
5406 				goto done;
5407 			}
5408 
5409 			len = sata_build_lsense_page_2f(sdinfo, buf + len,
5410 			    spx->txlt_sata_hba_inst);
5411 			break;
5412 		case PAGE_CODE_SMART_READ_DATA:
5413 			sata_id = &sdinfo->satadrv_id;
5414 			if (! (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED)) {
5415 				*scsipkt->pkt_scbp = STATUS_CHECK;
5416 				sense = sata_arq_sense(spx);
5417 				sense->es_key = KEY_ILLEGAL_REQUEST;
5418 				sense->es_add_code =
5419 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5420 
5421 				goto done;
5422 			}
5423 			if (! (sata_id->ai_features85 & SATA_SMART_ENABLED)) {
5424 				*scsipkt->pkt_scbp = STATUS_CHECK;
5425 				sense = sata_arq_sense(spx);
5426 				sense->es_key = KEY_ABORTED_COMMAND;
5427 				sense->es_add_code =
5428 				    SCSI_ASC_ATA_DEV_FEAT_NOT_ENABLED;
5429 				sense->es_qual_code =
5430 				    SCSI_ASCQ_ATA_DEV_FEAT_NOT_ENABLED;
5431 
5432 				goto done;
5433 			}
5434 
5435 			/* This page doesn't include a page header */
5436 			len = sata_build_lsense_page_30(sdinfo, buf,
5437 			    spx->txlt_sata_hba_inst);
5438 			goto no_header;
5439 		case PAGE_CODE_START_STOP_CYCLE_COUNTER:
5440 			sata_id = &sdinfo->satadrv_id;
5441 			if (! (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED)) {
5442 				*scsipkt->pkt_scbp = STATUS_CHECK;
5443 				sense = sata_arq_sense(spx);
5444 				sense->es_key = KEY_ILLEGAL_REQUEST;
5445 				sense->es_add_code =
5446 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5447 
5448 				goto done;
5449 			}
5450 			if (! (sata_id->ai_features85 & SATA_SMART_ENABLED)) {
5451 				*scsipkt->pkt_scbp = STATUS_CHECK;
5452 				sense = sata_arq_sense(spx);
5453 				sense->es_key = KEY_ABORTED_COMMAND;
5454 				sense->es_add_code =
5455 				    SCSI_ASC_ATA_DEV_FEAT_NOT_ENABLED;
5456 				sense->es_qual_code =
5457 				    SCSI_ASCQ_ATA_DEV_FEAT_NOT_ENABLED;
5458 
5459 				goto done;
5460 			}
5461 			len = sata_build_lsense_page_0e(sdinfo, buf, spx);
5462 			goto no_header;
5463 		default:
5464 			/* Invalid request */
5465 			*scsipkt->pkt_scbp = STATUS_CHECK;
5466 			sense = sata_arq_sense(spx);
5467 			sense->es_key = KEY_ILLEGAL_REQUEST;
5468 			sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5469 			goto done;
5470 		}
5471 
5472 		/* set parameter log sense data length */
5473 		buf[2] = len >> 8;	/* log sense length (MSB) */
5474 		buf[3] = len & 0xff;	/* log sense length (LSB) */
5475 
5476 		len += SCSI_LOG_PAGE_HDR_LEN;
5477 		ASSERT(len <= MAX_LOG_SENSE_PAGE_SIZE);
5478 
5479 no_header:
5480 		/* Check allocation length */
5481 		alc_len = scsipkt->pkt_cdbp[7];
5482 		alc_len = (len << 8) | scsipkt->pkt_cdbp[8];
5483 
5484 		/*
5485 		 * We do not check for possible parameters truncation
5486 		 * (alc_len < len) assuming that the target driver works
5487 		 * correctly. Just avoiding overrun.
5488 		 * Copy no more than requested and possible, buffer-wise.
5489 		 */
5490 		count = MIN(alc_len, len);
5491 		count = MIN(bp->b_bcount, count);
5492 		bcopy(buf, bp->b_un.b_addr, count);
5493 
5494 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
5495 		scsipkt->pkt_resid = alc_len > count ? alc_len - count : 0;
5496 	}
5497 	*scsipkt->pkt_scbp = STATUS_GOOD;
5498 done:
5499 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5500 	(void) kmem_free(buf, MAX_LOG_SENSE_PAGE_SIZE);
5501 
5502 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5503 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
5504 
5505 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
5506 	    scsipkt->pkt_comp != NULL) {
5507 		/* scsi callback required */
5508 		if (servicing_interrupt()) {
5509 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
5510 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
5511 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
5512 				return (TRAN_BUSY);
5513 			}
5514 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
5515 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
5516 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
5517 			/* Scheduling the callback failed */
5518 			return (TRAN_BUSY);
5519 		}
5520 	}
5521 
5522 	return (TRAN_ACCEPT);
5523 }
5524 
5525 /*
5526  * Translate command: Log Select
5527  * Not implemented at this time - returns invalid command response.
5528  */
5529 static	int
5530 sata_txlt_log_select(sata_pkt_txlate_t *spx)
5531 {
5532 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5533 	    "sata_txlt_log_select\n", NULL);
5534 
5535 	return (sata_txlt_invalid_command(spx));
5536 }
5537 
5538 
5539 /*
5540  * Translate command: Read (various types).
5541  * Translated into appropriate type of ATA READ command
5542  * for SATA hard disks.
5543  * Both the device capabilities and requested operation mode are
5544  * considered.
5545  *
5546  * Following scsi cdb fields are ignored:
5547  * rdprotect, dpo, fua, fua_nv, group_number.
5548  *
5549  * If SATA_ENABLE_QUEUING flag is set (in the global SATA HBA framework
5550  * enable variable sata_func_enable), the capability of the controller and
5551  * capability of a device are checked and if both support queueing, read
5552  * request will be translated to READ_DMA_QUEUEING or READ_DMA_QUEUEING_EXT
5553  * command rather than plain READ_XXX command.
5554  * If SATA_ENABLE_NCQ flag is set in addition to SATA_ENABLE_QUEUING flag and
5555  * both the controller and device suport such functionality, the read
5556  * request will be translated to READ_FPDMA_QUEUED command.
5557  * In both cases the maximum queue depth is derived as minimum of:
5558  * HBA capability,device capability and sata_max_queue_depth variable setting.
5559  * The value passed to HBA driver is decremented by 1, because only 5 bits are
5560  * used to pass max queue depth value, and the maximum possible queue depth
5561  * is 32.
5562  *
5563  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
5564  * appropriate values in scsi_pkt fields.
5565  */
5566 static int
5567 sata_txlt_read(sata_pkt_txlate_t *spx)
5568 {
5569 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5570 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
5571 	sata_drive_info_t *sdinfo;
5572 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
5573 	int cport = SATA_TXLT_CPORT(spx);
5574 	uint16_t sec_count;
5575 	uint64_t lba;
5576 	int rval, reason;
5577 	int synch;
5578 
5579 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
5580 
5581 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
5582 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
5583 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5584 		return (rval);
5585 	}
5586 
5587 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
5588 	    &spx->txlt_sata_pkt->satapkt_device);
5589 
5590 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
5591 	/*
5592 	 * Extract LBA and sector count from scsi CDB.
5593 	 */
5594 	switch ((uint_t)scsipkt->pkt_cdbp[0]) {
5595 	case SCMD_READ:
5596 		/* 6-byte scsi read cmd : 0x08 */
5597 		lba = (scsipkt->pkt_cdbp[1] & 0x1f);
5598 		lba = (lba << 8) | scsipkt->pkt_cdbp[2];
5599 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5600 		sec_count = scsipkt->pkt_cdbp[4];
5601 		/* sec_count 0 will be interpreted as 256 by a device */
5602 		break;
5603 	case SCMD_READ_G1:
5604 		/* 10-bytes scsi read command : 0x28 */
5605 		lba = scsipkt->pkt_cdbp[2];
5606 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5607 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
5608 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5609 		sec_count = scsipkt->pkt_cdbp[7];
5610 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
5611 		break;
5612 	case SCMD_READ_G5:
5613 		/* 12-bytes scsi read command : 0xA8 */
5614 		lba = scsipkt->pkt_cdbp[2];
5615 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5616 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
5617 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5618 		sec_count = scsipkt->pkt_cdbp[6];
5619 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[7];
5620 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
5621 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[9];
5622 		break;
5623 	case SCMD_READ_G4:
5624 		/* 16-bytes scsi read command : 0x88 */
5625 		lba = scsipkt->pkt_cdbp[2];
5626 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5627 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
5628 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5629 		lba = (lba << 8) | scsipkt->pkt_cdbp[6];
5630 		lba = (lba << 8) | scsipkt->pkt_cdbp[7];
5631 		lba = (lba << 8) | scsipkt->pkt_cdbp[8];
5632 		lba = (lba << 8) | scsipkt->pkt_cdbp[9];
5633 		sec_count = scsipkt->pkt_cdbp[10];
5634 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[11];
5635 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[12];
5636 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[13];
5637 		break;
5638 	default:
5639 		/* Unsupported command */
5640 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5641 		return (sata_txlt_invalid_command(spx));
5642 	}
5643 
5644 	/*
5645 	 * Check if specified address exceeds device capacity
5646 	 */
5647 	if ((lba >= sdinfo->satadrv_capacity) ||
5648 	    ((lba + sec_count) > sdinfo->satadrv_capacity)) {
5649 		/* LBA out of range */
5650 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5651 		return (sata_txlt_lba_out_of_range(spx));
5652 	}
5653 
5654 	/*
5655 	 * For zero-length transfer, emulate good completion of the command
5656 	 * (reasons for rejecting the command were already checked).
5657 	 * No DMA resources were allocated.
5658 	 */
5659 	if (spx->txlt_dma_cookie_list == NULL) {
5660 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5661 		return (sata_emul_rw_completion(spx));
5662 	}
5663 
5664 	/*
5665 	 * Build cmd block depending on the device capability and
5666 	 * requested operation mode.
5667 	 * Do not bother with non-dma mode - we are working only with
5668 	 * devices supporting DMA.
5669 	 */
5670 	scmd->satacmd_addr_type = ATA_ADDR_LBA;
5671 	scmd->satacmd_device_reg = SATA_ADH_LBA;
5672 	scmd->satacmd_cmd_reg = SATAC_READ_DMA;
5673 	if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48) {
5674 		scmd->satacmd_addr_type = ATA_ADDR_LBA48;
5675 		scmd->satacmd_cmd_reg = SATAC_READ_DMA_EXT;
5676 		scmd->satacmd_sec_count_msb = sec_count >> 8;
5677 #ifndef __lock_lint
5678 		scmd->satacmd_lba_low_msb = (lba >> 24) & 0xff;
5679 		scmd->satacmd_lba_mid_msb = (lba >> 32) & 0xff;
5680 		scmd->satacmd_lba_high_msb = lba >> 40;
5681 #endif
5682 	} else if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA28) {
5683 		scmd->satacmd_addr_type = ATA_ADDR_LBA28;
5684 		scmd->satacmd_device_reg = SATA_ADH_LBA | ((lba >> 24) & 0xf);
5685 	}
5686 	scmd->satacmd_sec_count_lsb = sec_count & 0xff;
5687 	scmd->satacmd_lba_low_lsb = lba & 0xff;
5688 	scmd->satacmd_lba_mid_lsb = (lba >> 8) & 0xff;
5689 	scmd->satacmd_lba_high_lsb = (lba >> 16) & 0xff;
5690 	scmd->satacmd_features_reg = 0;
5691 	scmd->satacmd_status_reg = 0;
5692 	scmd->satacmd_error_reg = 0;
5693 
5694 	/*
5695 	 * Check if queueing commands should be used and switch
5696 	 * to appropriate command if possible
5697 	 */
5698 	if (sata_func_enable & SATA_ENABLE_QUEUING) {
5699 		boolean_t using_queuing;
5700 
5701 		/* Queuing supported by controller and device? */
5702 		if ((sata_func_enable & SATA_ENABLE_NCQ) &&
5703 		    (sdinfo->satadrv_features_support &
5704 		    SATA_DEV_F_NCQ) &&
5705 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
5706 		    SATA_CTLF_NCQ)) {
5707 			using_queuing = B_TRUE;
5708 
5709 			/* NCQ supported - use FPDMA READ */
5710 			scmd->satacmd_cmd_reg =
5711 			    SATAC_READ_FPDMA_QUEUED;
5712 			scmd->satacmd_features_reg_ext =
5713 			    scmd->satacmd_sec_count_msb;
5714 			scmd->satacmd_sec_count_msb = 0;
5715 		} else if ((sdinfo->satadrv_features_support &
5716 		    SATA_DEV_F_TCQ) &&
5717 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
5718 		    SATA_CTLF_QCMD)) {
5719 			using_queuing = B_TRUE;
5720 
5721 			/* Legacy queueing */
5722 			if (sdinfo->satadrv_features_support &
5723 			    SATA_DEV_F_LBA48) {
5724 				scmd->satacmd_cmd_reg =
5725 				    SATAC_READ_DMA_QUEUED_EXT;
5726 				scmd->satacmd_features_reg_ext =
5727 				    scmd->satacmd_sec_count_msb;
5728 				scmd->satacmd_sec_count_msb = 0;
5729 			} else {
5730 				scmd->satacmd_cmd_reg =
5731 				    SATAC_READ_DMA_QUEUED;
5732 			}
5733 		} else	/* NCQ nor legacy queuing not supported */
5734 			using_queuing = B_FALSE;
5735 
5736 		/*
5737 		 * If queuing, the sector count goes in the features register
5738 		 * and the secount count will contain the tag.
5739 		 */
5740 		if (using_queuing) {
5741 			scmd->satacmd_features_reg =
5742 			    scmd->satacmd_sec_count_lsb;
5743 			scmd->satacmd_sec_count_lsb = 0;
5744 			scmd->satacmd_flags.sata_queued = B_TRUE;
5745 
5746 			/* Set-up maximum queue depth */
5747 			scmd->satacmd_flags.sata_max_queue_depth =
5748 			    sdinfo->satadrv_max_queue_depth - 1;
5749 		} else if (sdinfo->satadrv_features_enabled &
5750 		    SATA_DEV_F_E_UNTAGGED_QING) {
5751 			/*
5752 			 * Although NCQ/TCQ is not enabled, untagged queuing
5753 			 * may be still used.
5754 			 * Set-up the maximum untagged queue depth.
5755 			 * Use controller's queue depth from sata_hba_tran.
5756 			 * SATA HBA drivers may ignore this value and rely on
5757 			 * the internal limits.For drivers that do not
5758 			 * ignore untaged queue depth, limit the value to
5759 			 * SATA_MAX_QUEUE_DEPTH (32), as this is the
5760 			 * largest value that can be passed via
5761 			 * satacmd_flags.sata_max_queue_depth.
5762 			 */
5763 			scmd->satacmd_flags.sata_max_queue_depth =
5764 			    SATA_QDEPTH(shi) <= SATA_MAX_QUEUE_DEPTH ?
5765 			    SATA_QDEPTH(shi) - 1: SATA_MAX_QUEUE_DEPTH - 1;
5766 
5767 		} else {
5768 			scmd->satacmd_flags.sata_max_queue_depth = 0;
5769 		}
5770 	} else
5771 		scmd->satacmd_flags.sata_max_queue_depth = 0;
5772 
5773 	SATADBG3(SATA_DBG_HBA_IF, spx->txlt_sata_hba_inst,
5774 	    "sata_txlt_read cmd 0x%2x, lba %llx, sec count %x\n",
5775 	    scmd->satacmd_cmd_reg, lba, sec_count);
5776 
5777 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
5778 		/* Need callback function */
5779 		spx->txlt_sata_pkt->satapkt_comp = sata_txlt_rw_completion;
5780 		synch = FALSE;
5781 	} else
5782 		synch = TRUE;
5783 
5784 	/* Transfer command to HBA */
5785 	if (sata_hba_start(spx, &rval) != 0) {
5786 		/* Pkt not accepted for execution */
5787 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
5788 		return (rval);
5789 	}
5790 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
5791 	/*
5792 	 * If execution is non-synchronous,
5793 	 * a callback function will handle potential errors, translate
5794 	 * the response and will do a callback to a target driver.
5795 	 * If it was synchronous, check execution status using the same
5796 	 * framework callback.
5797 	 */
5798 	if (synch) {
5799 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5800 		    "synchronous execution status %x\n",
5801 		    spx->txlt_sata_pkt->satapkt_reason);
5802 		sata_txlt_rw_completion(spx->txlt_sata_pkt);
5803 	}
5804 	return (TRAN_ACCEPT);
5805 }
5806 
5807 
5808 /*
5809  * SATA translate command: Write (various types)
5810  * Translated into appropriate type of ATA WRITE command
5811  * for SATA hard disks.
5812  * Both the device capabilities and requested operation mode are
5813  * considered.
5814  *
5815  * Following scsi cdb fields are ignored:
5816  * rwprotect, dpo, fua, fua_nv, group_number.
5817  *
5818  * If SATA_ENABLE_QUEUING flag is set (in the global SATA HBA framework
5819  * enable variable sata_func_enable), the capability of the controller and
5820  * capability of a device are checked and if both support queueing, write
5821  * request will be translated to WRITE_DMA_QUEUEING or WRITE_DMA_QUEUEING_EXT
5822  * command rather than plain WRITE_XXX command.
5823  * If SATA_ENABLE_NCQ flag is set in addition to SATA_ENABLE_QUEUING flag and
5824  * both the controller and device suport such functionality, the write
5825  * request will be translated to WRITE_FPDMA_QUEUED command.
5826  * In both cases the maximum queue depth is derived as minimum of:
5827  * HBA capability,device capability and sata_max_queue_depth variable setting.
5828  * The value passed to HBA driver is decremented by 1, because only 5 bits are
5829  * used to pass max queue depth value, and the maximum possible queue depth
5830  * is 32.
5831  *
5832  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
5833  * appropriate values in scsi_pkt fields.
5834  */
5835 static int
5836 sata_txlt_write(sata_pkt_txlate_t *spx)
5837 {
5838 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5839 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
5840 	sata_drive_info_t *sdinfo;
5841 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
5842 	int cport = SATA_TXLT_CPORT(spx);
5843 	uint16_t sec_count;
5844 	uint64_t lba;
5845 	int rval, reason;
5846 	int synch;
5847 
5848 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
5849 
5850 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
5851 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
5852 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5853 		return (rval);
5854 	}
5855 
5856 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
5857 	    &spx->txlt_sata_pkt->satapkt_device);
5858 
5859 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_WRITE;
5860 	/*
5861 	 * Extract LBA and sector count from scsi CDB
5862 	 */
5863 	switch ((uint_t)scsipkt->pkt_cdbp[0]) {
5864 	case SCMD_WRITE:
5865 		/* 6-byte scsi read cmd : 0x0A */
5866 		lba = (scsipkt->pkt_cdbp[1] & 0x1f);
5867 		lba = (lba << 8) | scsipkt->pkt_cdbp[2];
5868 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5869 		sec_count = scsipkt->pkt_cdbp[4];
5870 		/* sec_count 0 will be interpreted as 256 by a device */
5871 		break;
5872 	case SCMD_WRITE_G1:
5873 		/* 10-bytes scsi write command : 0x2A */
5874 		lba = scsipkt->pkt_cdbp[2];
5875 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5876 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
5877 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5878 		sec_count = scsipkt->pkt_cdbp[7];
5879 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
5880 		break;
5881 	case SCMD_WRITE_G5:
5882 		/* 12-bytes scsi read command : 0xAA */
5883 		lba = scsipkt->pkt_cdbp[2];
5884 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5885 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
5886 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5887 		sec_count = scsipkt->pkt_cdbp[6];
5888 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[7];
5889 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
5890 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[9];
5891 		break;
5892 	case SCMD_WRITE_G4:
5893 		/* 16-bytes scsi write command : 0x8A */
5894 		lba = scsipkt->pkt_cdbp[2];
5895 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5896 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
5897 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5898 		lba = (lba << 8) | scsipkt->pkt_cdbp[6];
5899 		lba = (lba << 8) | scsipkt->pkt_cdbp[7];
5900 		lba = (lba << 8) | scsipkt->pkt_cdbp[8];
5901 		lba = (lba << 8) | scsipkt->pkt_cdbp[9];
5902 		sec_count = scsipkt->pkt_cdbp[10];
5903 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[11];
5904 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[12];
5905 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[13];
5906 		break;
5907 	default:
5908 		/* Unsupported command */
5909 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5910 		return (sata_txlt_invalid_command(spx));
5911 	}
5912 
5913 	/*
5914 	 * Check if specified address and length exceeds device capacity
5915 	 */
5916 	if ((lba >= sdinfo->satadrv_capacity) ||
5917 	    ((lba + sec_count) > sdinfo->satadrv_capacity)) {
5918 		/* LBA out of range */
5919 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5920 		return (sata_txlt_lba_out_of_range(spx));
5921 	}
5922 
5923 	/*
5924 	 * For zero-length transfer, emulate good completion of the command
5925 	 * (reasons for rejecting the command were already checked).
5926 	 * No DMA resources were allocated.
5927 	 */
5928 	if (spx->txlt_dma_cookie_list == NULL) {
5929 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5930 		return (sata_emul_rw_completion(spx));
5931 	}
5932 
5933 	/*
5934 	 * Build cmd block depending on the device capability and
5935 	 * requested operation mode.
5936 	 * Do not bother with non-dma mode- we are working only with
5937 	 * devices supporting DMA.
5938 	 */
5939 	scmd->satacmd_addr_type = ATA_ADDR_LBA;
5940 	scmd->satacmd_device_reg = SATA_ADH_LBA;
5941 	scmd->satacmd_cmd_reg = SATAC_WRITE_DMA;
5942 	if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48) {
5943 		scmd->satacmd_addr_type = ATA_ADDR_LBA48;
5944 		scmd->satacmd_cmd_reg = SATAC_WRITE_DMA_EXT;
5945 		scmd->satacmd_sec_count_msb = sec_count >> 8;
5946 		scmd->satacmd_lba_low_msb = (lba >> 24) & 0xff;
5947 #ifndef __lock_lint
5948 		scmd->satacmd_lba_mid_msb = (lba >> 32) & 0xff;
5949 		scmd->satacmd_lba_high_msb = lba >> 40;
5950 #endif
5951 	} else if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA28) {
5952 		scmd->satacmd_addr_type = ATA_ADDR_LBA28;
5953 		scmd->satacmd_device_reg = SATA_ADH_LBA | ((lba >> 24) & 0xf);
5954 	}
5955 	scmd->satacmd_sec_count_lsb = sec_count & 0xff;
5956 	scmd->satacmd_lba_low_lsb = lba & 0xff;
5957 	scmd->satacmd_lba_mid_lsb = (lba >> 8) & 0xff;
5958 	scmd->satacmd_lba_high_lsb = (lba >> 16) & 0xff;
5959 	scmd->satacmd_features_reg = 0;
5960 	scmd->satacmd_status_reg = 0;
5961 	scmd->satacmd_error_reg = 0;
5962 
5963 	/*
5964 	 * Check if queueing commands should be used and switch
5965 	 * to appropriate command if possible
5966 	 */
5967 	if (sata_func_enable & SATA_ENABLE_QUEUING) {
5968 		boolean_t using_queuing;
5969 
5970 		/* Queuing supported by controller and device? */
5971 		if ((sata_func_enable & SATA_ENABLE_NCQ) &&
5972 		    (sdinfo->satadrv_features_support &
5973 		    SATA_DEV_F_NCQ) &&
5974 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
5975 		    SATA_CTLF_NCQ)) {
5976 			using_queuing = B_TRUE;
5977 
5978 			/* NCQ supported - use FPDMA WRITE */
5979 			scmd->satacmd_cmd_reg =
5980 			    SATAC_WRITE_FPDMA_QUEUED;
5981 			scmd->satacmd_features_reg_ext =
5982 			    scmd->satacmd_sec_count_msb;
5983 			scmd->satacmd_sec_count_msb = 0;
5984 		} else if ((sdinfo->satadrv_features_support &
5985 		    SATA_DEV_F_TCQ) &&
5986 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
5987 		    SATA_CTLF_QCMD)) {
5988 			using_queuing = B_TRUE;
5989 
5990 			/* Legacy queueing */
5991 			if (sdinfo->satadrv_features_support &
5992 			    SATA_DEV_F_LBA48) {
5993 				scmd->satacmd_cmd_reg =
5994 				    SATAC_WRITE_DMA_QUEUED_EXT;
5995 				scmd->satacmd_features_reg_ext =
5996 				    scmd->satacmd_sec_count_msb;
5997 				scmd->satacmd_sec_count_msb = 0;
5998 			} else {
5999 				scmd->satacmd_cmd_reg =
6000 				    SATAC_WRITE_DMA_QUEUED;
6001 			}
6002 		} else	/*  NCQ nor legacy queuing not supported */
6003 			using_queuing = B_FALSE;
6004 
6005 		if (using_queuing) {
6006 			scmd->satacmd_features_reg =
6007 			    scmd->satacmd_sec_count_lsb;
6008 			scmd->satacmd_sec_count_lsb = 0;
6009 			scmd->satacmd_flags.sata_queued = B_TRUE;
6010 			/* Set-up maximum queue depth */
6011 			scmd->satacmd_flags.sata_max_queue_depth =
6012 			    sdinfo->satadrv_max_queue_depth - 1;
6013 		} else if (sdinfo->satadrv_features_enabled &
6014 		    SATA_DEV_F_E_UNTAGGED_QING) {
6015 			/*
6016 			 * Although NCQ/TCQ is not enabled, untagged queuing
6017 			 * may be still used.
6018 			 * Set-up the maximum untagged queue depth.
6019 			 * Use controller's queue depth from sata_hba_tran.
6020 			 * SATA HBA drivers may ignore this value and rely on
6021 			 * the internal limits. For drivera that do not
6022 			 * ignore untaged queue depth, limit the value to
6023 			 * SATA_MAX_QUEUE_DEPTH (32), as this is the
6024 			 * largest value that can be passed via
6025 			 * satacmd_flags.sata_max_queue_depth.
6026 			 */
6027 			scmd->satacmd_flags.sata_max_queue_depth =
6028 			    SATA_QDEPTH(shi) <= SATA_MAX_QUEUE_DEPTH ?
6029 			    SATA_QDEPTH(shi) - 1: SATA_MAX_QUEUE_DEPTH - 1;
6030 
6031 		} else {
6032 			scmd->satacmd_flags.sata_max_queue_depth = 0;
6033 		}
6034 	} else
6035 		scmd->satacmd_flags.sata_max_queue_depth = 0;
6036 
6037 	SATADBG3(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6038 	    "sata_txlt_write cmd 0x%2x, lba %llx, sec count %x\n",
6039 	    scmd->satacmd_cmd_reg, lba, sec_count);
6040 
6041 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
6042 		/* Need callback function */
6043 		spx->txlt_sata_pkt->satapkt_comp = sata_txlt_rw_completion;
6044 		synch = FALSE;
6045 	} else
6046 		synch = TRUE;
6047 
6048 	/* Transfer command to HBA */
6049 	if (sata_hba_start(spx, &rval) != 0) {
6050 		/* Pkt not accepted for execution */
6051 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
6052 		return (rval);
6053 	}
6054 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
6055 
6056 	/*
6057 	 * If execution is non-synchronous,
6058 	 * a callback function will handle potential errors, translate
6059 	 * the response and will do a callback to a target driver.
6060 	 * If it was synchronous, check execution status using the same
6061 	 * framework callback.
6062 	 */
6063 	if (synch) {
6064 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6065 		    "synchronous execution status %x\n",
6066 		    spx->txlt_sata_pkt->satapkt_reason);
6067 		sata_txlt_rw_completion(spx->txlt_sata_pkt);
6068 	}
6069 	return (TRAN_ACCEPT);
6070 }
6071 
6072 
6073 /*
6074  * Implements SCSI SBC WRITE BUFFER command download microcode option
6075  */
6076 static int
6077 sata_txlt_write_buffer(sata_pkt_txlate_t *spx)
6078 {
6079 #define	WB_DOWNLOAD_MICROCODE_AND_REVERT_MODE			4
6080 #define	WB_DOWNLOAD_MICROCODE_AND_SAVE_MODE			5
6081 
6082 	sata_hba_inst_t *sata_hba_inst = SATA_TXLT_HBA_INST(spx);
6083 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6084 	struct sata_pkt *sata_pkt = spx->txlt_sata_pkt;
6085 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
6086 
6087 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
6088 	struct scsi_extended_sense *sense;
6089 	int rval, mode, sector_count, reason;
6090 	int cport = SATA_TXLT_CPORT(spx);
6091 
6092 	mode = scsipkt->pkt_cdbp[1] & 0x1f;
6093 
6094 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6095 	    "sata_txlt_write_buffer, mode 0x%x\n", mode);
6096 
6097 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
6098 
6099 	if ((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
6100 	    TRAN_ACCEPT) {
6101 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
6102 		return (rval);
6103 	}
6104 
6105 	/* Use synchronous mode */
6106 	spx->txlt_sata_pkt->satapkt_op_mode
6107 	    |= SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
6108 
6109 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_WRITE;
6110 
6111 	scsipkt->pkt_reason = CMD_CMPLT;
6112 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6113 	    STATE_SENT_CMD | STATE_GOT_STATUS;
6114 
6115 	/*
6116 	 * The SCSI to ATA translation specification only calls
6117 	 * for WB_DOWNLOAD_MICROCODE_AND_SAVE_MODE.
6118 	 * WB_DOWNLOAD_MICROC_AND_REVERT_MODE is implemented, but
6119 	 * ATA 8 (draft) got rid of download microcode for temp
6120 	 * and it is even optional for ATA 7, so it may be aborted.
6121 	 * WB_DOWNLOAD_MICROCODE_WITH_OFFSET is not implemented as
6122 	 * it is not specified and the buffer offset for SCSI is a 16-bit
6123 	 * value in bytes, but for ATA it is a 16-bit offset in 512 byte
6124 	 * sectors.  Thus the offset really doesn't buy us anything.
6125 	 * If and when ATA 8 is stabilized and the SCSI to ATA specification
6126 	 * is revised, this can be revisisted.
6127 	 */
6128 	/* Reject not supported request */
6129 	switch (mode) {
6130 	case WB_DOWNLOAD_MICROCODE_AND_REVERT_MODE:
6131 		scmd->satacmd_features_reg = SATA_DOWNLOAD_MCODE_TEMP;
6132 		break;
6133 	case WB_DOWNLOAD_MICROCODE_AND_SAVE_MODE:
6134 		scmd->satacmd_features_reg = SATA_DOWNLOAD_MCODE_SAVE;
6135 		break;
6136 	default:
6137 		goto bad_param;
6138 	}
6139 
6140 	*scsipkt->pkt_scbp = STATUS_GOOD;	/* Presumed outcome */
6141 
6142 	scmd->satacmd_cmd_reg = SATAC_DOWNLOAD_MICROCODE;
6143 	if ((bp->b_bcount % SATA_DISK_SECTOR_SIZE) != 0)
6144 		goto bad_param;
6145 	sector_count = bp->b_bcount / SATA_DISK_SECTOR_SIZE;
6146 	scmd->satacmd_sec_count_lsb = (uint8_t)sector_count;
6147 	scmd->satacmd_lba_low_lsb = ((uint16_t)sector_count) >> 8;
6148 	scmd->satacmd_lba_mid_lsb = 0;
6149 	scmd->satacmd_lba_high_lsb = 0;
6150 	scmd->satacmd_device_reg = 0;
6151 	spx->txlt_sata_pkt->satapkt_comp = NULL;
6152 	scmd->satacmd_addr_type = 0;
6153 
6154 	/* Transfer command to HBA */
6155 	if (sata_hba_start(spx, &rval) != 0) {
6156 		/* Pkt not accepted for execution */
6157 		mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
6158 		return (rval);
6159 	}
6160 
6161 	mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
6162 
6163 	/* Then we need synchronous check the status of the disk */
6164 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6165 	    STATE_SENT_CMD | STATE_XFERRED_DATA | STATE_GOT_STATUS;
6166 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
6167 		scsipkt->pkt_reason = CMD_CMPLT;
6168 
6169 		/* Download commmand succeed, so probe and identify device */
6170 		sata_reidentify_device(spx);
6171 	} else {
6172 		/* Something went wrong, microcode download command failed */
6173 		scsipkt->pkt_reason = CMD_INCOMPLETE;
6174 		*scsipkt->pkt_scbp = STATUS_CHECK;
6175 		sense = sata_arq_sense(spx);
6176 		switch (sata_pkt->satapkt_reason) {
6177 		case SATA_PKT_PORT_ERROR:
6178 			/*
6179 			 * We have no device data. Assume no data transfered.
6180 			 */
6181 			sense->es_key = KEY_HARDWARE_ERROR;
6182 			break;
6183 
6184 		case SATA_PKT_DEV_ERROR:
6185 			if (sata_pkt->satapkt_cmd.satacmd_status_reg &
6186 			    SATA_STATUS_ERR) {
6187 				/*
6188 				 * determine dev error reason from error
6189 				 * reg content
6190 				 */
6191 				sata_decode_device_error(spx, sense);
6192 				break;
6193 			}
6194 			/* No extended sense key - no info available */
6195 			break;
6196 
6197 		case SATA_PKT_TIMEOUT:
6198 			scsipkt->pkt_reason = CMD_TIMEOUT;
6199 			scsipkt->pkt_statistics |=
6200 			    STAT_TIMEOUT | STAT_DEV_RESET;
6201 			/* No extended sense key ? */
6202 			break;
6203 
6204 		case SATA_PKT_ABORTED:
6205 			scsipkt->pkt_reason = CMD_ABORTED;
6206 			scsipkt->pkt_statistics |= STAT_ABORTED;
6207 			/* No extended sense key ? */
6208 			break;
6209 
6210 		case SATA_PKT_RESET:
6211 			/* pkt aborted by an explicit reset from a host */
6212 			scsipkt->pkt_reason = CMD_RESET;
6213 			scsipkt->pkt_statistics |= STAT_DEV_RESET;
6214 			break;
6215 
6216 		default:
6217 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
6218 			    "sata_txlt_nodata_cmd_completion: "
6219 			    "invalid packet completion reason %d",
6220 			    sata_pkt->satapkt_reason));
6221 			scsipkt->pkt_reason = CMD_TRAN_ERR;
6222 			break;
6223 		}
6224 
6225 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6226 		    "scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
6227 
6228 		if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
6229 			/* scsi callback required */
6230 			scsi_hba_pkt_comp(scsipkt);
6231 	}
6232 	return (TRAN_ACCEPT);
6233 
6234 bad_param:
6235 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
6236 	*scsipkt->pkt_scbp = STATUS_CHECK;
6237 	sense = sata_arq_sense(spx);
6238 	sense->es_key = KEY_ILLEGAL_REQUEST;
6239 	sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
6240 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
6241 	    scsipkt->pkt_comp != NULL) {
6242 		/* scsi callback required */
6243 		if (servicing_interrupt()) {
6244 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
6245 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
6246 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
6247 				return (TRAN_BUSY);
6248 			}
6249 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
6250 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
6251 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
6252 			/* Scheduling the callback failed */
6253 			return (TRAN_BUSY);
6254 		}
6255 	}
6256 	return (rval);
6257 }
6258 
6259 /*
6260  * Re-identify device after doing a firmware download.
6261  */
6262 static void
6263 sata_reidentify_device(sata_pkt_txlate_t *spx)
6264 {
6265 #define	DOWNLOAD_WAIT_TIME_SECS	60
6266 #define	DOWNLOAD_WAIT_INTERVAL_SECS	1
6267 	int rval;
6268 	int retry_cnt;
6269 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6270 	sata_hba_inst_t *sata_hba_inst = spx->txlt_sata_hba_inst;
6271 	sata_device_t sata_device = spx->txlt_sata_pkt->satapkt_device;
6272 	sata_drive_info_t *sdinfo;
6273 
6274 	/*
6275 	 * Before returning good status, probe device.
6276 	 * Device probing will get IDENTIFY DEVICE data, if possible.
6277 	 * The assumption is that the new microcode is applied by the
6278 	 * device. It is a caller responsibility to verify this.
6279 	 */
6280 	for (retry_cnt = 0;
6281 	    retry_cnt < DOWNLOAD_WAIT_TIME_SECS / DOWNLOAD_WAIT_INTERVAL_SECS;
6282 	    retry_cnt++) {
6283 		rval = sata_probe_device(sata_hba_inst, &sata_device);
6284 
6285 		if (rval == SATA_SUCCESS) { /* Set default features */
6286 			sdinfo = sata_get_device_info(sata_hba_inst,
6287 			    &sata_device);
6288 			if (sata_initialize_device(sata_hba_inst, sdinfo) !=
6289 			    SATA_SUCCESS) {
6290 				/* retry */
6291 				rval = sata_initialize_device(sata_hba_inst,
6292 				    sdinfo);
6293 				if (rval == SATA_RETRY)
6294 					sata_log(sata_hba_inst, CE_WARN,
6295 					    "SATA device at port %d pmport %d -"
6296 					    " default device features could not"
6297 					    " be set. Device may not operate "
6298 					    "as expected.",
6299 					    sata_device.satadev_addr.cport,
6300 					    sata_device.satadev_addr.pmport);
6301 			}
6302 			if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
6303 				scsi_hba_pkt_comp(scsipkt);
6304 			return;
6305 		} else if (rval == SATA_RETRY) {
6306 			delay(drv_usectohz(1000000 *
6307 			    DOWNLOAD_WAIT_INTERVAL_SECS));
6308 			continue;
6309 		} else	/* failed - no reason to retry */
6310 			break;
6311 	}
6312 
6313 	/*
6314 	 * Something went wrong, device probing failed.
6315 	 */
6316 	SATA_LOG_D((sata_hba_inst, CE_WARN,
6317 	    "Cannot probe device after downloading microcode\n"));
6318 
6319 	/* Reset device to force retrying the probe. */
6320 	(void) (*SATA_RESET_DPORT_FUNC(sata_hba_inst))
6321 	    (SATA_DIP(sata_hba_inst), &sata_device);
6322 
6323 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
6324 		scsi_hba_pkt_comp(scsipkt);
6325 }
6326 
6327 
6328 /*
6329  * Translate command: Synchronize Cache.
6330  * Translates into Flush Cache command for SATA hard disks.
6331  *
6332  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
6333  * appropriate values in scsi_pkt fields.
6334  */
6335 static 	int
6336 sata_txlt_synchronize_cache(sata_pkt_txlate_t *spx)
6337 {
6338 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
6339 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
6340 	int cport = SATA_TXLT_CPORT(spx);
6341 	int rval, reason;
6342 	int synch;
6343 
6344 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
6345 
6346 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
6347 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
6348 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
6349 		return (rval);
6350 	}
6351 
6352 	scmd->satacmd_addr_type = 0;
6353 	scmd->satacmd_cmd_reg = SATAC_FLUSH_CACHE;
6354 	scmd->satacmd_device_reg = 0;
6355 	scmd->satacmd_sec_count_lsb = 0;
6356 	scmd->satacmd_lba_low_lsb = 0;
6357 	scmd->satacmd_lba_mid_lsb = 0;
6358 	scmd->satacmd_lba_high_lsb = 0;
6359 	scmd->satacmd_features_reg = 0;
6360 	scmd->satacmd_status_reg = 0;
6361 	scmd->satacmd_error_reg = 0;
6362 
6363 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6364 	    "sata_txlt_synchronize_cache\n", NULL);
6365 
6366 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
6367 		/* Need to set-up a callback function */
6368 		spx->txlt_sata_pkt->satapkt_comp =
6369 		    sata_txlt_nodata_cmd_completion;
6370 		synch = FALSE;
6371 	} else
6372 		synch = TRUE;
6373 
6374 	/* Transfer command to HBA */
6375 	if (sata_hba_start(spx, &rval) != 0) {
6376 		/* Pkt not accepted for execution */
6377 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
6378 		return (rval);
6379 	}
6380 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
6381 
6382 	/*
6383 	 * If execution non-synchronous, it had to be completed
6384 	 * a callback function will handle potential errors, translate
6385 	 * the response and will do a callback to a target driver.
6386 	 * If it was synchronous, check status, using the same
6387 	 * framework callback.
6388 	 */
6389 	if (synch) {
6390 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6391 		    "synchronous execution status %x\n",
6392 		    spx->txlt_sata_pkt->satapkt_reason);
6393 		sata_txlt_nodata_cmd_completion(spx->txlt_sata_pkt);
6394 	}
6395 	return (TRAN_ACCEPT);
6396 }
6397 
6398 
6399 /*
6400  * Send pkt to SATA HBA driver
6401  *
6402  * This function may be called only if the operation is requested by scsi_pkt,
6403  * i.e. scsi_pkt is not NULL.
6404  *
6405  * This function has to be called with cport mutex held. It does release
6406  * the mutex when it calls HBA driver sata_tran_start function and
6407  * re-acquires it afterwards.
6408  *
6409  * If return value is 0, pkt was accepted, -1 otherwise
6410  * rval is set to appropriate sata_scsi_start return value.
6411  *
6412  * Note 1:If HBA driver returns value other than TRAN_ACCEPT, it should not
6413  * have called the sata_pkt callback function for this packet.
6414  *
6415  * The scsi callback has to be performed by the caller of this routine.
6416  */
6417 static int
6418 sata_hba_start(sata_pkt_txlate_t *spx, int *rval)
6419 {
6420 	int stat;
6421 	uint8_t cport = SATA_TXLT_CPORT(spx);
6422 	uint8_t pmport = SATA_TXLT_PMPORT(spx);
6423 	sata_hba_inst_t *sata_hba_inst = spx->txlt_sata_hba_inst;
6424 	sata_drive_info_t *sdinfo;
6425 	sata_pmult_info_t *pminfo;
6426 	sata_pmport_info_t *pmportinfo = NULL;
6427 	sata_device_t *sata_device = NULL;
6428 	uint8_t cmd;
6429 	struct sata_cmd_flags cmd_flags;
6430 
6431 	ASSERT(spx->txlt_sata_pkt != NULL);
6432 
6433 	ASSERT(mutex_owned(&SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6434 
6435 	sdinfo = sata_get_device_info(sata_hba_inst,
6436 	    &spx->txlt_sata_pkt->satapkt_device);
6437 	ASSERT(sdinfo != NULL);
6438 
6439 	/* Clear device reset state? */
6440 	/* qual should be XXX_DPMPORT, but add XXX_PMPORT in case */
6441 	if (sdinfo->satadrv_addr.qual == SATA_ADDR_DPMPORT ||
6442 	    sdinfo->satadrv_addr.qual == SATA_ADDR_PMPORT) {
6443 
6444 		/*
6445 		 * Get the pmult_info of the its parent port multiplier, all
6446 		 * sub-devices share a common device reset flags on in
6447 		 * pmult_info.
6448 		 */
6449 		pminfo = SATA_PMULT_INFO(sata_hba_inst, cport);
6450 		pmportinfo = pminfo->pmult_dev_port[pmport];
6451 		ASSERT(pminfo != NULL);
6452 		if (pminfo->pmult_event_flags & SATA_EVNT_CLEAR_DEVICE_RESET) {
6453 			spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.
6454 			    sata_clear_dev_reset = B_TRUE;
6455 			pminfo->pmult_event_flags &=
6456 			    ~SATA_EVNT_CLEAR_DEVICE_RESET;
6457 			SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
6458 			    "sata_hba_start: clearing device reset state"
6459 			    "on pmult.\n", NULL);
6460 		}
6461 	} else {
6462 		if (sdinfo->satadrv_event_flags &
6463 		    SATA_EVNT_CLEAR_DEVICE_RESET) {
6464 			spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.
6465 			    sata_clear_dev_reset = B_TRUE;
6466 			sdinfo->satadrv_event_flags &=
6467 			    ~SATA_EVNT_CLEAR_DEVICE_RESET;
6468 			SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
6469 			    "sata_hba_start: clearing device reset state\n",
6470 			    NULL);
6471 		}
6472 	}
6473 
6474 	cmd = spx->txlt_sata_pkt->satapkt_cmd.satacmd_cmd_reg;
6475 	cmd_flags = spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags;
6476 	sata_device = &spx->txlt_sata_pkt->satapkt_device;
6477 
6478 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6479 
6480 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6481 	    "Sata cmd 0x%2x\n", cmd);
6482 
6483 	stat = (*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst),
6484 	    spx->txlt_sata_pkt);
6485 
6486 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6487 	/*
6488 	 * If sata pkt was accepted and executed in asynchronous mode, i.e.
6489 	 * with the sata callback, the sata_pkt could be already destroyed
6490 	 * by the time we check ther return status from the hba_start()
6491 	 * function, because sata_scsi_destroy_pkt() could have been already
6492 	 * called (perhaps in the interrupt context). So, in such case, there
6493 	 * should be no references to it. In other cases, sata_pkt still
6494 	 * exists.
6495 	 */
6496 	if (stat == SATA_TRAN_ACCEPTED) {
6497 		/*
6498 		 * pkt accepted for execution.
6499 		 * If it was executed synchronously, it is already completed
6500 		 * and pkt completion_reason indicates completion status.
6501 		 */
6502 		*rval = TRAN_ACCEPT;
6503 		return (0);
6504 	}
6505 
6506 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
6507 	switch (stat) {
6508 	case SATA_TRAN_QUEUE_FULL:
6509 		/*
6510 		 * Controller detected queue full condition.
6511 		 */
6512 		SATADBG1(SATA_DBG_HBA_IF, sata_hba_inst,
6513 		    "sata_hba_start: queue full\n", NULL);
6514 
6515 		spx->txlt_scsi_pkt->pkt_reason = CMD_INCOMPLETE;
6516 		*spx->txlt_scsi_pkt->pkt_scbp = STATUS_QFULL;
6517 
6518 		*rval = TRAN_BUSY;
6519 		break;
6520 
6521 	case SATA_TRAN_PORT_ERROR:
6522 		/*
6523 		 * Communication/link with device or general port error
6524 		 * detected before pkt execution begun.
6525 		 */
6526 		if (spx->txlt_sata_pkt->satapkt_device.satadev_addr.qual ==
6527 		    SATA_ADDR_CPORT ||
6528 		    spx->txlt_sata_pkt->satapkt_device.satadev_addr.qual ==
6529 		    SATA_ADDR_DCPORT)
6530 			sata_log(sata_hba_inst, CE_CONT,
6531 			    "SATA port %d error",
6532 			    sata_device->satadev_addr.cport);
6533 		else
6534 			sata_log(sata_hba_inst, CE_CONT,
6535 			    "SATA port %d:%d error\n",
6536 			    sata_device->satadev_addr.cport,
6537 			    sata_device->satadev_addr.pmport);
6538 
6539 		/*
6540 		 * Update the port/device structure.
6541 		 * sata_pkt should be still valid. Since port error is
6542 		 * returned, sata_device content should reflect port
6543 		 * state - it means, that sata address have been changed,
6544 		 * because original packet's sata address refered to a device
6545 		 * attached to some port.
6546 		 */
6547 		if (sata_device->satadev_addr.qual == SATA_ADDR_DPMPORT ||
6548 		    sata_device->satadev_addr.qual == SATA_ADDR_PMPORT) {
6549 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6550 			mutex_enter(&pmportinfo->pmport_mutex);
6551 			sata_update_pmport_info(sata_hba_inst, sata_device);
6552 			mutex_exit(&pmportinfo->pmport_mutex);
6553 			mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6554 		} else {
6555 			sata_update_port_info(sata_hba_inst, sata_device);
6556 		}
6557 
6558 		spx->txlt_scsi_pkt->pkt_reason = CMD_TRAN_ERR;
6559 		*rval = TRAN_FATAL_ERROR;
6560 		break;
6561 
6562 	case SATA_TRAN_CMD_UNSUPPORTED:
6563 		/*
6564 		 * Command rejected by HBA as unsupported. It was HBA driver
6565 		 * that rejected the command, command was not sent to
6566 		 * an attached device.
6567 		 */
6568 		if ((sdinfo != NULL) &&
6569 		    (sdinfo->satadrv_state & SATA_DSTATE_RESET))
6570 			SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
6571 			    "sat_hba_start: cmd 0x%2x rejected "
6572 			    "with SATA_TRAN_CMD_UNSUPPORTED status\n", cmd);
6573 
6574 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6575 		(void) sata_txlt_invalid_command(spx);
6576 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6577 
6578 		*rval = TRAN_ACCEPT;
6579 		break;
6580 
6581 	case SATA_TRAN_BUSY:
6582 		/*
6583 		 * Command rejected by HBA because other operation prevents
6584 		 * accepting the packet, or device is in RESET condition.
6585 		 */
6586 		if (sdinfo != NULL) {
6587 			sdinfo->satadrv_state =
6588 			    spx->txlt_sata_pkt->satapkt_device.satadev_state;
6589 
6590 			if (sdinfo->satadrv_state & SATA_DSTATE_RESET) {
6591 				SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
6592 				    "sata_hba_start: cmd 0x%2x rejected "
6593 				    "because of device reset condition\n",
6594 				    cmd);
6595 			} else {
6596 				SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
6597 				    "sata_hba_start: cmd 0x%2x rejected "
6598 				    "with SATA_TRAN_BUSY status\n",
6599 				    cmd);
6600 			}
6601 		}
6602 		spx->txlt_scsi_pkt->pkt_reason = CMD_INCOMPLETE;
6603 		*rval = TRAN_BUSY;
6604 		break;
6605 
6606 	default:
6607 		/* Unrecognized HBA response */
6608 		SATA_LOG_D((sata_hba_inst, CE_WARN,
6609 		    "sata_hba_start: unrecognized HBA response "
6610 		    "to cmd : 0x%2x resp 0x%x", cmd, rval));
6611 		spx->txlt_scsi_pkt->pkt_reason = CMD_TRAN_ERR;
6612 		*rval = TRAN_FATAL_ERROR;
6613 		break;
6614 	}
6615 
6616 	/*
6617 	 * If we got here, the packet was rejected.
6618 	 * Check if we need to remember reset state clearing request
6619 	 */
6620 	if (cmd_flags.sata_clear_dev_reset) {
6621 		/*
6622 		 * Check if device is still configured - it may have
6623 		 * disapeared from the configuration
6624 		 */
6625 		sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
6626 		if (sdinfo != NULL) {
6627 			/*
6628 			 * Restore the flag that requests clearing of
6629 			 * the device reset state,
6630 			 * so the next sata packet may carry it to HBA.
6631 			 */
6632 			if (sdinfo->satadrv_addr.qual == SATA_ADDR_PMPORT ||
6633 			    sdinfo->satadrv_addr.qual == SATA_ADDR_DPMPORT) {
6634 				pminfo->pmult_event_flags |=
6635 				    SATA_EVNT_CLEAR_DEVICE_RESET;
6636 			} else {
6637 				sdinfo->satadrv_event_flags |=
6638 				    SATA_EVNT_CLEAR_DEVICE_RESET;
6639 			}
6640 		}
6641 	}
6642 	return (-1);
6643 }
6644 
6645 /*
6646  * Scsi response setup for invalid LBA
6647  *
6648  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
6649  */
6650 static int
6651 sata_txlt_lba_out_of_range(sata_pkt_txlate_t *spx)
6652 {
6653 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6654 	struct scsi_extended_sense *sense;
6655 
6656 	scsipkt->pkt_reason = CMD_CMPLT;
6657 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6658 	    STATE_SENT_CMD | STATE_GOT_STATUS;
6659 	*scsipkt->pkt_scbp = STATUS_CHECK;
6660 
6661 	*scsipkt->pkt_scbp = STATUS_CHECK;
6662 	sense = sata_arq_sense(spx);
6663 	sense->es_key = KEY_ILLEGAL_REQUEST;
6664 	sense->es_add_code = SD_SCSI_ASC_LBA_OUT_OF_RANGE;
6665 
6666 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6667 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
6668 
6669 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
6670 	    scsipkt->pkt_comp != NULL) {
6671 		/* scsi callback required */
6672 		if (servicing_interrupt()) {
6673 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
6674 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
6675 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
6676 				return (TRAN_BUSY);
6677 			}
6678 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
6679 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
6680 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
6681 			/* Scheduling the callback failed */
6682 			return (TRAN_BUSY);
6683 		}
6684 	}
6685 	return (TRAN_ACCEPT);
6686 }
6687 
6688 
6689 /*
6690  * Analyze device status and error registers and translate them into
6691  * appropriate scsi sense codes.
6692  * NOTE: non-packet commands only for now
6693  */
6694 static void
6695 sata_decode_device_error(sata_pkt_txlate_t *spx,
6696     struct scsi_extended_sense *sense)
6697 {
6698 	uint8_t err_reg = spx->txlt_sata_pkt->satapkt_cmd.satacmd_error_reg;
6699 
6700 	ASSERT(sense != NULL);
6701 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_status_reg &
6702 	    SATA_STATUS_ERR);
6703 
6704 
6705 	if (err_reg & SATA_ERROR_ICRC) {
6706 		sense->es_key = KEY_ABORTED_COMMAND;
6707 		sense->es_add_code = 0x08; /* Communication failure */
6708 		return;
6709 	}
6710 
6711 	if (err_reg & SATA_ERROR_UNC) {
6712 		sense->es_key = KEY_MEDIUM_ERROR;
6713 		/* Information bytes (LBA) need to be set by a caller */
6714 		return;
6715 	}
6716 
6717 	/* ADD HERE: MC error bit handling for ATAPI CD/DVD */
6718 	if (err_reg & (SATA_ERROR_MCR | SATA_ERROR_NM)) {
6719 		sense->es_key = KEY_UNIT_ATTENTION;
6720 		sense->es_add_code = 0x3a; /* No media present */
6721 		return;
6722 	}
6723 
6724 	if (err_reg & SATA_ERROR_IDNF) {
6725 		if (err_reg & SATA_ERROR_ABORT) {
6726 			sense->es_key = KEY_ABORTED_COMMAND;
6727 		} else {
6728 			sense->es_key = KEY_ILLEGAL_REQUEST;
6729 			sense->es_add_code = 0x21; /* LBA out of range */
6730 		}
6731 		return;
6732 	}
6733 
6734 	if (err_reg & SATA_ERROR_ABORT) {
6735 		ASSERT(spx->txlt_sata_pkt != NULL);
6736 		sense->es_key = KEY_ABORTED_COMMAND;
6737 		return;
6738 	}
6739 }
6740 
6741 /*
6742  * Extract error LBA from sata_pkt.satapkt_cmd register fields
6743  */
6744 static void
6745 sata_extract_error_lba(sata_pkt_txlate_t *spx, uint64_t *lba)
6746 {
6747 	sata_cmd_t *sata_cmd = &spx->txlt_sata_pkt->satapkt_cmd;
6748 
6749 	*lba = 0;
6750 	if (sata_cmd->satacmd_addr_type == ATA_ADDR_LBA48) {
6751 		*lba = sata_cmd->satacmd_lba_high_msb;
6752 		*lba = (*lba << 8) | sata_cmd->satacmd_lba_mid_msb;
6753 		*lba = (*lba << 8) | sata_cmd->satacmd_lba_low_msb;
6754 	} else if (sata_cmd->satacmd_addr_type == ATA_ADDR_LBA28) {
6755 		*lba = sata_cmd->satacmd_device_reg & 0xf;
6756 	}
6757 	*lba = (*lba << 8) | sata_cmd->satacmd_lba_high_lsb;
6758 	*lba = (*lba << 8) | sata_cmd->satacmd_lba_mid_lsb;
6759 	*lba = (*lba << 8) | sata_cmd->satacmd_lba_low_lsb;
6760 }
6761 
6762 /*
6763  * This is fixed sense format - if LBA exceeds the info field size,
6764  * no valid info will be returned (valid bit in extended sense will
6765  * be set to 0).
6766  */
6767 static struct scsi_extended_sense *
6768 sata_arq_sense(sata_pkt_txlate_t *spx)
6769 {
6770 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6771 	struct scsi_arq_status *arqs;
6772 	struct scsi_extended_sense *sense;
6773 
6774 	/* Fill ARQ sense data */
6775 	scsipkt->pkt_state |= STATE_ARQ_DONE;
6776 	arqs = (struct scsi_arq_status *)scsipkt->pkt_scbp;
6777 	*(uchar_t *)&arqs->sts_status = STATUS_CHECK;
6778 	*(uchar_t *)&arqs->sts_rqpkt_status = STATUS_GOOD;
6779 	arqs->sts_rqpkt_reason = CMD_CMPLT;
6780 	arqs->sts_rqpkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6781 	    STATE_XFERRED_DATA | STATE_SENT_CMD | STATE_GOT_STATUS;
6782 	arqs->sts_rqpkt_resid = 0;
6783 	sense = &arqs->sts_sensedata;
6784 	bzero(sense, sizeof (struct scsi_extended_sense));
6785 	sata_fixed_sense_data_preset(sense);
6786 	return (sense);
6787 }
6788 
6789 /*
6790  * ATA Pass Through support
6791  * Sets flags indicating that an invalid value was found in some
6792  * field in the command.  It could be something illegal according to
6793  * the SAT-2 spec or it could be a feature that is not (yet?)
6794  * supported.
6795  */
6796 static int
6797 sata_txlt_ata_pass_thru_illegal_cmd(sata_pkt_txlate_t *spx)
6798 {
6799 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6800 	struct scsi_extended_sense *sense = sata_arq_sense(spx);
6801 
6802 	scsipkt->pkt_reason = CMD_CMPLT;
6803 	*scsipkt->pkt_scbp = STATUS_CHECK;
6804 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6805 	    STATE_SENT_CMD | STATE_GOT_STATUS;
6806 
6807 	sense = sata_arq_sense(spx);
6808 	sense->es_key = KEY_ILLEGAL_REQUEST;
6809 	sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
6810 
6811 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
6812 	    scsipkt->pkt_comp != NULL) {
6813 		/* scsi callback required */
6814 		if (servicing_interrupt()) {
6815 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
6816 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
6817 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
6818 				return (TRAN_BUSY);
6819 			}
6820 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
6821 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
6822 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
6823 			/* Scheduling the callback failed */
6824 			return (TRAN_BUSY);
6825 		}
6826 	}
6827 
6828 	return (TRAN_ACCEPT);
6829 }
6830 
6831 /*
6832  * Emulated SATA Read/Write command completion for zero-length requests.
6833  * This request always succedes, so in synchronous mode it always returns
6834  * TRAN_ACCEPT, and in non-synchronous mode it may return TRAN_BUSY if the
6835  * callback cannot be scheduled.
6836  */
6837 static int
6838 sata_emul_rw_completion(sata_pkt_txlate_t *spx)
6839 {
6840 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6841 
6842 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6843 	    STATE_SENT_CMD | STATE_GOT_STATUS;
6844 	scsipkt->pkt_reason = CMD_CMPLT;
6845 	*scsipkt->pkt_scbp = STATUS_GOOD;
6846 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
6847 		/* scsi callback required - have to schedule it */
6848 		if (servicing_interrupt()) {
6849 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
6850 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
6851 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
6852 				return (TRAN_BUSY);
6853 			}
6854 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
6855 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
6856 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
6857 			/* Scheduling the callback failed */
6858 			return (TRAN_BUSY);
6859 		}
6860 	}
6861 	return (TRAN_ACCEPT);
6862 }
6863 
6864 
6865 /*
6866  * Translate completion status of SATA read/write commands into scsi response.
6867  * pkt completion_reason is checked to determine the completion status.
6868  * Do scsi callback if necessary.
6869  *
6870  * Note: this function may be called also for synchronously executed
6871  * commands.
6872  * This function may be used only if scsi_pkt is non-NULL.
6873  */
6874 static void
6875 sata_txlt_rw_completion(sata_pkt_t *sata_pkt)
6876 {
6877 	sata_pkt_txlate_t *spx =
6878 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
6879 	sata_cmd_t *scmd = &sata_pkt->satapkt_cmd;
6880 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6881 	struct scsi_extended_sense *sense;
6882 	uint64_t lba;
6883 	struct buf *bp;
6884 	int rval;
6885 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
6886 		/* Normal completion */
6887 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6888 		    STATE_SENT_CMD | STATE_XFERRED_DATA | STATE_GOT_STATUS;
6889 		scsipkt->pkt_reason = CMD_CMPLT;
6890 		*scsipkt->pkt_scbp = STATUS_GOOD;
6891 		if (spx->txlt_tmp_buf != NULL) {
6892 			/* Temporary buffer was used */
6893 			bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
6894 			if (bp->b_flags & B_READ) {
6895 				rval = ddi_dma_sync(
6896 				    spx->txlt_buf_dma_handle, 0, 0,
6897 				    DDI_DMA_SYNC_FORCPU);
6898 				ASSERT(rval == DDI_SUCCESS);
6899 				bcopy(spx->txlt_tmp_buf, bp->b_un.b_addr,
6900 				    bp->b_bcount);
6901 			}
6902 		}
6903 	} else {
6904 		/*
6905 		 * Something went wrong - analyze return
6906 		 */
6907 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6908 		    STATE_SENT_CMD | STATE_GOT_STATUS;
6909 		scsipkt->pkt_reason = CMD_INCOMPLETE;
6910 		*scsipkt->pkt_scbp = STATUS_CHECK;
6911 		sense = sata_arq_sense(spx);
6912 		ASSERT(sense != NULL);
6913 
6914 		/*
6915 		 * SATA_PKT_DEV_ERROR is the only case where we may be able to
6916 		 * extract from device registers the failing LBA.
6917 		 */
6918 		if (sata_pkt->satapkt_reason == SATA_PKT_DEV_ERROR) {
6919 			if ((scmd->satacmd_addr_type == ATA_ADDR_LBA48) &&
6920 			    (scmd->satacmd_lba_mid_msb != 0 ||
6921 			    scmd->satacmd_lba_high_msb != 0)) {
6922 				/*
6923 				 * We have problem reporting this cmd LBA
6924 				 * in fixed sense data format, because of
6925 				 * the size of the scsi LBA fields.
6926 				 */
6927 				sense->es_valid = 0;
6928 			} else {
6929 				sata_extract_error_lba(spx, &lba);
6930 				sense->es_info_1 = (lba & 0xFF000000) >> 24;
6931 				sense->es_info_2 = (lba & 0xFF0000) >> 16;
6932 				sense->es_info_3 = (lba & 0xFF00) >> 8;
6933 				sense->es_info_4 = lba & 0xFF;
6934 			}
6935 		} else {
6936 			/* Invalid extended sense info */
6937 			sense->es_valid = 0;
6938 		}
6939 
6940 		switch (sata_pkt->satapkt_reason) {
6941 		case SATA_PKT_PORT_ERROR:
6942 			/* We may want to handle DEV GONE state as well */
6943 			/*
6944 			 * We have no device data. Assume no data transfered.
6945 			 */
6946 			sense->es_key = KEY_HARDWARE_ERROR;
6947 			break;
6948 
6949 		case SATA_PKT_DEV_ERROR:
6950 			if (sata_pkt->satapkt_cmd.satacmd_status_reg &
6951 			    SATA_STATUS_ERR) {
6952 				/*
6953 				 * determine dev error reason from error
6954 				 * reg content
6955 				 */
6956 				sata_decode_device_error(spx, sense);
6957 				if (sense->es_key == KEY_MEDIUM_ERROR) {
6958 					switch (scmd->satacmd_cmd_reg) {
6959 					case SATAC_READ_DMA:
6960 					case SATAC_READ_DMA_EXT:
6961 					case SATAC_READ_DMA_QUEUED:
6962 					case SATAC_READ_DMA_QUEUED_EXT:
6963 					case SATAC_READ_FPDMA_QUEUED:
6964 						/* Unrecovered read error */
6965 						sense->es_add_code =
6966 						    SD_SCSI_ASC_UNREC_READ_ERR;
6967 						break;
6968 					case SATAC_WRITE_DMA:
6969 					case SATAC_WRITE_DMA_EXT:
6970 					case SATAC_WRITE_DMA_QUEUED:
6971 					case SATAC_WRITE_DMA_QUEUED_EXT:
6972 					case SATAC_WRITE_FPDMA_QUEUED:
6973 						/* Write error */
6974 						sense->es_add_code =
6975 						    SD_SCSI_ASC_WRITE_ERR;
6976 						break;
6977 					default:
6978 						/* Internal error */
6979 						SATA_LOG_D((
6980 						    spx->txlt_sata_hba_inst,
6981 						    CE_WARN,
6982 						    "sata_txlt_rw_completion :"
6983 						    "internal error - invalid "
6984 						    "command 0x%2x",
6985 						    scmd->satacmd_cmd_reg));
6986 						break;
6987 					}
6988 				}
6989 				break;
6990 			}
6991 			/* No extended sense key - no info available */
6992 			scsipkt->pkt_reason = CMD_INCOMPLETE;
6993 			break;
6994 
6995 		case SATA_PKT_TIMEOUT:
6996 			scsipkt->pkt_reason = CMD_TIMEOUT;
6997 			scsipkt->pkt_statistics |=
6998 			    STAT_TIMEOUT | STAT_DEV_RESET;
6999 			sense->es_key = KEY_ABORTED_COMMAND;
7000 			break;
7001 
7002 		case SATA_PKT_ABORTED:
7003 			scsipkt->pkt_reason = CMD_ABORTED;
7004 			scsipkt->pkt_statistics |= STAT_ABORTED;
7005 			sense->es_key = KEY_ABORTED_COMMAND;
7006 			break;
7007 
7008 		case SATA_PKT_RESET:
7009 			scsipkt->pkt_reason = CMD_RESET;
7010 			scsipkt->pkt_statistics |= STAT_DEV_RESET;
7011 			sense->es_key = KEY_ABORTED_COMMAND;
7012 			break;
7013 
7014 		default:
7015 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
7016 			    "sata_txlt_rw_completion: "
7017 			    "invalid packet completion reason"));
7018 			scsipkt->pkt_reason = CMD_TRAN_ERR;
7019 			break;
7020 		}
7021 	}
7022 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
7023 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
7024 
7025 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
7026 		/* scsi callback required */
7027 		scsi_hba_pkt_comp(scsipkt);
7028 }
7029 
7030 
7031 /*
7032  * Translate completion status of non-data commands (i.e. commands returning
7033  * no data).
7034  * pkt completion_reason is checked to determine the completion status.
7035  * Do scsi callback if necessary (FLAG_NOINTR == 0)
7036  *
7037  * Note: this function may be called also for synchronously executed
7038  * commands.
7039  * This function may be used only if scsi_pkt is non-NULL.
7040  */
7041 
7042 static	void
7043 sata_txlt_nodata_cmd_completion(sata_pkt_t *sata_pkt)
7044 {
7045 	sata_pkt_txlate_t *spx =
7046 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
7047 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7048 
7049 	sata_set_arq_data(sata_pkt);
7050 
7051 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
7052 		/* scsi callback required */
7053 		scsi_hba_pkt_comp(scsipkt);
7054 }
7055 
7056 /*
7057  * Completion handler for ATA Pass Through command
7058  */
7059 static void
7060 sata_txlt_apt_completion(sata_pkt_t *sata_pkt)
7061 {
7062 	sata_pkt_txlate_t *spx =
7063 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
7064 	sata_cmd_t *scmd = &sata_pkt->satapkt_cmd;
7065 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7066 	struct buf *bp;
7067 	uint8_t sense_key = 0, addl_sense_code = 0, addl_sense_qual = 0;
7068 
7069 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
7070 		/* Normal completion */
7071 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7072 		    STATE_SENT_CMD | STATE_XFERRED_DATA | STATE_GOT_STATUS;
7073 		scsipkt->pkt_reason = CMD_CMPLT;
7074 		*scsipkt->pkt_scbp = STATUS_GOOD;
7075 
7076 		/*
7077 		 * If the command has CK_COND set
7078 		 */
7079 		if (scsipkt->pkt_cdbp[2] & SATL_APT_BM_CK_COND) {
7080 			*scsipkt->pkt_scbp = STATUS_CHECK;
7081 			sata_fill_ata_return_desc(sata_pkt,
7082 			    KEY_RECOVERABLE_ERROR,
7083 			    SD_SCSI_ASC_ATP_INFO_AVAIL, 0);
7084 		}
7085 
7086 		if (spx->txlt_tmp_buf != NULL) {
7087 			/* Temporary buffer was used */
7088 			bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
7089 			if (bp->b_flags & B_READ) {
7090 				bcopy(spx->txlt_tmp_buf, bp->b_un.b_addr,
7091 				    bp->b_bcount);
7092 			}
7093 		}
7094 	} else {
7095 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7096 		    STATE_SENT_CMD | STATE_GOT_STATUS;
7097 		scsipkt->pkt_reason = CMD_INCOMPLETE;
7098 		*scsipkt->pkt_scbp = STATUS_CHECK;
7099 
7100 		/*
7101 		 * If DF or ERR was set, the HBA should have copied out the
7102 		 * status and error registers to the satacmd structure.
7103 		 */
7104 		if (scmd->satacmd_status_reg & SATA_STATUS_DF) {
7105 			sense_key = KEY_HARDWARE_ERROR;
7106 			addl_sense_code = SD_SCSI_ASC_INTERNAL_TARGET_FAILURE;
7107 			addl_sense_qual = 0;
7108 		} else if (scmd->satacmd_status_reg & SATA_STATUS_ERR) {
7109 			if (scmd->satacmd_error_reg & SATA_ERROR_NM) {
7110 				sense_key = KEY_NOT_READY;
7111 				addl_sense_code =
7112 				    SD_SCSI_ASC_MEDIUM_NOT_PRESENT;
7113 				addl_sense_qual = 0;
7114 			} else if (scmd->satacmd_error_reg & SATA_ERROR_UNC) {
7115 				sense_key = KEY_MEDIUM_ERROR;
7116 				addl_sense_code = SD_SCSI_ASC_UNREC_READ_ERR;
7117 				addl_sense_qual = 0;
7118 			} else if (scmd->satacmd_error_reg & SATA_ERROR_ILI) {
7119 				sense_key = KEY_DATA_PROTECT;
7120 				addl_sense_code = SD_SCSI_ASC_WRITE_PROTECTED;
7121 				addl_sense_qual = 0;
7122 			} else if (scmd->satacmd_error_reg & SATA_ERROR_IDNF) {
7123 				sense_key = KEY_ILLEGAL_REQUEST;
7124 				addl_sense_code = SD_SCSI_ASC_LBA_OUT_OF_RANGE;
7125 				addl_sense_qual = 0;
7126 			} else if (scmd->satacmd_error_reg & SATA_ERROR_ABORT) {
7127 				sense_key = KEY_ABORTED_COMMAND;
7128 				addl_sense_code = SD_SCSI_ASC_NO_ADD_SENSE;
7129 				addl_sense_qual = 0;
7130 			} else if (scmd->satacmd_error_reg & SATA_ERROR_MC) {
7131 				sense_key = KEY_UNIT_ATTENTION;
7132 				addl_sense_code =
7133 				    SD_SCSI_ASC_MEDIUM_MAY_HAVE_CHANGED;
7134 				addl_sense_qual = 0;
7135 			} else if (scmd->satacmd_error_reg & SATA_ERROR_MCR) {
7136 				sense_key = KEY_UNIT_ATTENTION;
7137 				addl_sense_code = SD_SCSI_ASC_OP_MEDIUM_REM_REQ;
7138 				addl_sense_qual = 0;
7139 			} else if (scmd->satacmd_error_reg & SATA_ERROR_ICRC) {
7140 				sense_key = KEY_ABORTED_COMMAND;
7141 				addl_sense_code =
7142 				    SD_SCSI_ASC_INFO_UNIT_IUCRC_ERR;
7143 				addl_sense_qual = 0;
7144 			}
7145 		}
7146 
7147 		sata_fill_ata_return_desc(sata_pkt, sense_key, addl_sense_code,
7148 		    addl_sense_qual);
7149 	}
7150 
7151 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
7152 		/* scsi callback required */
7153 		scsi_hba_pkt_comp(scsipkt);
7154 }
7155 
7156 /*
7157  * j
7158  */
7159 static void
7160 sata_fill_ata_return_desc(sata_pkt_t *sata_pkt, uint8_t sense_key,
7161     uint8_t addl_sense_code, uint8_t addl_sense_qual)
7162 {
7163 	sata_pkt_txlate_t *spx =
7164 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
7165 	sata_cmd_t *scmd = &sata_pkt->satapkt_cmd;
7166 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7167 	struct sata_apt_sense_data *apt_sd =
7168 	    (struct sata_apt_sense_data *)scsipkt->pkt_scbp;
7169 	struct scsi_descr_sense_hdr *sds = &(apt_sd->apt_sd_hdr);
7170 	struct scsi_ata_status_ret_sense_descr *ata_ret_desc =
7171 	    &(apt_sd->apt_sd_sense);
7172 	int extend = 0;
7173 
7174 	if ((scsipkt->pkt_cdbp[0] == SPC3_CMD_ATA_COMMAND_PASS_THROUGH16) &&
7175 	    (scsipkt->pkt_cdbp[2] & SATL_APT_BM_EXTEND))
7176 		extend = 1;
7177 
7178 	scsipkt->pkt_state |= STATE_ARQ_DONE;
7179 
7180 	/* update the residual count */
7181 	*(uchar_t *)&apt_sd->apt_status = STATUS_CHECK;
7182 	*(uchar_t *)&apt_sd->apt_rqpkt_status = STATUS_GOOD;
7183 	apt_sd->apt_rqpkt_reason = CMD_CMPLT;
7184 	apt_sd->apt_rqpkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7185 	    STATE_XFERRED_DATA | STATE_SENT_CMD | STATE_GOT_STATUS;
7186 	apt_sd->apt_rqpkt_resid = scsipkt->pkt_scblen -
7187 	    sizeof (struct sata_apt_sense_data);
7188 
7189 	/*
7190 	 * Fill in the Descriptor sense header
7191 	 */
7192 	bzero(sds, sizeof (struct scsi_descr_sense_hdr));
7193 	sds->ds_code = CODE_FMT_DESCR_CURRENT;
7194 	sds->ds_class = CLASS_EXTENDED_SENSE;
7195 	sds->ds_key = sense_key & 0xf;
7196 	sds->ds_add_code = addl_sense_code;
7197 	sds->ds_qual_code = addl_sense_qual;
7198 	sds->ds_addl_sense_length =
7199 	    sizeof (struct scsi_ata_status_ret_sense_descr);
7200 
7201 	/*
7202 	 * Fill in the ATA Return descriptor sense data
7203 	 */
7204 	bzero(ata_ret_desc, sizeof (struct scsi_ata_status_ret_sense_descr));
7205 	ata_ret_desc->ars_descr_type = DESCR_ATA_STATUS_RETURN;
7206 	ata_ret_desc->ars_addl_length = 0xc;
7207 	ata_ret_desc->ars_error = scmd->satacmd_error_reg;
7208 	ata_ret_desc->ars_sec_count_lsb = scmd->satacmd_sec_count_lsb;
7209 	ata_ret_desc->ars_lba_low_lsb = scmd->satacmd_lba_low_lsb;
7210 	ata_ret_desc->ars_lba_mid_lsb = scmd->satacmd_lba_mid_lsb;
7211 	ata_ret_desc->ars_lba_high_lsb = scmd->satacmd_lba_high_lsb;
7212 	ata_ret_desc->ars_device = scmd->satacmd_device_reg;
7213 	ata_ret_desc->ars_status = scmd->satacmd_status_reg;
7214 
7215 	if (extend == 1) {
7216 		ata_ret_desc->ars_extend = 1;
7217 		ata_ret_desc->ars_sec_count_msb = scmd->satacmd_sec_count_msb;
7218 		ata_ret_desc->ars_lba_low_msb = scmd->satacmd_lba_low_msb;
7219 		ata_ret_desc->ars_lba_mid_msb = scmd->satacmd_lba_mid_msb;
7220 		ata_ret_desc->ars_lba_high_msb = scmd->satacmd_lba_high_msb;
7221 	} else {
7222 		ata_ret_desc->ars_extend = 0;
7223 		ata_ret_desc->ars_sec_count_msb = 0;
7224 		ata_ret_desc->ars_lba_low_msb = 0;
7225 		ata_ret_desc->ars_lba_mid_msb = 0;
7226 		ata_ret_desc->ars_lba_high_msb = 0;
7227 	}
7228 }
7229 
7230 static	void
7231 sata_set_arq_data(sata_pkt_t *sata_pkt)
7232 {
7233 	sata_pkt_txlate_t *spx =
7234 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
7235 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7236 	struct scsi_extended_sense *sense;
7237 
7238 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7239 	    STATE_SENT_CMD | STATE_GOT_STATUS;
7240 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
7241 		/* Normal completion */
7242 		scsipkt->pkt_reason = CMD_CMPLT;
7243 		*scsipkt->pkt_scbp = STATUS_GOOD;
7244 	} else {
7245 		/* Something went wrong */
7246 		scsipkt->pkt_reason = CMD_INCOMPLETE;
7247 		*scsipkt->pkt_scbp = STATUS_CHECK;
7248 		sense = sata_arq_sense(spx);
7249 		switch (sata_pkt->satapkt_reason) {
7250 		case SATA_PKT_PORT_ERROR:
7251 			/*
7252 			 * We have no device data. Assume no data transfered.
7253 			 */
7254 			sense->es_key = KEY_HARDWARE_ERROR;
7255 			break;
7256 
7257 		case SATA_PKT_DEV_ERROR:
7258 			if (sata_pkt->satapkt_cmd.satacmd_status_reg &
7259 			    SATA_STATUS_ERR) {
7260 				/*
7261 				 * determine dev error reason from error
7262 				 * reg content
7263 				 */
7264 				sata_decode_device_error(spx, sense);
7265 				break;
7266 			}
7267 			/* No extended sense key - no info available */
7268 			break;
7269 
7270 		case SATA_PKT_TIMEOUT:
7271 			scsipkt->pkt_reason = CMD_TIMEOUT;
7272 			scsipkt->pkt_statistics |=
7273 			    STAT_TIMEOUT | STAT_DEV_RESET;
7274 			/* No extended sense key ? */
7275 			break;
7276 
7277 		case SATA_PKT_ABORTED:
7278 			scsipkt->pkt_reason = CMD_ABORTED;
7279 			scsipkt->pkt_statistics |= STAT_ABORTED;
7280 			/* No extended sense key ? */
7281 			break;
7282 
7283 		case SATA_PKT_RESET:
7284 			/* pkt aborted by an explicit reset from a host */
7285 			scsipkt->pkt_reason = CMD_RESET;
7286 			scsipkt->pkt_statistics |= STAT_DEV_RESET;
7287 			break;
7288 
7289 		default:
7290 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
7291 			    "sata_txlt_nodata_cmd_completion: "
7292 			    "invalid packet completion reason %d",
7293 			    sata_pkt->satapkt_reason));
7294 			scsipkt->pkt_reason = CMD_TRAN_ERR;
7295 			break;
7296 		}
7297 
7298 	}
7299 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
7300 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
7301 }
7302 
7303 
7304 /*
7305  * Build Mode sense R/W recovery page
7306  * NOT IMPLEMENTED
7307  */
7308 
7309 static int
7310 sata_build_msense_page_1(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
7311 {
7312 #ifndef __lock_lint
7313 	_NOTE(ARGUNUSED(sdinfo))
7314 	_NOTE(ARGUNUSED(pcntrl))
7315 	_NOTE(ARGUNUSED(buf))
7316 #endif
7317 	return (0);
7318 }
7319 
7320 /*
7321  * Build Mode sense caching page  -  scsi-3 implementation.
7322  * Page length distinguishes previous format from scsi-3 format.
7323  * buf must have space for 0x12 bytes.
7324  * Only DRA (disable read ahead ) and WCE (write cache enable) are changeable.
7325  *
7326  */
7327 static int
7328 sata_build_msense_page_8(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
7329 {
7330 	struct mode_cache_scsi3 *page = (struct mode_cache_scsi3 *)buf;
7331 	sata_id_t *sata_id = &sdinfo->satadrv_id;
7332 
7333 	/*
7334 	 * Most of the fields are set to 0, being not supported and/or disabled
7335 	 */
7336 	bzero(buf, PAGELENGTH_DAD_MODE_CACHE_SCSI3);
7337 
7338 	/* Saved paramters not supported */
7339 	if (pcntrl == 3)
7340 		return (0);
7341 	if (pcntrl == 0 || pcntrl == 2) {
7342 		/*
7343 		 * For now treat current and default parameters as same
7344 		 * That may have to change, if target driver will complain
7345 		 */
7346 		page->mode_page.code = MODEPAGE_CACHING;	/* PS = 0 */
7347 		page->mode_page.length = PAGELENGTH_DAD_MODE_CACHE_SCSI3;
7348 
7349 		if (SATA_READ_AHEAD_SUPPORTED(*sata_id) &&
7350 		    !SATA_READ_AHEAD_ENABLED(*sata_id)) {
7351 			page->dra = 1;		/* Read Ahead disabled */
7352 			page->rcd = 1;		/* Read Cache disabled */
7353 		}
7354 		if (SATA_WRITE_CACHE_SUPPORTED(*sata_id) &&
7355 		    SATA_WRITE_CACHE_ENABLED(*sata_id))
7356 			page->wce = 1;		/* Write Cache enabled */
7357 	} else {
7358 		/* Changeable parameters */
7359 		page->mode_page.code = MODEPAGE_CACHING;
7360 		page->mode_page.length = PAGELENGTH_DAD_MODE_CACHE_SCSI3;
7361 		if (SATA_READ_AHEAD_SUPPORTED(*sata_id)) {
7362 			page->dra = 1;
7363 			page->rcd = 1;
7364 		}
7365 		if (SATA_WRITE_CACHE_SUPPORTED(*sata_id))
7366 			page->wce = 1;
7367 	}
7368 	return (PAGELENGTH_DAD_MODE_CACHE_SCSI3 +
7369 	    sizeof (struct mode_page));
7370 }
7371 
7372 /*
7373  * Build Mode sense exception cntrl page
7374  */
7375 static int
7376 sata_build_msense_page_1c(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
7377 {
7378 	struct mode_info_excpt_page *page = (struct mode_info_excpt_page *)buf;
7379 	sata_id_t *sata_id = &sdinfo->satadrv_id;
7380 
7381 	/*
7382 	 * Most of the fields are set to 0, being not supported and/or disabled
7383 	 */
7384 	bzero(buf, PAGELENGTH_INFO_EXCPT);
7385 
7386 	page->mode_page.code = MODEPAGE_INFO_EXCPT;
7387 	page->mode_page.length = PAGELENGTH_INFO_EXCPT;
7388 
7389 	/* Indicate that this is page is saveable */
7390 	page->mode_page.ps = 1;
7391 
7392 	/*
7393 	 * We will return the same data for default, current and saved page.
7394 	 * The only changeable bit is dexcpt and that bit is required
7395 	 * by the ATA specification to be preserved across power cycles.
7396 	 */
7397 	if (pcntrl != 1) {
7398 		page->dexcpt = !(sata_id->ai_features85 & SATA_SMART_SUPPORTED);
7399 		page->mrie = MRIE_ONLY_ON_REQUEST;
7400 	}
7401 	else
7402 		page->dexcpt = 1;	/* Only changeable parameter */
7403 
7404 	return (PAGELENGTH_INFO_EXCPT + sizeof (struct mode_page));
7405 }
7406 
7407 
7408 static int
7409 sata_build_msense_page_30(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
7410 {
7411 	struct mode_acoustic_management *page =
7412 	    (struct mode_acoustic_management *)buf;
7413 	sata_id_t *sata_id = &sdinfo->satadrv_id;
7414 
7415 	/*
7416 	 * Most of the fields are set to 0, being not supported and/or disabled
7417 	 */
7418 	bzero(buf, PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT);
7419 
7420 	switch (pcntrl) {
7421 	case P_CNTRL_DEFAULT:
7422 		/*  default paramters not supported */
7423 		return (0);
7424 
7425 	case P_CNTRL_CURRENT:
7426 	case P_CNTRL_SAVED:
7427 		/* Saved and current are supported and are identical */
7428 		page->mode_page.code = MODEPAGE_ACOUSTIC_MANAG;
7429 		page->mode_page.length =
7430 		    PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT;
7431 		page->mode_page.ps = 1;
7432 
7433 		/* Word 83 indicates if feature is supported */
7434 		/* If feature is not supported */
7435 		if (!(sata_id->ai_cmdset83 & SATA_ACOUSTIC_MGMT)) {
7436 			page->acoustic_manag_enable =
7437 			    ACOUSTIC_DISABLED;
7438 		} else {
7439 			page->acoustic_manag_enable =
7440 			    ((sata_id->ai_features86 & SATA_ACOUSTIC_MGMT)
7441 			    != 0);
7442 			/* Word 94 inidicates the value */
7443 #ifdef	_LITTLE_ENDIAN
7444 			page->acoustic_manag_level =
7445 			    (uchar_t)sata_id->ai_acoustic;
7446 			page->vendor_recommended_value =
7447 			    sata_id->ai_acoustic >> 8;
7448 #else
7449 			page->acoustic_manag_level =
7450 			    sata_id->ai_acoustic >> 8;
7451 			page->vendor_recommended_value =
7452 			    (uchar_t)sata_id->ai_acoustic;
7453 #endif
7454 		}
7455 		break;
7456 
7457 	case P_CNTRL_CHANGEABLE:
7458 		page->mode_page.code = MODEPAGE_ACOUSTIC_MANAG;
7459 		page->mode_page.length =
7460 		    PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT;
7461 		page->mode_page.ps = 1;
7462 
7463 		/* Word 83 indicates if the feature is supported */
7464 		if (sata_id->ai_cmdset83 & SATA_ACOUSTIC_MGMT) {
7465 			page->acoustic_manag_enable =
7466 			    ACOUSTIC_ENABLED;
7467 			page->acoustic_manag_level = 0xff;
7468 		}
7469 		break;
7470 	}
7471 	return (PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT +
7472 	    sizeof (struct mode_page));
7473 }
7474 
7475 
7476 /*
7477  * Build Mode sense power condition page.
7478  */
7479 static int
7480 sata_build_msense_page_1a(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
7481 {
7482 	struct mode_info_power_cond *page = (struct mode_info_power_cond *)buf;
7483 	sata_id_t *sata_id = &sdinfo->satadrv_id;
7484 
7485 	/*
7486 	 * Most of the fields are set to 0, being not supported and/or disabled
7487 	 * power condition page length was 0x0a
7488 	 */
7489 	bzero(buf, sizeof (struct mode_info_power_cond));
7490 
7491 	if (pcntrl == P_CNTRL_DEFAULT) {
7492 		/*  default paramters not supported */
7493 		return (0);
7494 	}
7495 
7496 	page->mode_page.code = MODEPAGE_POWER_COND;
7497 	page->mode_page.length = sizeof (struct mode_info_power_cond);
7498 
7499 	if (sata_id->ai_cap && SATA_STANDBYTIMER) {
7500 		page->standby = 1;
7501 		bcopy(sdinfo->satadrv_standby_timer, page->standby_cond_timer,
7502 		    sizeof (uchar_t) * 4);
7503 	}
7504 
7505 	return (sizeof (struct mode_info_power_cond));
7506 }
7507 
7508 /*
7509  * Process mode select caching page 8 (scsi3 format only).
7510  * Read Ahead (same as read cache) and Write Cache may be turned on and off
7511  * if these features are supported by the device. If these features are not
7512  * supported, the command will be terminated with STATUS_CHECK.
7513  * This function fails only if the SET FEATURE command sent to
7514  * the device fails. The page format is not varified, assuming that the
7515  * target driver operates correctly - if parameters length is too short,
7516  * we just drop the page.
7517  * Two command may be sent if both Read Cache/Read Ahead and Write Cache
7518  * setting have to be changed.
7519  * SET FEATURE command is executed synchronously, i.e. we wait here until
7520  * it is completed, regardless of the scsi pkt directives.
7521  *
7522  * Note: Mode Select Caching page RCD and DRA bits are tied together, i.e.
7523  * changing DRA will change RCD.
7524  *
7525  * More than one SATA command may be executed to perform operations specified
7526  * by mode select pages. The first error terminates further execution.
7527  * Operations performed successully are not backed-up in such case.
7528  *
7529  * Return SATA_SUCCESS if operation succeeded, SATA_FAILURE otherwise.
7530  * If operation resulted in changing device setup, dmod flag should be set to
7531  * one (1). If parameters were not changed, dmod flag should be set to 0.
7532  * Upon return, if operation required sending command to the device, the rval
7533  * should be set to the value returned by sata_hba_start. If operation
7534  * did not require device access, rval should be set to TRAN_ACCEPT.
7535  * The pagelen should be set to the length of the page.
7536  *
7537  * This function has to be called with a port mutex held.
7538  *
7539  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
7540  */
7541 int
7542 sata_mode_select_page_8(sata_pkt_txlate_t *spx, struct mode_cache_scsi3 *page,
7543     int parmlen, int *pagelen, int *rval, int *dmod)
7544 {
7545 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7546 	sata_drive_info_t *sdinfo;
7547 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
7548 	sata_id_t *sata_id;
7549 	struct scsi_extended_sense *sense;
7550 	int wce, dra;	/* Current settings */
7551 
7552 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
7553 	    &spx->txlt_sata_pkt->satapkt_device);
7554 	sata_id = &sdinfo->satadrv_id;
7555 	*dmod = 0;
7556 
7557 	/* Verify parameters length. If too short, drop it */
7558 	if ((PAGELENGTH_DAD_MODE_CACHE_SCSI3 +
7559 	    sizeof (struct mode_page)) > parmlen) {
7560 		*scsipkt->pkt_scbp = STATUS_CHECK;
7561 		sense = sata_arq_sense(spx);
7562 		sense->es_key = KEY_ILLEGAL_REQUEST;
7563 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
7564 		*pagelen = parmlen;
7565 		*rval = TRAN_ACCEPT;
7566 		return (SATA_FAILURE);
7567 	}
7568 
7569 	*pagelen = PAGELENGTH_DAD_MODE_CACHE_SCSI3 + sizeof (struct mode_page);
7570 
7571 	/* Current setting of Read Ahead (and Read Cache) */
7572 	if (SATA_READ_AHEAD_ENABLED(*sata_id))
7573 		dra = 0;	/* 0 == not disabled */
7574 	else
7575 		dra = 1;
7576 	/* Current setting of Write Cache */
7577 	if (SATA_WRITE_CACHE_ENABLED(*sata_id))
7578 		wce = 1;
7579 	else
7580 		wce = 0;
7581 
7582 	if (page->dra == dra && page->wce == wce && page->rcd == dra) {
7583 		/* nothing to do */
7584 		*rval = TRAN_ACCEPT;
7585 		return (SATA_SUCCESS);
7586 	}
7587 
7588 	/*
7589 	 * Need to flip some setting
7590 	 * Set-up Internal SET FEATURES command(s)
7591 	 */
7592 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
7593 	scmd->satacmd_addr_type = 0;
7594 	scmd->satacmd_device_reg = 0;
7595 	scmd->satacmd_status_reg = 0;
7596 	scmd->satacmd_error_reg = 0;
7597 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
7598 	if (page->dra != dra || page->rcd != dra) {
7599 		if (SATA_READ_AHEAD_SUPPORTED(*sata_id)) {
7600 			/* Need to flip read ahead setting */
7601 			if (dra == 0)
7602 				/* Disable read ahead / read cache */
7603 				scmd->satacmd_features_reg =
7604 				    SATAC_SF_DISABLE_READ_AHEAD;
7605 			else
7606 				/* Enable read ahead  / read cache */
7607 				scmd->satacmd_features_reg =
7608 				    SATAC_SF_ENABLE_READ_AHEAD;
7609 
7610 			/* Transfer command to HBA */
7611 			if (sata_hba_start(spx, rval) != 0)
7612 				/*
7613 				 * Pkt not accepted for execution.
7614 				 */
7615 				return (SATA_FAILURE);
7616 
7617 			*dmod = 1;
7618 
7619 			/* Now process return */
7620 			if (spx->txlt_sata_pkt->satapkt_reason !=
7621 			    SATA_PKT_COMPLETED) {
7622 				goto failure;	/* Terminate */
7623 			}
7624 		} else {
7625 			*scsipkt->pkt_scbp = STATUS_CHECK;
7626 			sense = sata_arq_sense(spx);
7627 			sense->es_key = KEY_ILLEGAL_REQUEST;
7628 			sense->es_add_code =
7629 			    SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
7630 			*pagelen = parmlen;
7631 			*rval = TRAN_ACCEPT;
7632 			return (SATA_FAILURE);
7633 		}
7634 	}
7635 
7636 	/* Note that the packet is not removed, so it could be re-used */
7637 	if (page->wce != wce) {
7638 		if (SATA_WRITE_CACHE_SUPPORTED(*sata_id)) {
7639 			/* Need to flip Write Cache setting */
7640 			if (page->wce == 1)
7641 				/* Enable write cache */
7642 				scmd->satacmd_features_reg =
7643 				    SATAC_SF_ENABLE_WRITE_CACHE;
7644 			else
7645 				/* Disable write cache */
7646 				scmd->satacmd_features_reg =
7647 				    SATAC_SF_DISABLE_WRITE_CACHE;
7648 
7649 			/* Transfer command to HBA */
7650 			if (sata_hba_start(spx, rval) != 0)
7651 				/*
7652 				 * Pkt not accepted for execution.
7653 				 */
7654 				return (SATA_FAILURE);
7655 
7656 			*dmod = 1;
7657 
7658 			/* Now process return */
7659 			if (spx->txlt_sata_pkt->satapkt_reason !=
7660 			    SATA_PKT_COMPLETED) {
7661 				goto failure;
7662 			}
7663 		} else {
7664 			*scsipkt->pkt_scbp = STATUS_CHECK;
7665 			sense = sata_arq_sense(spx);
7666 			sense->es_key = KEY_ILLEGAL_REQUEST;
7667 			sense->es_add_code =
7668 			    SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
7669 			*pagelen = parmlen;
7670 			*rval = TRAN_ACCEPT;
7671 			return (SATA_FAILURE);
7672 		}
7673 	}
7674 	return (SATA_SUCCESS);
7675 
7676 failure:
7677 	sata_xlate_errors(spx);
7678 
7679 	return (SATA_FAILURE);
7680 }
7681 
7682 /*
7683  * Process mode select informational exceptions control page 0x1c
7684  *
7685  * The only changeable bit is dexcpt (disable exceptions).
7686  * MRIE (method of reporting informational exceptions) must be
7687  * "only on request".
7688  * This page applies to informational exceptions that report
7689  * additional sense codes with the ADDITIONAL SENSE CODE field set to 5Dh
7690  * (e.g.,FAILURE PREDICTION THRESHOLD EXCEEDED) or 0Bh (e.g., WARNING_).
7691  * Informational exception conditions occur as the result of background scan
7692  * errors, background self-test errors, or vendor specific events within a
7693  * logical unit. An informational exception condition may occur asynchronous
7694  * to any commands.
7695  *
7696  * Returns: SATA_SUCCESS if operation succeeded, SATA_FAILURE otherwise.
7697  * If operation resulted in changing device setup, dmod flag should be set to
7698  * one (1). If parameters were not changed, dmod flag should be set to 0.
7699  * Upon return, if operation required sending command to the device, the rval
7700  * should be set to the value returned by sata_hba_start. If operation
7701  * did not require device access, rval should be set to TRAN_ACCEPT.
7702  * The pagelen should be set to the length of the page.
7703  *
7704  * This function has to be called with a port mutex held.
7705  *
7706  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
7707  *
7708  * Cannot be called in the interrupt context.
7709  */
7710 static	int
7711 sata_mode_select_page_1c(
7712 	sata_pkt_txlate_t *spx,
7713 	struct mode_info_excpt_page *page,
7714 	int parmlen,
7715 	int *pagelen,
7716 	int *rval,
7717 	int *dmod)
7718 {
7719 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7720 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
7721 	sata_drive_info_t *sdinfo;
7722 	sata_id_t *sata_id;
7723 	struct scsi_extended_sense *sense;
7724 
7725 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
7726 	    &spx->txlt_sata_pkt->satapkt_device);
7727 	sata_id = &sdinfo->satadrv_id;
7728 
7729 	*dmod = 0;
7730 
7731 	/* Verify parameters length. If too short, drop it */
7732 	if (((PAGELENGTH_INFO_EXCPT + sizeof (struct mode_page)) > parmlen) ||
7733 	    page->perf || page->test || (page->mrie != MRIE_ONLY_ON_REQUEST)) {
7734 		*scsipkt->pkt_scbp = STATUS_CHECK;
7735 		sense = sata_arq_sense(spx);
7736 		sense->es_key = KEY_ILLEGAL_REQUEST;
7737 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
7738 		*pagelen = parmlen;
7739 		*rval = TRAN_ACCEPT;
7740 		return (SATA_FAILURE);
7741 	}
7742 
7743 	*pagelen = PAGELENGTH_INFO_EXCPT + sizeof (struct mode_page);
7744 
7745 	if (! (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED)) {
7746 		*scsipkt->pkt_scbp = STATUS_CHECK;
7747 		sense = sata_arq_sense(spx);
7748 		sense->es_key = KEY_ILLEGAL_REQUEST;
7749 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
7750 		*pagelen = parmlen;
7751 		*rval = TRAN_ACCEPT;
7752 		return (SATA_FAILURE);
7753 	}
7754 
7755 	/* If already in the state requested, we are done */
7756 	if (page->dexcpt == ! (sata_id->ai_features85 & SATA_SMART_ENABLED)) {
7757 		/* nothing to do */
7758 		*rval = TRAN_ACCEPT;
7759 		return (SATA_SUCCESS);
7760 	}
7761 
7762 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
7763 
7764 	/* Build SMART_ENABLE or SMART_DISABLE command */
7765 	scmd->satacmd_addr_type = 0;		/* N/A */
7766 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
7767 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
7768 	scmd->satacmd_features_reg = page->dexcpt ?
7769 	    SATA_SMART_DISABLE_OPS : SATA_SMART_ENABLE_OPS;
7770 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
7771 	scmd->satacmd_cmd_reg = SATAC_SMART;
7772 
7773 	/* Transfer command to HBA */
7774 	if (sata_hba_start(spx, rval) != 0)
7775 		/*
7776 		 * Pkt not accepted for execution.
7777 		 */
7778 		return (SATA_FAILURE);
7779 
7780 	*dmod = 1;	/* At least may have been modified */
7781 
7782 	/* Now process return */
7783 	if (spx->txlt_sata_pkt->satapkt_reason == SATA_PKT_COMPLETED)
7784 		return (SATA_SUCCESS);
7785 
7786 	/* Packet did not complete successfully */
7787 	sata_xlate_errors(spx);
7788 
7789 	return (SATA_FAILURE);
7790 }
7791 
7792 /*
7793  * Process mode select acoustic management control page 0x30
7794  *
7795  *
7796  * This function has to be called with a port mutex held.
7797  *
7798  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
7799  *
7800  * Cannot be called in the interrupt context.
7801  */
7802 int
7803 sata_mode_select_page_30(sata_pkt_txlate_t *spx, struct
7804     mode_acoustic_management *page, int parmlen, int *pagelen,
7805     int *rval, int *dmod)
7806 {
7807 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7808 	sata_drive_info_t *sdinfo;
7809 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
7810 	sata_id_t *sata_id;
7811 	struct scsi_extended_sense *sense;
7812 
7813 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
7814 	    &spx->txlt_sata_pkt->satapkt_device);
7815 	sata_id = &sdinfo->satadrv_id;
7816 	*dmod = 0;
7817 
7818 	/* If parmlen is too short or the feature is not supported, drop it */
7819 	if (((PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT +
7820 	    sizeof (struct mode_page)) > parmlen) ||
7821 	    (! (sata_id->ai_cmdset83 & SATA_ACOUSTIC_MGMT))) {
7822 		*scsipkt->pkt_scbp = STATUS_CHECK;
7823 		sense = sata_arq_sense(spx);
7824 		sense->es_key = KEY_ILLEGAL_REQUEST;
7825 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
7826 		*pagelen = parmlen;
7827 		*rval = TRAN_ACCEPT;
7828 		return (SATA_FAILURE);
7829 	}
7830 
7831 	*pagelen = PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT +
7832 	    sizeof (struct mode_page);
7833 
7834 	/*
7835 	 * We can enable and disable acoustice management and
7836 	 * set the acoustic management level.
7837 	 */
7838 
7839 	/*
7840 	 * Set-up Internal SET FEATURES command(s)
7841 	 */
7842 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
7843 	scmd->satacmd_addr_type = 0;
7844 	scmd->satacmd_device_reg = 0;
7845 	scmd->satacmd_status_reg = 0;
7846 	scmd->satacmd_error_reg = 0;
7847 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
7848 	if (page->acoustic_manag_enable) {
7849 		scmd->satacmd_features_reg = SATAC_SF_ENABLE_ACOUSTIC;
7850 		scmd->satacmd_sec_count_lsb = page->acoustic_manag_level;
7851 	} else {	/* disabling acoustic management */
7852 		scmd->satacmd_features_reg = SATAC_SF_DISABLE_ACOUSTIC;
7853 	}
7854 
7855 	/* Transfer command to HBA */
7856 	if (sata_hba_start(spx, rval) != 0)
7857 		/*
7858 		 * Pkt not accepted for execution.
7859 		 */
7860 		return (SATA_FAILURE);
7861 
7862 	/* Now process return */
7863 	if (spx->txlt_sata_pkt->satapkt_reason != SATA_PKT_COMPLETED) {
7864 		sata_xlate_errors(spx);
7865 		return (SATA_FAILURE);
7866 	}
7867 
7868 	*dmod = 1;
7869 
7870 	return (SATA_SUCCESS);
7871 }
7872 
7873 /*
7874  * Process mode select power condition page 0x1a
7875  *
7876  * This function has to be called with a port mutex held.
7877  *
7878  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
7879  *
7880  * Cannot be called in the interrupt context.
7881  */
7882 int
7883 sata_mode_select_page_1a(sata_pkt_txlate_t *spx, struct
7884     mode_info_power_cond *page, int parmlen, int *pagelen,
7885     int *rval, int *dmod)
7886 {
7887 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7888 	sata_drive_info_t *sdinfo;
7889 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
7890 	sata_id_t *sata_id;
7891 	struct scsi_extended_sense *sense;
7892 	uint8_t ata_count;
7893 	int i, len;
7894 
7895 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
7896 	    &spx->txlt_sata_pkt->satapkt_device);
7897 	sata_id = &sdinfo->satadrv_id;
7898 	*dmod = 0;
7899 
7900 	len = sizeof (struct mode_info_power_cond);
7901 	len += sizeof (struct mode_page);
7902 
7903 	/* If parmlen is too short or the feature is not supported, drop it */
7904 	if ((len < parmlen) || (page->idle == 1) ||
7905 	    (!(sata_id->ai_cap && SATA_STANDBYTIMER) && page->standby == 1)) {
7906 		*scsipkt->pkt_scbp = STATUS_CHECK;
7907 		sense = sata_arq_sense(spx);
7908 		sense->es_key = KEY_ILLEGAL_REQUEST;
7909 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
7910 		*pagelen = parmlen;
7911 		*rval = TRAN_ACCEPT;
7912 		return (SATA_FAILURE);
7913 	}
7914 
7915 	*pagelen = len;
7916 
7917 	/*
7918 	 * Set-up Internal STANDBY command(s)
7919 	 */
7920 	if (page->standby == 0)
7921 		goto out;
7922 
7923 	ata_count = sata_get_standby_timer(page->standby_cond_timer);
7924 
7925 	scmd->satacmd_addr_type = 0;
7926 	scmd->satacmd_sec_count_lsb = ata_count;
7927 	scmd->satacmd_lba_low_lsb = 0;
7928 	scmd->satacmd_lba_mid_lsb = 0;
7929 	scmd->satacmd_lba_high_lsb = 0;
7930 	scmd->satacmd_features_reg = 0;
7931 	scmd->satacmd_device_reg = 0;
7932 	scmd->satacmd_status_reg = 0;
7933 	scmd->satacmd_cmd_reg = SATAC_STANDBY;
7934 	scmd->satacmd_flags.sata_special_regs = B_TRUE;
7935 	scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
7936 
7937 	/* Transfer command to HBA */
7938 	if (sata_hba_start(spx, rval) != 0) {
7939 		return (SATA_FAILURE);
7940 	} else {
7941 		if ((scmd->satacmd_error_reg != 0) ||
7942 		    (spx->txlt_sata_pkt->satapkt_reason !=
7943 		    SATA_PKT_COMPLETED)) {
7944 			sata_xlate_errors(spx);
7945 			return (SATA_FAILURE);
7946 		}
7947 	}
7948 
7949 	for (i = 0; i < 4; i++) {
7950 		sdinfo->satadrv_standby_timer[i] = page->standby_cond_timer[i];
7951 	}
7952 out:
7953 	*dmod = 1;
7954 	return (SATA_SUCCESS);
7955 }
7956 
7957 /*
7958  * sata_build_lsense_page0() is used to create the
7959  * SCSI LOG SENSE page 0 (supported log pages)
7960  *
7961  * Currently supported pages are 0, 0x10, 0x2f, 0x30 and 0x0e
7962  * (supported log pages, self-test results, informational exceptions
7963  * Sun vendor specific ATA SMART data, and start stop cycle counter).
7964  *
7965  * Takes a sata_drive_info t * and the address of a buffer
7966  * in which to create the page information.
7967  *
7968  * Returns the number of bytes valid in the buffer.
7969  */
7970 static	int
7971 sata_build_lsense_page_0(sata_drive_info_t *sdinfo, uint8_t *buf)
7972 {
7973 	struct log_parameter *lpp = (struct log_parameter *)buf;
7974 	uint8_t *page_ptr = (uint8_t *)lpp->param_values;
7975 	int num_pages_supported = 1; /* Always have GET_SUPPORTED_LOG_PAGES */
7976 	sata_id_t *sata_id = &sdinfo->satadrv_id;
7977 
7978 	lpp->param_code[0] = 0;
7979 	lpp->param_code[1] = 0;
7980 	lpp->param_ctrl_flags = LOG_CTRL_LP | LOG_CTRL_LBIN;
7981 	*page_ptr++ = PAGE_CODE_GET_SUPPORTED_LOG_PAGES;
7982 
7983 	if (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED) {
7984 		if (sata_id->ai_cmdset84 & SATA_SMART_SELF_TEST_SUPPORTED) {
7985 			*page_ptr++ = PAGE_CODE_SELF_TEST_RESULTS;
7986 			++num_pages_supported;
7987 		}
7988 		*page_ptr++ = PAGE_CODE_INFORMATION_EXCEPTIONS;
7989 		++num_pages_supported;
7990 		*page_ptr++ = PAGE_CODE_SMART_READ_DATA;
7991 		++num_pages_supported;
7992 		*page_ptr++ = PAGE_CODE_START_STOP_CYCLE_COUNTER;
7993 		++num_pages_supported;
7994 	}
7995 
7996 	lpp->param_len = num_pages_supported;
7997 
7998 	return ((&lpp->param_values[0] - (uint8_t *)lpp) +
7999 	    num_pages_supported);
8000 }
8001 
8002 /*
8003  * sata_build_lsense_page_10() is used to create the
8004  * SCSI LOG SENSE page 0x10 (self-test results)
8005  *
8006  * Takes a sata_drive_info t * and the address of a buffer
8007  * in which to create the page information as well as a sata_hba_inst_t *.
8008  *
8009  * Returns the number of bytes valid in the buffer.
8010  *
8011  * Note: Self test and SMART data is accessible in device log pages.
8012  * The log pages can be accessed by SMART READ/WRITE LOG (up to 255 sectors
8013  * of data can be transferred by a single command), or by the General Purpose
8014  * Logging commands (GPL) READ LOG EXT and WRITE LOG EXT (up to 65,535 sectors
8015  * - approximately 33MB - can be transferred by a single command.
8016  * The SCT Command response (either error or command) is the same for both
8017  * the SMART and GPL methods of issuing commands.
8018  * This function uses READ LOG EXT command when drive supports LBA48, and
8019  * SMART READ command otherwise.
8020  *
8021  * Since above commands are executed in a synchronous mode, this function
8022  * should not be called in an interrupt context.
8023  */
8024 static	int
8025 sata_build_lsense_page_10(
8026 	sata_drive_info_t *sdinfo,
8027 	uint8_t *buf,
8028 	sata_hba_inst_t *sata_hba_inst)
8029 {
8030 	struct log_parameter *lpp = (struct log_parameter *)buf;
8031 	int rval;
8032 
8033 	if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48) {
8034 		struct smart_ext_selftest_log *ext_selftest_log;
8035 
8036 		ext_selftest_log = kmem_zalloc(
8037 		    sizeof (struct smart_ext_selftest_log), KM_SLEEP);
8038 
8039 		rval = sata_ext_smart_selftest_read_log(sata_hba_inst, sdinfo,
8040 		    ext_selftest_log, 0);
8041 		if (rval == 0) {
8042 			int index, start_index;
8043 			struct smart_ext_selftest_log_entry *entry;
8044 			static const struct smart_ext_selftest_log_entry empty =
8045 			    {0};
8046 			uint16_t block_num;
8047 			int count;
8048 			boolean_t only_one_block = B_FALSE;
8049 
8050 			index = ext_selftest_log->
8051 			    smart_ext_selftest_log_index[0];
8052 			index |= ext_selftest_log->
8053 			    smart_ext_selftest_log_index[1] << 8;
8054 			if (index == 0)
8055 				goto out;
8056 
8057 			--index;	/* Correct for 0 origin */
8058 			start_index = index;	/* remember where we started */
8059 			block_num = index / ENTRIES_PER_EXT_SELFTEST_LOG_BLK;
8060 			if (block_num != 0) {
8061 				rval = sata_ext_smart_selftest_read_log(
8062 				    sata_hba_inst, sdinfo, ext_selftest_log,
8063 				    block_num);
8064 				if (rval != 0)
8065 					goto out;
8066 			}
8067 			index %= ENTRIES_PER_EXT_SELFTEST_LOG_BLK;
8068 			entry =
8069 			    &ext_selftest_log->
8070 			    smart_ext_selftest_log_entries[index];
8071 
8072 			for (count = 1;
8073 			    count <= SCSI_ENTRIES_IN_LOG_SENSE_SELFTEST_RESULTS;
8074 			    ++count) {
8075 				uint8_t status;
8076 				uint8_t code;
8077 				uint8_t sense_key;
8078 				uint8_t add_sense_code;
8079 				uint8_t add_sense_code_qual;
8080 
8081 				/* If this is an unused entry, we are done */
8082 				if (bcmp(entry, &empty, sizeof (empty)) == 0) {
8083 					/* Broken firmware on some disks */
8084 					if (index + 1 ==
8085 					    ENTRIES_PER_EXT_SELFTEST_LOG_BLK) {
8086 						--entry;
8087 						--index;
8088 						if (bcmp(entry, &empty,
8089 						    sizeof (empty)) == 0)
8090 							goto out;
8091 					} else
8092 						goto out;
8093 				}
8094 
8095 				if (only_one_block &&
8096 				    start_index == index)
8097 					goto out;
8098 
8099 				lpp->param_code[0] = 0;
8100 				lpp->param_code[1] = count;
8101 				lpp->param_ctrl_flags =
8102 				    LOG_CTRL_LP | LOG_CTRL_LBIN;
8103 				lpp->param_len =
8104 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN;
8105 
8106 				status = entry->smart_ext_selftest_log_status;
8107 				status >>= 4;
8108 				switch (status) {
8109 				case 0:
8110 				default:
8111 					sense_key = KEY_NO_SENSE;
8112 					add_sense_code =
8113 					    SD_SCSI_ASC_NO_ADD_SENSE;
8114 					add_sense_code_qual = 0;
8115 					break;
8116 				case 1:
8117 					sense_key = KEY_ABORTED_COMMAND;
8118 					add_sense_code =
8119 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8120 					add_sense_code_qual = SCSI_COMPONENT_81;
8121 					break;
8122 				case 2:
8123 					sense_key = KEY_ABORTED_COMMAND;
8124 					add_sense_code =
8125 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8126 					add_sense_code_qual = SCSI_COMPONENT_82;
8127 					break;
8128 				case 3:
8129 					sense_key = KEY_ABORTED_COMMAND;
8130 					add_sense_code =
8131 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8132 					add_sense_code_qual = SCSI_COMPONENT_83;
8133 					break;
8134 				case 4:
8135 					sense_key = KEY_HARDWARE_ERROR;
8136 					add_sense_code =
8137 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8138 					add_sense_code_qual = SCSI_COMPONENT_84;
8139 					break;
8140 				case 5:
8141 					sense_key = KEY_HARDWARE_ERROR;
8142 					add_sense_code =
8143 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8144 					add_sense_code_qual = SCSI_COMPONENT_85;
8145 					break;
8146 				case 6:
8147 					sense_key = KEY_HARDWARE_ERROR;
8148 					add_sense_code =
8149 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8150 					add_sense_code_qual = SCSI_COMPONENT_86;
8151 					break;
8152 				case 7:
8153 					sense_key = KEY_MEDIUM_ERROR;
8154 					add_sense_code =
8155 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8156 					add_sense_code_qual = SCSI_COMPONENT_87;
8157 					break;
8158 				case 8:
8159 					sense_key = KEY_HARDWARE_ERROR;
8160 					add_sense_code =
8161 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8162 					add_sense_code_qual = SCSI_COMPONENT_88;
8163 					break;
8164 				}
8165 				code = 0;	/* unspecified */
8166 				status |= (code << 4);
8167 				lpp->param_values[0] = status;
8168 				lpp->param_values[1] = 0; /* unspecified */
8169 				lpp->param_values[2] = entry->
8170 				    smart_ext_selftest_log_timestamp[1];
8171 				lpp->param_values[3] = entry->
8172 				    smart_ext_selftest_log_timestamp[0];
8173 				if (status != 0) {
8174 					lpp->param_values[4] = 0;
8175 					lpp->param_values[5] = 0;
8176 					lpp->param_values[6] = entry->
8177 					    smart_ext_selftest_log_failing_lba
8178 					    [5];
8179 					lpp->param_values[7] = entry->
8180 					    smart_ext_selftest_log_failing_lba
8181 					    [4];
8182 					lpp->param_values[8] = entry->
8183 					    smart_ext_selftest_log_failing_lba
8184 					    [3];
8185 					lpp->param_values[9] = entry->
8186 					    smart_ext_selftest_log_failing_lba
8187 					    [2];
8188 					lpp->param_values[10] = entry->
8189 					    smart_ext_selftest_log_failing_lba
8190 					    [1];
8191 					lpp->param_values[11] = entry->
8192 					    smart_ext_selftest_log_failing_lba
8193 					    [0];
8194 				} else {	/* No bad block address */
8195 					lpp->param_values[4] = 0xff;
8196 					lpp->param_values[5] = 0xff;
8197 					lpp->param_values[6] = 0xff;
8198 					lpp->param_values[7] = 0xff;
8199 					lpp->param_values[8] = 0xff;
8200 					lpp->param_values[9] = 0xff;
8201 					lpp->param_values[10] = 0xff;
8202 					lpp->param_values[11] = 0xff;
8203 				}
8204 
8205 				lpp->param_values[12] = sense_key;
8206 				lpp->param_values[13] = add_sense_code;
8207 				lpp->param_values[14] = add_sense_code_qual;
8208 				lpp->param_values[15] = 0; /* undefined */
8209 
8210 				lpp = (struct log_parameter *)
8211 				    (((uint8_t *)lpp) +
8212 				    SCSI_LOG_PARAM_HDR_LEN +
8213 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN);
8214 
8215 				--index;	/* Back up to previous entry */
8216 				if (index < 0) {
8217 					if (block_num > 0) {
8218 						--block_num;
8219 					} else {
8220 						struct read_log_ext_directory
8221 						    logdir;
8222 
8223 						rval =
8224 						    sata_read_log_ext_directory(
8225 						    sata_hba_inst, sdinfo,
8226 						    &logdir);
8227 						if (rval == -1)
8228 							goto out;
8229 						if ((logdir.read_log_ext_vers
8230 						    [0] == 0) &&
8231 						    (logdir.read_log_ext_vers
8232 						    [1] == 0))
8233 							goto out;
8234 						block_num =
8235 						    logdir.read_log_ext_nblks
8236 						    [EXT_SMART_SELFTEST_LOG_PAGE
8237 						    - 1][0];
8238 						block_num |= logdir.
8239 						    read_log_ext_nblks
8240 						    [EXT_SMART_SELFTEST_LOG_PAGE
8241 						    - 1][1] << 8;
8242 						--block_num;
8243 						only_one_block =
8244 						    (block_num == 0);
8245 					}
8246 					rval = sata_ext_smart_selftest_read_log(
8247 					    sata_hba_inst, sdinfo,
8248 					    ext_selftest_log, block_num);
8249 					if (rval != 0)
8250 						goto out;
8251 
8252 					index =
8253 					    ENTRIES_PER_EXT_SELFTEST_LOG_BLK -
8254 					    1;
8255 				}
8256 				index %= ENTRIES_PER_EXT_SELFTEST_LOG_BLK;
8257 				entry = &ext_selftest_log->
8258 				    smart_ext_selftest_log_entries[index];
8259 			}
8260 		}
8261 out:
8262 		kmem_free(ext_selftest_log,
8263 		    sizeof (struct smart_ext_selftest_log));
8264 	} else {
8265 		struct smart_selftest_log *selftest_log;
8266 
8267 		selftest_log = kmem_zalloc(sizeof (struct smart_selftest_log),
8268 		    KM_SLEEP);
8269 
8270 		rval = sata_smart_selftest_log(sata_hba_inst, sdinfo,
8271 		    selftest_log);
8272 
8273 		if (rval == 0) {
8274 			int index;
8275 			int count;
8276 			struct smart_selftest_log_entry *entry;
8277 			static const struct smart_selftest_log_entry empty =
8278 			    { 0 };
8279 
8280 			index = selftest_log->smart_selftest_log_index;
8281 			if (index == 0)
8282 				goto done;
8283 			--index;	/* Correct for 0 origin */
8284 			entry = &selftest_log->
8285 			    smart_selftest_log_entries[index];
8286 			for (count = 1;
8287 			    count <= SCSI_ENTRIES_IN_LOG_SENSE_SELFTEST_RESULTS;
8288 			    ++count) {
8289 				uint8_t status;
8290 				uint8_t code;
8291 				uint8_t sense_key;
8292 				uint8_t add_sense_code;
8293 				uint8_t add_sense_code_qual;
8294 
8295 				if (bcmp(entry, &empty, sizeof (empty)) == 0)
8296 					goto done;
8297 
8298 				lpp->param_code[0] = 0;
8299 				lpp->param_code[1] = count;
8300 				lpp->param_ctrl_flags =
8301 				    LOG_CTRL_LP | LOG_CTRL_LBIN;
8302 				lpp->param_len =
8303 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN;
8304 
8305 				status = entry->smart_selftest_log_status;
8306 				status >>= 4;
8307 				switch (status) {
8308 				case 0:
8309 				default:
8310 					sense_key = KEY_NO_SENSE;
8311 					add_sense_code =
8312 					    SD_SCSI_ASC_NO_ADD_SENSE;
8313 					break;
8314 				case 1:
8315 					sense_key = KEY_ABORTED_COMMAND;
8316 					add_sense_code =
8317 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8318 					add_sense_code_qual = SCSI_COMPONENT_81;
8319 					break;
8320 				case 2:
8321 					sense_key = KEY_ABORTED_COMMAND;
8322 					add_sense_code =
8323 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8324 					add_sense_code_qual = SCSI_COMPONENT_82;
8325 					break;
8326 				case 3:
8327 					sense_key = KEY_ABORTED_COMMAND;
8328 					add_sense_code =
8329 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8330 					add_sense_code_qual = SCSI_COMPONENT_83;
8331 					break;
8332 				case 4:
8333 					sense_key = KEY_HARDWARE_ERROR;
8334 					add_sense_code =
8335 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8336 					add_sense_code_qual = SCSI_COMPONENT_84;
8337 					break;
8338 				case 5:
8339 					sense_key = KEY_HARDWARE_ERROR;
8340 					add_sense_code =
8341 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8342 					add_sense_code_qual = SCSI_COMPONENT_85;
8343 					break;
8344 				case 6:
8345 					sense_key = KEY_HARDWARE_ERROR;
8346 					add_sense_code =
8347 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8348 					add_sense_code_qual = SCSI_COMPONENT_86;
8349 					break;
8350 				case 7:
8351 					sense_key = KEY_MEDIUM_ERROR;
8352 					add_sense_code =
8353 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8354 					add_sense_code_qual = SCSI_COMPONENT_87;
8355 					break;
8356 				case 8:
8357 					sense_key = KEY_HARDWARE_ERROR;
8358 					add_sense_code =
8359 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8360 					add_sense_code_qual = SCSI_COMPONENT_88;
8361 					break;
8362 				}
8363 				code = 0;	/* unspecified */
8364 				status |= (code << 4);
8365 				lpp->param_values[0] = status;
8366 				lpp->param_values[1] = 0; /* unspecified */
8367 				lpp->param_values[2] = entry->
8368 				    smart_selftest_log_timestamp[1];
8369 				lpp->param_values[3] = entry->
8370 				    smart_selftest_log_timestamp[0];
8371 				if (status != 0) {
8372 					lpp->param_values[4] = 0;
8373 					lpp->param_values[5] = 0;
8374 					lpp->param_values[6] = 0;
8375 					lpp->param_values[7] = 0;
8376 					lpp->param_values[8] = entry->
8377 					    smart_selftest_log_failing_lba[3];
8378 					lpp->param_values[9] = entry->
8379 					    smart_selftest_log_failing_lba[2];
8380 					lpp->param_values[10] = entry->
8381 					    smart_selftest_log_failing_lba[1];
8382 					lpp->param_values[11] = entry->
8383 					    smart_selftest_log_failing_lba[0];
8384 				} else {	/* No block address */
8385 					lpp->param_values[4] = 0xff;
8386 					lpp->param_values[5] = 0xff;
8387 					lpp->param_values[6] = 0xff;
8388 					lpp->param_values[7] = 0xff;
8389 					lpp->param_values[8] = 0xff;
8390 					lpp->param_values[9] = 0xff;
8391 					lpp->param_values[10] = 0xff;
8392 					lpp->param_values[11] = 0xff;
8393 				}
8394 				lpp->param_values[12] = sense_key;
8395 				lpp->param_values[13] = add_sense_code;
8396 				lpp->param_values[14] = add_sense_code_qual;
8397 				lpp->param_values[15] = 0; /* undefined */
8398 
8399 				lpp = (struct log_parameter *)
8400 				    (((uint8_t *)lpp) +
8401 				    SCSI_LOG_PARAM_HDR_LEN +
8402 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN);
8403 				--index;	/* back up to previous entry */
8404 				if (index < 0) {
8405 					index =
8406 					    NUM_SMART_SELFTEST_LOG_ENTRIES - 1;
8407 				}
8408 				entry = &selftest_log->
8409 				    smart_selftest_log_entries[index];
8410 			}
8411 		}
8412 done:
8413 		kmem_free(selftest_log, sizeof (struct smart_selftest_log));
8414 	}
8415 
8416 	return ((SCSI_LOG_PARAM_HDR_LEN + SCSI_LOG_SENSE_SELFTEST_PARAM_LEN) *
8417 	    SCSI_ENTRIES_IN_LOG_SENSE_SELFTEST_RESULTS);
8418 }
8419 
8420 /*
8421  * sata_build_lsense_page_2f() is used to create the
8422  * SCSI LOG SENSE page 0x2f (informational exceptions)
8423  *
8424  * Takes a sata_drive_info t * and the address of a buffer
8425  * in which to create the page information as well as a sata_hba_inst_t *.
8426  *
8427  * Returns the number of bytes valid in the buffer.
8428  *
8429  * Because it invokes function(s) that send synchronously executed command
8430  * to the HBA, it cannot be called in the interrupt context.
8431  */
8432 static	int
8433 sata_build_lsense_page_2f(
8434 	sata_drive_info_t *sdinfo,
8435 	uint8_t *buf,
8436 	sata_hba_inst_t *sata_hba_inst)
8437 {
8438 	struct log_parameter *lpp = (struct log_parameter *)buf;
8439 	int rval;
8440 	uint8_t *smart_data;
8441 	uint8_t temp;
8442 	sata_id_t *sata_id;
8443 #define	SMART_NO_TEMP	0xff
8444 
8445 	lpp->param_code[0] = 0;
8446 	lpp->param_code[1] = 0;
8447 	lpp->param_ctrl_flags = LOG_CTRL_LP | LOG_CTRL_LBIN;
8448 
8449 	/* Now get the SMART status w.r.t. threshold exceeded */
8450 	rval = sata_fetch_smart_return_status(sata_hba_inst, sdinfo);
8451 	switch (rval) {
8452 	case 1:
8453 		lpp->param_values[0] = SCSI_PREDICTED_FAILURE;
8454 		lpp->param_values[1] = SCSI_GENERAL_HD_FAILURE;
8455 		break;
8456 	case 0:
8457 	case -1:	/* failed to get data */
8458 		lpp->param_values[0] = 0;	/* No failure predicted */
8459 		lpp->param_values[1] = 0;
8460 		break;
8461 #if defined(SATA_DEBUG)
8462 	default:
8463 		cmn_err(CE_PANIC, "sata_build_lsense_page_2f bad return value");
8464 		/* NOTREACHED */
8465 #endif
8466 	}
8467 
8468 	sata_id = &sdinfo->satadrv_id;
8469 	if (! (sata_id->ai_sctsupport & SATA_SCT_CMD_TRANS_SUP))
8470 		temp = SMART_NO_TEMP;
8471 	else {
8472 		/* Now get the temperature */
8473 		smart_data = kmem_zalloc(512, KM_SLEEP);
8474 		rval = sata_smart_read_log(sata_hba_inst, sdinfo, smart_data,
8475 		    SCT_STATUS_LOG_PAGE, 1);
8476 		if (rval == -1)
8477 			temp = SMART_NO_TEMP;
8478 		else {
8479 			temp = smart_data[200];
8480 			if (temp & 0x80) {
8481 				if (temp & 0x7f)
8482 					temp = 0;
8483 				else
8484 					temp = SMART_NO_TEMP;
8485 			}
8486 		}
8487 		kmem_free(smart_data, 512);
8488 	}
8489 
8490 	lpp->param_values[2] = temp;	/* most recent temperature */
8491 	lpp->param_values[3] = 0;	/* required vendor specific byte */
8492 
8493 	lpp->param_len = SCSI_INFO_EXCEPTIONS_PARAM_LEN;
8494 
8495 
8496 	return (SCSI_INFO_EXCEPTIONS_PARAM_LEN + SCSI_LOG_PARAM_HDR_LEN);
8497 }
8498 
8499 /*
8500  * sata_build_lsense_page_30() is used to create the
8501  * SCSI LOG SENSE page 0x30 (Sun's vendor specific page for ATA SMART data).
8502  *
8503  * Takes a sata_drive_info t * and the address of a buffer
8504  * in which to create the page information as well as a sata_hba_inst_t *.
8505  *
8506  * Returns the number of bytes valid in the buffer.
8507  */
8508 static int
8509 sata_build_lsense_page_30(
8510 	sata_drive_info_t *sdinfo,
8511 	uint8_t *buf,
8512 	sata_hba_inst_t *sata_hba_inst)
8513 {
8514 	struct smart_data *smart_data = (struct smart_data *)buf;
8515 	int rval;
8516 
8517 	/* Now do the SMART READ DATA */
8518 	rval = sata_fetch_smart_data(sata_hba_inst, sdinfo, smart_data);
8519 	if (rval == -1)
8520 		return (0);
8521 
8522 	return (sizeof (struct smart_data));
8523 }
8524 
8525 /*
8526  * sata_build_lsense_page_0e() is used to create the
8527  * SCSI LOG SENSE page 0e (start-stop cycle counter page)
8528  *
8529  * Date of Manufacture (0x0001)
8530  *	YEAR = "0000"
8531  *	WEEK = "00"
8532  * Accounting Date (0x0002)
8533  *	6 ASCII space character(20h)
8534  * Specified cycle count over device lifetime
8535  *	VALUE - THRESH - the delta between max and min;
8536  * Accumulated start-stop cycles
8537  *	VALUE - WORST - the accumulated cycles;
8538  *
8539  * ID FLAG THRESH VALUE WORST RAW on start/stop counter attribute
8540  *
8541  * Takes a sata_drive_info t * and the address of a buffer
8542  * in which to create the page information as well as a sata_hba_inst_t *.
8543  *
8544  * Returns the number of bytes valid in the buffer.
8545  */
8546 static	int
8547 sata_build_lsense_page_0e(sata_drive_info_t *sdinfo, uint8_t *buf,
8548 	sata_pkt_txlate_t *spx)
8549 {
8550 	struct start_stop_cycle_counter_log *log_page;
8551 	int i, rval, index;
8552 	uint8_t smart_data[512], id, value, worst, thresh;
8553 	uint32_t max_count, cycles;
8554 
8555 	/* Now do the SMART READ DATA */
8556 	rval = sata_fetch_smart_data(spx->txlt_sata_hba_inst, sdinfo,
8557 	    (struct smart_data *)smart_data);
8558 	if (rval == -1)
8559 		return (0);
8560 	for (i = 0, id = 0; i < SMART_START_STOP_COUNT_ID * 2; i++) {
8561 		index = (i * 12) + 2;
8562 		id = smart_data[index];
8563 		if (id != SMART_START_STOP_COUNT_ID)
8564 			continue;
8565 		else {
8566 			thresh = smart_data[index + 2];
8567 			value = smart_data[index + 3];
8568 			worst = smart_data[index + 4];
8569 			break;
8570 		}
8571 	}
8572 	if (id != SMART_START_STOP_COUNT_ID)
8573 		return (0);
8574 	max_count = value - thresh;
8575 	cycles = value - worst;
8576 
8577 	log_page = (struct start_stop_cycle_counter_log *)buf;
8578 	bzero(log_page, sizeof (struct start_stop_cycle_counter_log));
8579 	log_page->code = 0x0e;
8580 	log_page->page_len_low = 0x24;
8581 
8582 	log_page->manufactor_date_low = 0x1;
8583 	log_page->param_1.fmt_link = 0x1; /* 01b */
8584 	log_page->param_len_1 = 0x06;
8585 	for (i = 0; i < 4; i++) {
8586 		log_page->year_manu[i] = 0x30;
8587 		if (i < 2)
8588 			log_page->week_manu[i] = 0x30;
8589 	}
8590 
8591 	log_page->account_date_low = 0x02;
8592 	log_page->param_2.fmt_link = 0x01; /* 01b */
8593 	log_page->param_len_2 = 0x06;
8594 	for (i = 0; i < 4; i++) {
8595 		log_page->year_account[i] = 0x20;
8596 		if (i < 2)
8597 			log_page->week_account[i] = 0x20;
8598 	}
8599 
8600 	log_page->lifetime_code_low = 0x03;
8601 	log_page->param_3.fmt_link = 0x03; /* 11b */
8602 	log_page->param_len_3 = 0x04;
8603 	/* VALUE - THRESH - the delta between max and min */
8604 	log_page->cycle_code_low = 0x04;
8605 	log_page->param_4.fmt_link = 0x03; /* 11b */
8606 	log_page->param_len_4 = 0x04;
8607 	/* WORST - THRESH - the distance from 'now' to min */
8608 
8609 	for (i = 0; i < 4; i++) {
8610 		log_page->cycle_lifetime[i] =
8611 		    (max_count >> (8 * (3 - i))) & 0xff;
8612 		log_page->cycle_accumulated[i] =
8613 		    (cycles >> (8 * (3 - i))) & 0xff;
8614 	}
8615 
8616 	return (sizeof (struct start_stop_cycle_counter_log));
8617 }
8618 
8619 /*
8620  * This function was used for build a ATA read verify sector command
8621  */
8622 static void
8623 sata_build_read_verify_cmd(sata_cmd_t *scmd, uint16_t sec, uint64_t lba)
8624 {
8625 	scmd->satacmd_cmd_reg = SATAC_RDVER;
8626 	scmd->satacmd_addr_type = ATA_ADDR_LBA28;
8627 	scmd->satacmd_flags.sata_special_regs = B_TRUE;
8628 
8629 	scmd->satacmd_sec_count_lsb = sec & 0xff;
8630 	scmd->satacmd_lba_low_lsb = lba & 0xff;
8631 	scmd->satacmd_lba_mid_lsb = (lba >> 8) & 0xff;
8632 	scmd->satacmd_lba_high_lsb = (lba >> 16) & 0xff;
8633 	scmd->satacmd_device_reg = (SATA_ADH_LBA | (lba >> 24) & 0xf);
8634 	scmd->satacmd_features_reg = 0;
8635 	scmd->satacmd_status_reg = 0;
8636 	scmd->satacmd_error_reg = 0;
8637 }
8638 
8639 /*
8640  * This function was used for building an ATA
8641  * command, and only command register need to
8642  * be defined, other register will be zero or na.
8643  */
8644 static void
8645 sata_build_generic_cmd(sata_cmd_t *scmd, uint8_t cmd)
8646 {
8647 	scmd->satacmd_addr_type = 0;
8648 	scmd->satacmd_cmd_reg = cmd;
8649 	scmd->satacmd_device_reg = 0;
8650 	scmd->satacmd_sec_count_lsb = 0;
8651 	scmd->satacmd_lba_low_lsb = 0;
8652 	scmd->satacmd_lba_mid_lsb = 0;
8653 	scmd->satacmd_lba_high_lsb = 0;
8654 	scmd->satacmd_features_reg = 0;
8655 	scmd->satacmd_status_reg = 0;
8656 	scmd->satacmd_error_reg = 0;
8657 	scmd->satacmd_flags.sata_special_regs = B_TRUE;
8658 }
8659 
8660 /*
8661  * This function was used for changing the standby
8662  * timer format from SCSI to ATA.
8663  */
8664 static uint8_t
8665 sata_get_standby_timer(uint8_t *timer)
8666 {
8667 	uint32_t i = 0, count = 0;
8668 	uint8_t ata_count;
8669 
8670 	for (i = 0; i < 4; i++) {
8671 		count = count << 8 | timer[i];
8672 	}
8673 
8674 	if (count == 0)
8675 		return (0);
8676 
8677 	if (count >= 1 && count <= 12000)
8678 		ata_count = (count -1) / 50 + 1;
8679 	else if (count > 12000 && count <= 12600)
8680 		ata_count = 0xfc;
8681 	else if (count > 12601 && count <= 12750)
8682 		ata_count = 0xff;
8683 	else if (count > 12750 && count <= 17999)
8684 		ata_count = 0xf1;
8685 	else if (count > 18000 && count <= 198000)
8686 		ata_count = count / 18000 + 240;
8687 	else
8688 		ata_count = 0xfd;
8689 	return (ata_count);
8690 }
8691 
8692 /* ************************** ATAPI-SPECIFIC FUNCTIONS ********************** */
8693 
8694 /*
8695  * Start command for ATAPI device.
8696  * This function processes scsi_pkt requests.
8697  * Now CD/DVD, tape and ATAPI disk devices are supported.
8698  * Most commands are packet without any translation into Packet Command.
8699  * Some may be trapped and executed as SATA commands (not clear which one).
8700  *
8701  * Returns TRAN_ACCEPT if command is accepted for execution (or completed
8702  * execution).
8703  * Returns other TRAN_XXXX codes if command is not accepted or completed
8704  * (see return values for sata_hba_start()).
8705  *
8706  * Note:
8707  * Inquiry cdb format differs between transport version 2 and 3.
8708  * However, the transport version 3 devices that were checked did not adhere
8709  * to the specification (ignored MSB of the allocation length). Therefore,
8710  * the transport version is not checked, but Inquiry allocation length is
8711  * truncated to 255 bytes if the original allocation length set-up by the
8712  * target driver is greater than 255 bytes.
8713  */
8714 static int
8715 sata_txlt_atapi(sata_pkt_txlate_t *spx)
8716 {
8717 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
8718 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
8719 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
8720 	sata_hba_inst_t *sata_hba = SATA_TXLT_HBA_INST(spx);
8721 	sata_drive_info_t *sdinfo = sata_get_device_info(sata_hba,
8722 	    &spx->txlt_sata_pkt->satapkt_device);
8723 	int cport = SATA_TXLT_CPORT(spx);
8724 	int cdblen;
8725 	int rval, reason;
8726 	int synch;
8727 	union scsi_cdb *cdbp = (union scsi_cdb *)scsipkt->pkt_cdbp;
8728 
8729 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
8730 
8731 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
8732 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
8733 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
8734 		return (rval);
8735 	}
8736 
8737 	/*
8738 	 * ATAPI device executes some ATA commands in addition to those
8739 	 * commands sent via PACKET command. These ATA commands may be
8740 	 * executed by the regular SATA translation functions. None needs
8741 	 * to be captured now.
8742 	 *
8743 	 * Commands sent via PACKET command include:
8744 	 *	MMC command set for ATAPI CD/DVD device
8745 	 *	SSC command set for ATAPI TAPE device
8746 	 *	SBC command set for ATAPI disk device
8747 	 *
8748 	 */
8749 
8750 	/* Check the size of cdb */
8751 
8752 	switch (GETGROUP(cdbp)) {
8753 	case CDB_GROUPID_3:   /* Reserved, per SPC-4 */
8754 		/*
8755 		 * opcodes 0x7e and 0x7f identify variable-length CDBs and
8756 		 * therefore require special handling.  Return failure, for now.
8757 		 */
8758 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
8759 		return (TRAN_BADPKT);
8760 
8761 	case CDB_GROUPID_6:   /* Vendor-specific, per SPC-4 */
8762 	case CDB_GROUPID_7:   /* Vendor-specific, per SPC-4 */
8763 		/* obtain length from the scsi_pkt */
8764 		cdblen = scsipkt->pkt_cdblen;
8765 		break;
8766 
8767 	default:
8768 		/* CDB's length is statically known, per SPC-4 */
8769 		cdblen = scsi_cdb_size[GETGROUP(cdbp)];
8770 		break;
8771 	}
8772 
8773 	if (cdblen <= 0 || cdblen > sdinfo->satadrv_atapi_cdb_len) {
8774 		sata_log(NULL, CE_WARN,
8775 		    "sata: invalid ATAPI cdb length %d",
8776 		    cdblen);
8777 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
8778 		return (TRAN_BADPKT);
8779 	}
8780 
8781 	SATAATAPITRACE(spx, cdblen);
8782 
8783 	/*
8784 	 * For non-read/write commands we need to
8785 	 * map buffer
8786 	 */
8787 	switch ((uint_t)scsipkt->pkt_cdbp[0]) {
8788 	case SCMD_READ:
8789 	case SCMD_READ_G1:
8790 	case SCMD_READ_G5:
8791 	case SCMD_READ_G4:
8792 	case SCMD_WRITE:
8793 	case SCMD_WRITE_G1:
8794 	case SCMD_WRITE_G5:
8795 	case SCMD_WRITE_G4:
8796 		break;
8797 	default:
8798 		if (bp != NULL) {
8799 			if (bp->b_flags & (B_PHYS | B_PAGEIO))
8800 				bp_mapin(bp);
8801 		}
8802 		break;
8803 	}
8804 	/*
8805 	 * scmd->satacmd_flags.sata_data_direction default -
8806 	 * SATA_DIR_NODATA_XFER - is set by
8807 	 * sata_txlt_generic_pkt_info().
8808 	 */
8809 	if (scmd->satacmd_bp) {
8810 		if (scmd->satacmd_bp->b_flags & B_READ) {
8811 			scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
8812 		} else {
8813 			scmd->satacmd_flags.sata_data_direction =
8814 			    SATA_DIR_WRITE;
8815 		}
8816 	}
8817 
8818 	/*
8819 	 * Set up ATAPI packet command.
8820 	 */
8821 
8822 	sata_atapi_packet_cmd_setup(scmd, sdinfo);
8823 
8824 	/* Copy cdb into sata_cmd */
8825 	scmd->satacmd_acdb_len = sdinfo->satadrv_atapi_cdb_len;
8826 	bzero(scmd->satacmd_acdb, SATA_ATAPI_MAX_CDB_LEN);
8827 	bcopy(cdbp, scmd->satacmd_acdb, cdblen);
8828 
8829 	/* See note in the command header */
8830 	if (scmd->satacmd_acdb[0] == SCMD_INQUIRY) {
8831 		if (scmd->satacmd_acdb[3] != 0)
8832 			scmd->satacmd_acdb[4] = 255;
8833 	}
8834 
8835 #ifdef SATA_DEBUG
8836 	if (sata_debug_flags & SATA_DBG_ATAPI) {
8837 		uint8_t *p = scmd->satacmd_acdb;
8838 		char buf[3 * SATA_ATAPI_MAX_CDB_LEN];
8839 
8840 		(void) snprintf(buf, SATA_ATAPI_MAX_CDB_LEN,
8841 		    "%02x %02x %02x %02x %02x %02x %02x %02x "
8842 		    "%2x %02x %02x %02x %02x %02x %02x %02x",
8843 		    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
8844 		    p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
8845 		buf[(3 * SATA_ATAPI_MAX_CDB_LEN) - 1] = '\0';
8846 		cmn_err(CE_NOTE, "ATAPI cdb: %s\n", buf);
8847 	}
8848 #endif
8849 
8850 	/*
8851 	 * Preset request sense data to NO SENSE.
8852 	 * If there is no way to get error information via Request Sense,
8853 	 * the packet request sense data would not have to be modified by HBA,
8854 	 * but it could be returned as is.
8855 	 */
8856 	bzero(scmd->satacmd_rqsense, SATA_ATAPI_RQSENSE_LEN);
8857 	sata_fixed_sense_data_preset(
8858 	    (struct scsi_extended_sense *)scmd->satacmd_rqsense);
8859 
8860 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
8861 		/* Need callback function */
8862 		spx->txlt_sata_pkt->satapkt_comp = sata_txlt_atapi_completion;
8863 		synch = FALSE;
8864 	} else
8865 		synch = TRUE;
8866 
8867 	/* Transfer command to HBA */
8868 	if (sata_hba_start(spx, &rval) != 0) {
8869 		/* Pkt not accepted for execution */
8870 		mutex_exit(&SATA_CPORT_MUTEX(sata_hba, cport));
8871 		return (rval);
8872 	}
8873 	mutex_exit(&SATA_CPORT_MUTEX(sata_hba, cport));
8874 	/*
8875 	 * If execution is non-synchronous,
8876 	 * a callback function will handle potential errors, translate
8877 	 * the response and will do a callback to a target driver.
8878 	 * If it was synchronous, use the same framework callback to check
8879 	 * an execution status.
8880 	 */
8881 	if (synch) {
8882 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
8883 		    "synchronous execution status %x\n",
8884 		    spx->txlt_sata_pkt->satapkt_reason);
8885 		sata_txlt_atapi_completion(spx->txlt_sata_pkt);
8886 	}
8887 	return (TRAN_ACCEPT);
8888 }
8889 
8890 
8891 /*
8892  * ATAPI Packet command completion.
8893  *
8894  * Failure of the command passed via Packet command are considered device
8895  * error. SATA HBA driver would have to retrieve error data (via Request
8896  * Sense command delivered via error retrieval sata packet) and copy it
8897  * to satacmd_rqsense array. From there, it is moved into scsi pkt sense data.
8898  */
8899 static void
8900 sata_txlt_atapi_completion(sata_pkt_t *sata_pkt)
8901 {
8902 	sata_pkt_txlate_t *spx =
8903 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
8904 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
8905 	struct scsi_extended_sense *sense;
8906 	struct buf *bp;
8907 	int rval;
8908 
8909 #ifdef SATA_DEBUG
8910 	uint8_t *rqsp = sata_pkt->satapkt_cmd.satacmd_rqsense;
8911 #endif
8912 
8913 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
8914 	    STATE_SENT_CMD | STATE_GOT_STATUS;
8915 
8916 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
8917 		/* Normal completion */
8918 		if (sata_pkt->satapkt_cmd.satacmd_bp != NULL)
8919 			scsipkt->pkt_state |= STATE_XFERRED_DATA;
8920 		scsipkt->pkt_reason = CMD_CMPLT;
8921 		*scsipkt->pkt_scbp = STATUS_GOOD;
8922 		if (spx->txlt_tmp_buf != NULL) {
8923 			/* Temporary buffer was used */
8924 			bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
8925 			if (bp->b_flags & B_READ) {
8926 				rval = ddi_dma_sync(
8927 				    spx->txlt_buf_dma_handle, 0, 0,
8928 				    DDI_DMA_SYNC_FORCPU);
8929 				ASSERT(rval == DDI_SUCCESS);
8930 				bcopy(spx->txlt_tmp_buf, bp->b_un.b_addr,
8931 				    bp->b_bcount);
8932 			}
8933 		}
8934 	} else {
8935 		/*
8936 		 * Something went wrong - analyze return
8937 		 */
8938 		*scsipkt->pkt_scbp = STATUS_CHECK;
8939 		sense = sata_arq_sense(spx);
8940 
8941 		if (sata_pkt->satapkt_reason == SATA_PKT_DEV_ERROR) {
8942 			/*
8943 			 * pkt_reason should be CMD_CMPLT for DEVICE ERROR.
8944 			 * Under this condition ERR bit is set for ATA command,
8945 			 * and CHK bit set for ATAPI command.
8946 			 *
8947 			 * Please check st_intr & sdintr about how pkt_reason
8948 			 * is used.
8949 			 */
8950 			scsipkt->pkt_reason = CMD_CMPLT;
8951 
8952 			/*
8953 			 * We may not have ARQ data if there was a double
8954 			 * error. But sense data in sata packet was pre-set
8955 			 * with NO SENSE so it is valid even if HBA could
8956 			 * not retrieve a real sense data.
8957 			 * Just copy this sense data into scsi pkt sense area.
8958 			 */
8959 			bcopy(sata_pkt->satapkt_cmd.satacmd_rqsense, sense,
8960 			    SATA_ATAPI_MIN_RQSENSE_LEN);
8961 #ifdef SATA_DEBUG
8962 			if (sata_debug_flags & SATA_DBG_SCSI_IF) {
8963 				sata_log(spx->txlt_sata_hba_inst, CE_WARN,
8964 				    "sata_txlt_atapi_completion: %02x\n"
8965 				    "RQSENSE:  %02x %02x %02x %02x %02x %02x "
8966 				    "          %02x %02x %02x %02x %02x %02x "
8967 				    "          %02x %02x %02x %02x %02x %02x\n",
8968 				    scsipkt->pkt_reason,
8969 				    rqsp[0], rqsp[1], rqsp[2], rqsp[3],
8970 				    rqsp[4], rqsp[5], rqsp[6], rqsp[7],
8971 				    rqsp[8], rqsp[9], rqsp[10], rqsp[11],
8972 				    rqsp[12], rqsp[13], rqsp[14], rqsp[15],
8973 				    rqsp[16], rqsp[17]);
8974 			}
8975 #endif
8976 		} else {
8977 			switch (sata_pkt->satapkt_reason) {
8978 			case SATA_PKT_PORT_ERROR:
8979 				/*
8980 				 * We have no device data.
8981 				 */
8982 				scsipkt->pkt_reason = CMD_INCOMPLETE;
8983 				scsipkt->pkt_state &= ~(STATE_GOT_BUS |
8984 				    STATE_GOT_TARGET | STATE_SENT_CMD |
8985 				    STATE_GOT_STATUS);
8986 				sense->es_key = KEY_HARDWARE_ERROR;
8987 				break;
8988 
8989 			case SATA_PKT_TIMEOUT:
8990 				scsipkt->pkt_reason = CMD_TIMEOUT;
8991 				scsipkt->pkt_statistics |=
8992 				    STAT_TIMEOUT | STAT_DEV_RESET;
8993 				/*
8994 				 * Need to check if HARDWARE_ERROR/
8995 				 * TIMEOUT_ON_LOGICAL_UNIT 4/3E/2 would be more
8996 				 * appropriate.
8997 				 */
8998 				break;
8999 
9000 			case SATA_PKT_ABORTED:
9001 				scsipkt->pkt_reason = CMD_ABORTED;
9002 				scsipkt->pkt_statistics |= STAT_ABORTED;
9003 				/* Should we set key COMMAND_ABPRTED? */
9004 				break;
9005 
9006 			case SATA_PKT_RESET:
9007 				scsipkt->pkt_reason = CMD_RESET;
9008 				scsipkt->pkt_statistics |= STAT_DEV_RESET;
9009 				/*
9010 				 * May be we should set Unit Attention /
9011 				 * Reset. Perhaps the same should be
9012 				 * returned for disks....
9013 				 */
9014 				sense->es_key = KEY_UNIT_ATTENTION;
9015 				sense->es_add_code = SD_SCSI_ASC_RESET;
9016 				break;
9017 
9018 			default:
9019 				SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
9020 				    "sata_txlt_atapi_completion: "
9021 				    "invalid packet completion reason"));
9022 				scsipkt->pkt_reason = CMD_TRAN_ERR;
9023 				scsipkt->pkt_state &= ~(STATE_GOT_BUS |
9024 				    STATE_GOT_TARGET | STATE_SENT_CMD |
9025 				    STATE_GOT_STATUS);
9026 				break;
9027 			}
9028 		}
9029 	}
9030 
9031 	SATAATAPITRACE(spx, 0);
9032 
9033 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
9034 	    scsipkt->pkt_comp != NULL) {
9035 		/* scsi callback required */
9036 		(*scsipkt->pkt_comp)(scsipkt);
9037 	}
9038 }
9039 
9040 /*
9041  * Set up error retrieval sata command for ATAPI Packet Command error data
9042  * recovery.
9043  *
9044  * Returns SATA_SUCCESS when data buffer is allocated and packet set-up,
9045  * returns SATA_FAILURE otherwise.
9046  */
9047 
9048 static int
9049 sata_atapi_err_ret_cmd_setup(sata_pkt_txlate_t *spx, sata_drive_info_t *sdinfo)
9050 {
9051 	sata_pkt_t *spkt = spx->txlt_sata_pkt;
9052 	sata_cmd_t *scmd;
9053 	struct buf *bp;
9054 
9055 	/*
9056 	 * Allocate dma-able buffer error data.
9057 	 * Buffer allocation will take care of buffer alignment and other DMA
9058 	 * attributes.
9059 	 */
9060 	bp = sata_alloc_local_buffer(spx, SATA_ATAPI_MIN_RQSENSE_LEN);
9061 	if (bp == NULL) {
9062 		SATADBG1(SATA_DBG_ATAPI, spx->txlt_sata_hba_inst,
9063 		    "sata_get_err_retrieval_pkt: "
9064 		    "cannot allocate buffer for error data", NULL);
9065 		return (SATA_FAILURE);
9066 	}
9067 	bp_mapin(bp); /* make data buffer accessible */
9068 
9069 	/* Operation modes are up to the caller */
9070 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
9071 
9072 	/* Synchronous mode, no callback - may be changed by the caller */
9073 	spkt->satapkt_comp = NULL;
9074 	spkt->satapkt_time = sata_default_pkt_time;
9075 
9076 	scmd = &spkt->satapkt_cmd;
9077 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
9078 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
9079 
9080 	sata_atapi_packet_cmd_setup(scmd, sdinfo);
9081 
9082 	/*
9083 	 * Set-up acdb. Request Sense CDB (packet command content) is
9084 	 * not in DMA-able buffer. Its handling is HBA-specific (how
9085 	 * it is transfered into packet FIS).
9086 	 */
9087 	scmd->satacmd_acdb_len = sdinfo->satadrv_atapi_cdb_len;
9088 	bcopy(sata_rqsense_cdb, scmd->satacmd_acdb, SATA_ATAPI_RQSENSE_CDB_LEN);
9089 	/* Following zeroing of pad bytes may not be necessary */
9090 	bzero(&scmd->satacmd_acdb[SATA_ATAPI_RQSENSE_CDB_LEN],
9091 	    sdinfo->satadrv_atapi_cdb_len - SATA_ATAPI_RQSENSE_CDB_LEN);
9092 
9093 	/*
9094 	 * Set-up pointer to the buffer handle, so HBA can sync buffer
9095 	 * before accessing it. Handle is in usual place in translate struct.
9096 	 */
9097 	scmd->satacmd_err_ret_buf_handle = &spx->txlt_buf_dma_handle;
9098 
9099 	/*
9100 	 * Preset request sense data to NO SENSE.
9101 	 * Here it is redundant, only for a symetry with scsi-originated
9102 	 * packets. It should not be used for anything but debugging.
9103 	 */
9104 	bzero(scmd->satacmd_rqsense, SATA_ATAPI_RQSENSE_LEN);
9105 	sata_fixed_sense_data_preset(
9106 	    (struct scsi_extended_sense *)scmd->satacmd_rqsense);
9107 
9108 	ASSERT(scmd->satacmd_num_dma_cookies != 0);
9109 	ASSERT(scmd->satacmd_dma_cookie_list != NULL);
9110 
9111 	return (SATA_SUCCESS);
9112 }
9113 
9114 /*
9115  * Set-up ATAPI packet command.
9116  * Data transfer direction has to be set-up in sata_cmd structure prior to
9117  * calling this function.
9118  *
9119  * Returns void
9120  */
9121 
9122 static void
9123 sata_atapi_packet_cmd_setup(sata_cmd_t *scmd, sata_drive_info_t *sdinfo)
9124 {
9125 	scmd->satacmd_addr_type = 0;		/* N/A */
9126 	scmd->satacmd_sec_count_lsb = 0;	/* no tag */
9127 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
9128 	scmd->satacmd_lba_mid_lsb = (uint8_t)SATA_ATAPI_MAX_BYTES_PER_DRQ;
9129 	scmd->satacmd_lba_high_lsb =
9130 	    (uint8_t)(SATA_ATAPI_MAX_BYTES_PER_DRQ >> 8);
9131 	scmd->satacmd_cmd_reg = SATAC_PACKET;	/* Command */
9132 
9133 	/*
9134 	 * We want all data to be transfered via DMA.
9135 	 * But specify it only if drive supports DMA and DMA mode is
9136 	 * selected - some drives are sensitive about it.
9137 	 * Hopefully it wil work for all drives....
9138 	 */
9139 	if (sdinfo->satadrv_settings & SATA_DEV_DMA)
9140 		scmd->satacmd_features_reg = SATA_ATAPI_F_DMA;
9141 
9142 	/*
9143 	 * Features register requires special care for devices that use
9144 	 * Serial ATA bridge - they need an explicit specification of
9145 	 * the data transfer direction for Packet DMA commands.
9146 	 * Setting this bit is harmless if DMA is not used.
9147 	 *
9148 	 * Many drives do not implement word 80, specifying what ATA/ATAPI
9149 	 * spec they follow.
9150 	 * We are arbitrarily following the latest SerialATA 2.6 spec,
9151 	 * which uses ATA/ATAPI 6 specification for Identify Data, unless
9152 	 * ATA/ATAPI-7 support is explicitly indicated.
9153 	 */
9154 	if (sdinfo->satadrv_id.ai_majorversion != 0 &&
9155 	    sdinfo->satadrv_id.ai_majorversion != 0xffff &&
9156 	    (sdinfo->satadrv_id.ai_majorversion & SATA_MAJVER_7) != 0) {
9157 		/*
9158 		 * Specification of major version is valid and version 7
9159 		 * is supported. It does automatically imply that all
9160 		 * spec features are supported. For now, we assume that
9161 		 * DMADIR setting is valid. ATA/ATAPI7 spec is incomplete.
9162 		 */
9163 		if ((sdinfo->satadrv_id.ai_dirdma &
9164 		    SATA_ATAPI_ID_DMADIR_REQ) != 0) {
9165 			if (scmd->satacmd_flags.sata_data_direction ==
9166 			    SATA_DIR_READ)
9167 			scmd->satacmd_features_reg |=
9168 			    SATA_ATAPI_F_DATA_DIR_READ;
9169 		}
9170 	}
9171 }
9172 
9173 
9174 #ifdef SATA_DEBUG
9175 
9176 /* Display 18 bytes of Inquiry data */
9177 static void
9178 sata_show_inqry_data(uint8_t *buf)
9179 {
9180 	struct scsi_inquiry *inq = (struct scsi_inquiry *)buf;
9181 	uint8_t *p;
9182 
9183 	cmn_err(CE_NOTE, "Inquiry data:");
9184 	cmn_err(CE_NOTE, "device type %x", inq->inq_dtype);
9185 	cmn_err(CE_NOTE, "removable media %x", inq->inq_rmb);
9186 	cmn_err(CE_NOTE, "version %x", inq->inq_ansi);
9187 	cmn_err(CE_NOTE, "ATAPI transport version %d",
9188 	    SATA_ATAPI_TRANS_VERSION(inq));
9189 	cmn_err(CE_NOTE, "response data format %d, aenc %d",
9190 	    inq->inq_rdf, inq->inq_aenc);
9191 	cmn_err(CE_NOTE, " additional length %d", inq->inq_len);
9192 	cmn_err(CE_NOTE, "tpgs %d", inq->inq_tpgs);
9193 	p = (uint8_t *)inq->inq_vid;
9194 	cmn_err(CE_NOTE, "vendor id (binary): %02x %02x %02x %02x "
9195 	    "%02x %02x %02x %02x",
9196 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7]);
9197 	p = (uint8_t *)inq->inq_vid;
9198 	cmn_err(CE_NOTE, "vendor id: %c %c %c %c %c %c %c %c",
9199 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7]);
9200 
9201 	p = (uint8_t *)inq->inq_pid;
9202 	cmn_err(CE_NOTE, "product id (binary): %02x %02x %02x %02x "
9203 	    "%02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x",
9204 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
9205 	    p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
9206 	p = (uint8_t *)inq->inq_pid;
9207 	cmn_err(CE_NOTE, "product id: %c %c %c %c %c %c %c %c "
9208 	    "%c %c %c %c %c %c %c %c",
9209 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
9210 	    p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
9211 
9212 	p = (uint8_t *)inq->inq_revision;
9213 	cmn_err(CE_NOTE, "revision (binary): %02x %02x %02x %02x",
9214 	    p[0], p[1], p[2], p[3]);
9215 	p = (uint8_t *)inq->inq_revision;
9216 	cmn_err(CE_NOTE, "revision: %c %c %c %c",
9217 	    p[0], p[1], p[2], p[3]);
9218 
9219 }
9220 
9221 
9222 static void
9223 sata_save_atapi_trace(sata_pkt_txlate_t *spx, int count)
9224 {
9225 	struct scsi_pkt *scsi_pkt = spx->txlt_scsi_pkt;
9226 
9227 	if (scsi_pkt == NULL)
9228 		return;
9229 	if (count != 0) {
9230 		/* saving cdb */
9231 		bzero(sata_atapi_trace[sata_atapi_trace_index].acdb,
9232 		    SATA_ATAPI_MAX_CDB_LEN);
9233 		bcopy(scsi_pkt->pkt_cdbp,
9234 		    sata_atapi_trace[sata_atapi_trace_index].acdb, count);
9235 	} else {
9236 		bcopy(&((struct scsi_arq_status *)scsi_pkt->pkt_scbp)->
9237 		    sts_sensedata,
9238 		    sata_atapi_trace[sata_atapi_trace_index].arqs,
9239 		    SATA_ATAPI_MIN_RQSENSE_LEN);
9240 		sata_atapi_trace[sata_atapi_trace_index].scsi_pkt_reason =
9241 		    scsi_pkt->pkt_reason;
9242 		sata_atapi_trace[sata_atapi_trace_index].sata_pkt_reason =
9243 		    spx->txlt_sata_pkt->satapkt_reason;
9244 
9245 		if (++sata_atapi_trace_index >= 64)
9246 			sata_atapi_trace_index = 0;
9247 	}
9248 }
9249 
9250 #endif
9251 
9252 /*
9253  * Fetch inquiry data from ATAPI device
9254  * Returns SATA_SUCCESS if operation was successfull, SATA_FAILURE otherwise.
9255  *
9256  * Note:
9257  * inqb pointer does not point to a DMA-able buffer. It is a local buffer
9258  * where the caller expects to see the inquiry data.
9259  *
9260  */
9261 
9262 static int
9263 sata_get_atapi_inquiry_data(sata_hba_inst_t *sata_hba,
9264     sata_address_t *saddr, struct scsi_inquiry *inq)
9265 {
9266 	sata_pkt_txlate_t *spx;
9267 	sata_pkt_t *spkt;
9268 	struct buf *bp;
9269 	sata_drive_info_t *sdinfo;
9270 	sata_cmd_t *scmd;
9271 	int rval;
9272 	uint8_t *rqsp;
9273 #ifdef SATA_DEBUG
9274 	char msg_buf[MAXPATHLEN];
9275 #endif
9276 
9277 	ASSERT(sata_hba != NULL);
9278 
9279 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
9280 	spx->txlt_sata_hba_inst = sata_hba;
9281 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
9282 	spkt = sata_pkt_alloc(spx, NULL);
9283 	if (spkt == NULL) {
9284 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
9285 		return (SATA_FAILURE);
9286 	}
9287 	/* address is needed now */
9288 	spkt->satapkt_device.satadev_addr = *saddr;
9289 
9290 	/* scsi_inquiry size buffer */
9291 	bp = sata_alloc_local_buffer(spx, sizeof (struct scsi_inquiry));
9292 	if (bp == NULL) {
9293 		sata_pkt_free(spx);
9294 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
9295 		SATA_LOG_D((sata_hba, CE_WARN,
9296 		    "sata_get_atapi_inquiry_data: "
9297 		    "cannot allocate data buffer"));
9298 		return (SATA_FAILURE);
9299 	}
9300 	bp_mapin(bp); /* make data buffer accessible */
9301 
9302 	scmd = &spkt->satapkt_cmd;
9303 	ASSERT(scmd->satacmd_num_dma_cookies != 0);
9304 	ASSERT(scmd->satacmd_dma_cookie_list != NULL);
9305 
9306 	/* Use synchronous mode */
9307 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
9308 	spkt->satapkt_comp = NULL;
9309 	spkt->satapkt_time = sata_default_pkt_time;
9310 
9311 	/* Issue inquiry command - 6 bytes cdb, data transfer, read */
9312 
9313 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
9314 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
9315 
9316 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
9317 	sdinfo = sata_get_device_info(sata_hba,
9318 	    &spx->txlt_sata_pkt->satapkt_device);
9319 	if (sdinfo == NULL) {
9320 		/* we have to be carefull about the disapearing device */
9321 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
9322 		rval = SATA_FAILURE;
9323 		goto cleanup;
9324 	}
9325 	sata_atapi_packet_cmd_setup(scmd, sdinfo);
9326 
9327 	/*
9328 	 * Set-up acdb. This works for atapi transport version 2 and later.
9329 	 */
9330 	scmd->satacmd_acdb_len = sdinfo->satadrv_atapi_cdb_len;
9331 	bzero(scmd->satacmd_acdb, SATA_ATAPI_MAX_CDB_LEN);
9332 	scmd->satacmd_acdb[0] = 0x12;	/* Inquiry */
9333 	scmd->satacmd_acdb[1] = 0x00;
9334 	scmd->satacmd_acdb[2] = 0x00;
9335 	scmd->satacmd_acdb[3] = 0x00;
9336 	scmd->satacmd_acdb[4] = sizeof (struct scsi_inquiry);
9337 	scmd->satacmd_acdb[5] = 0x00;
9338 
9339 	sata_fixed_sense_data_preset(
9340 	    (struct scsi_extended_sense *)scmd->satacmd_rqsense);
9341 
9342 	/* Transfer command to HBA */
9343 	if (sata_hba_start(spx, &rval) != 0) {
9344 		/* Pkt not accepted for execution */
9345 		SATADBG1(SATA_DBG_ATAPI, sata_hba,
9346 		    "sata_get_atapi_inquiry_data: "
9347 		    "Packet not accepted for execution - ret: %02x", rval);
9348 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
9349 		rval = SATA_FAILURE;
9350 		goto cleanup;
9351 	}
9352 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
9353 
9354 	if (spkt->satapkt_reason == SATA_PKT_COMPLETED) {
9355 		SATADBG1(SATA_DBG_ATAPI, sata_hba,
9356 		    "sata_get_atapi_inquiry_data: "
9357 		    "Packet completed successfully - ret: %02x", rval);
9358 		if (spx->txlt_buf_dma_handle != NULL) {
9359 			/*
9360 			 * Sync buffer. Handle is in usual place in translate
9361 			 * struct.
9362 			 */
9363 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
9364 			    DDI_DMA_SYNC_FORCPU);
9365 			ASSERT(rval == DDI_SUCCESS);
9366 		}
9367 		/*
9368 		 * Normal completion - copy data into caller's buffer
9369 		 */
9370 		bcopy(bp->b_un.b_addr, (uint8_t *)inq,
9371 		    sizeof (struct scsi_inquiry));
9372 #ifdef SATA_DEBUG
9373 		if (sata_debug_flags & SATA_DBG_ATAPI) {
9374 			sata_show_inqry_data((uint8_t *)inq);
9375 		}
9376 #endif
9377 		rval = SATA_SUCCESS;
9378 	} else {
9379 		/*
9380 		 * Something went wrong - analyze return - check rqsense data
9381 		 */
9382 		rval = SATA_FAILURE;
9383 		if (spkt->satapkt_reason == SATA_PKT_DEV_ERROR) {
9384 			/*
9385 			 * ARQ data hopefull show something other than NO SENSE
9386 			 */
9387 			rqsp = scmd->satacmd_rqsense;
9388 #ifdef SATA_DEBUG
9389 			if (sata_debug_flags & SATA_DBG_ATAPI) {
9390 				msg_buf[0] = '\0';
9391 				(void) snprintf(msg_buf, MAXPATHLEN,
9392 				    "ATAPI packet completion reason: %02x\n"
9393 				    "RQSENSE:  %02x %02x %02x %02x %02x %02x\n"
9394 				    "          %02x %02x %02x %02x %02x %02x\n"
9395 				    "          %02x %02x %02x %02x %02x %02x",
9396 				    spkt->satapkt_reason,
9397 				    rqsp[0], rqsp[1], rqsp[2], rqsp[3],
9398 				    rqsp[4], rqsp[5], rqsp[6], rqsp[7],
9399 				    rqsp[8], rqsp[9], rqsp[10], rqsp[11],
9400 				    rqsp[12], rqsp[13], rqsp[14], rqsp[15],
9401 				    rqsp[16], rqsp[17]);
9402 				sata_log(spx->txlt_sata_hba_inst, CE_WARN,
9403 				    "%s", msg_buf);
9404 			}
9405 #endif
9406 		} else {
9407 			switch (spkt->satapkt_reason) {
9408 			case SATA_PKT_PORT_ERROR:
9409 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
9410 				    "sata_get_atapi_inquiry_data: "
9411 				    "packet reason: port error", NULL);
9412 				break;
9413 
9414 			case SATA_PKT_TIMEOUT:
9415 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
9416 				    "sata_get_atapi_inquiry_data: "
9417 				    "packet reason: timeout", NULL);
9418 				break;
9419 
9420 			case SATA_PKT_ABORTED:
9421 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
9422 				    "sata_get_atapi_inquiry_data: "
9423 				    "packet reason: aborted", NULL);
9424 				break;
9425 
9426 			case SATA_PKT_RESET:
9427 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
9428 				    "sata_get_atapi_inquiry_data: "
9429 				    "packet reason: reset\n", NULL);
9430 				break;
9431 			default:
9432 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
9433 				    "sata_get_atapi_inquiry_data: "
9434 				    "invalid packet reason: %02x\n",
9435 				    spkt->satapkt_reason);
9436 				break;
9437 			}
9438 		}
9439 	}
9440 cleanup:
9441 	sata_free_local_buffer(spx);
9442 	sata_pkt_free(spx);
9443 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
9444 	return (rval);
9445 }
9446 
9447 
9448 
9449 
9450 
9451 #if 0
9452 #ifdef SATA_DEBUG
9453 
9454 /*
9455  * Test ATAPI packet command.
9456  * Single threaded test: send packet command in synch mode, process completion
9457  *
9458  */
9459 static void
9460 sata_test_atapi_packet_command(sata_hba_inst_t *sata_hba_inst, int cport)
9461 {
9462 	sata_pkt_txlate_t *spx;
9463 	sata_pkt_t *spkt;
9464 	struct buf *bp;
9465 	sata_device_t sata_device;
9466 	sata_drive_info_t *sdinfo;
9467 	sata_cmd_t *scmd;
9468 	int rval;
9469 	uint8_t *rqsp;
9470 
9471 	ASSERT(sata_hba_inst != NULL);
9472 	sata_device.satadev_addr.cport = cport;
9473 	sata_device.satadev_addr.pmport = 0;
9474 	sata_device.satadev_addr.qual = SATA_ADDR_DCPORT;
9475 	sata_device.satadev_rev = SATA_DEVICE_REV;
9476 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
9477 	sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
9478 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
9479 	if (sdinfo == NULL) {
9480 		sata_log(sata_hba_inst, CE_WARN,
9481 		    "sata_test_atapi_packet_command: "
9482 		    "no device info for cport %d",
9483 		    sata_device.satadev_addr.cport);
9484 		return;
9485 	}
9486 
9487 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
9488 	spx->txlt_sata_hba_inst = sata_hba_inst;
9489 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
9490 	spkt = sata_pkt_alloc(spx, NULL);
9491 	if (spkt == NULL) {
9492 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
9493 		return;
9494 	}
9495 	/* address is needed now */
9496 	spkt->satapkt_device.satadev_addr = sata_device.satadev_addr;
9497 
9498 	/* 1024k buffer */
9499 	bp = sata_alloc_local_buffer(spx, 1024);
9500 	if (bp == NULL) {
9501 		sata_pkt_free(spx);
9502 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
9503 		sata_log(sata_hba_inst, CE_WARN,
9504 		    "sata_test_atapi_packet_command: "
9505 		    "cannot allocate data buffer");
9506 		return;
9507 	}
9508 	bp_mapin(bp); /* make data buffer accessible */
9509 
9510 	scmd = &spkt->satapkt_cmd;
9511 	ASSERT(scmd->satacmd_num_dma_cookies != 0);
9512 	ASSERT(scmd->satacmd_dma_cookie_list != NULL);
9513 
9514 	/* Use synchronous mode */
9515 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
9516 
9517 	/* Synchronous mode, no callback - may be changed by the caller */
9518 	spkt->satapkt_comp = NULL;
9519 	spkt->satapkt_time = sata_default_pkt_time;
9520 
9521 	/* Issue inquiry command - 6 bytes cdb, data transfer, read */
9522 
9523 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
9524 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
9525 
9526 	sata_atapi_packet_cmd_setup(scmd, sdinfo);
9527 
9528 	/* Set-up acdb. */
9529 	scmd->satacmd_acdb_len = sdinfo->satadrv_atapi_cdb_len;
9530 	bzero(scmd->satacmd_acdb, SATA_ATAPI_MAX_CDB_LEN);
9531 	scmd->satacmd_acdb[0] = 0x12;	/* Inquiry */
9532 	scmd->satacmd_acdb[1] = 0x00;
9533 	scmd->satacmd_acdb[2] = 0x00;
9534 	scmd->satacmd_acdb[3] = 0x00;
9535 	scmd->satacmd_acdb[4] = sizeof (struct scsi_inquiry);
9536 	scmd->satacmd_acdb[5] = 0x00;
9537 
9538 	sata_fixed_sense_data_preset(
9539 	    (struct scsi_extended_sense *)scmd->satacmd_rqsense);
9540 
9541 	/* Transfer command to HBA */
9542 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
9543 	if (sata_hba_start(spx, &rval) != 0) {
9544 		/* Pkt not accepted for execution */
9545 		sata_log(sata_hba_inst, CE_WARN,
9546 		    "sata_test_atapi_packet_command: "
9547 		    "Packet not accepted for execution - ret: %02x", rval);
9548 		mutex_exit(
9549 		    &SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
9550 		goto cleanup;
9551 	}
9552 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
9553 
9554 	if (spx->txlt_buf_dma_handle != NULL) {
9555 		/*
9556 		 * Sync buffer. Handle is in usual place in translate struct.
9557 		 */
9558 		rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
9559 		    DDI_DMA_SYNC_FORCPU);
9560 		ASSERT(rval == DDI_SUCCESS);
9561 	}
9562 	if (spkt->satapkt_reason == SATA_PKT_COMPLETED) {
9563 		sata_log(sata_hba_inst, CE_WARN,
9564 		    "sata_test_atapi_packet_command: "
9565 		    "Packet completed successfully");
9566 		/*
9567 		 * Normal completion - show inquiry data
9568 		 */
9569 		sata_show_inqry_data((uint8_t *)bp->b_un.b_addr);
9570 	} else {
9571 		/*
9572 		 * Something went wrong - analyze return - check rqsense data
9573 		 */
9574 		if (spkt->satapkt_reason == SATA_PKT_DEV_ERROR) {
9575 			/*
9576 			 * ARQ data hopefull show something other than NO SENSE
9577 			 */
9578 			rqsp = scmd->satacmd_rqsense;
9579 			sata_log(spx->txlt_sata_hba_inst, CE_WARN,
9580 			    "ATAPI packet completion reason: %02x\n"
9581 			    "RQSENSE:  %02x %02x %02x %02x %02x %02x "
9582 			    "          %02x %02x %02x %02x %02x %02x "
9583 			    "          %02x %02x %02x %02x %02x %02x\n",
9584 			    spkt->satapkt_reason,
9585 			    rqsp[0], rqsp[1], rqsp[2], rqsp[3],
9586 			    rqsp[4], rqsp[5], rqsp[6], rqsp[7],
9587 			    rqsp[8], rqsp[9], rqsp[10], rqsp[11],
9588 			    rqsp[12], rqsp[13], rqsp[14], rqsp[15],
9589 			    rqsp[16], rqsp[17]);
9590 		} else {
9591 			switch (spkt->satapkt_reason) {
9592 			case SATA_PKT_PORT_ERROR:
9593 				sata_log(sata_hba_inst, CE_WARN,
9594 				    "sata_test_atapi_packet_command: "
9595 				    "packet reason: port error\n");
9596 				break;
9597 
9598 			case SATA_PKT_TIMEOUT:
9599 				sata_log(sata_hba_inst, CE_WARN,
9600 				    "sata_test_atapi_packet_command: "
9601 				    "packet reason: timeout\n");
9602 				break;
9603 
9604 			case SATA_PKT_ABORTED:
9605 				sata_log(sata_hba_inst, CE_WARN,
9606 				    "sata_test_atapi_packet_command: "
9607 				    "packet reason: aborted\n");
9608 				break;
9609 
9610 			case SATA_PKT_RESET:
9611 				sata_log(sata_hba_inst, CE_WARN,
9612 				    "sata_test_atapi_packet_command: "
9613 				    "packet reason: reset\n");
9614 				break;
9615 			default:
9616 				sata_log(sata_hba_inst, CE_WARN,
9617 				    "sata_test_atapi_packet_command: "
9618 				    "invalid packet reason: %02x\n",
9619 				    spkt->satapkt_reason);
9620 				break;
9621 			}
9622 		}
9623 	}
9624 cleanup:
9625 	sata_free_local_buffer(spx);
9626 	sata_pkt_free(spx);
9627 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
9628 }
9629 
9630 #endif /* SATA_DEBUG */
9631 #endif /* 1 */
9632 
9633 
9634 /* ************************** LOCAL HELPER FUNCTIONS *********************** */
9635 
9636 /*
9637  * Validate sata_tran info
9638  * SATA_FAILURE returns if structure is inconsistent or structure revision
9639  * does not match one used by the framework.
9640  *
9641  * Returns SATA_SUCCESS if sata_hba_tran has matching revision and contains
9642  * required function pointers.
9643  * Returns SATA_FAILURE otherwise.
9644  */
9645 static int
9646 sata_validate_sata_hba_tran(dev_info_t *dip, sata_hba_tran_t *sata_tran)
9647 {
9648 	/*
9649 	 * SATA_TRAN_HBA_REV is the current (highest) revision number
9650 	 * of the SATA interface.
9651 	 */
9652 	if (sata_tran->sata_tran_hba_rev > SATA_TRAN_HBA_REV) {
9653 		sata_log(NULL, CE_WARN,
9654 		    "sata: invalid sata_hba_tran version %d for driver %s",
9655 		    sata_tran->sata_tran_hba_rev, ddi_driver_name(dip));
9656 		return (SATA_FAILURE);
9657 	}
9658 
9659 	if (dip != sata_tran->sata_tran_hba_dip) {
9660 		SATA_LOG_D((NULL, CE_WARN,
9661 		    "sata: inconsistent sata_tran_hba_dip "
9662 		    "%p / %p", sata_tran->sata_tran_hba_dip, dip));
9663 		return (SATA_FAILURE);
9664 	}
9665 
9666 	if (sata_tran->sata_tran_probe_port == NULL ||
9667 	    sata_tran->sata_tran_start == NULL ||
9668 	    sata_tran->sata_tran_abort == NULL ||
9669 	    sata_tran->sata_tran_reset_dport == NULL ||
9670 	    sata_tran->sata_tran_hotplug_ops == NULL ||
9671 	    sata_tran->sata_tran_hotplug_ops->sata_tran_port_activate == NULL ||
9672 	    sata_tran->sata_tran_hotplug_ops->sata_tran_port_deactivate ==
9673 	    NULL) {
9674 		SATA_LOG_D((NULL, CE_WARN, "sata: sata_hba_tran missing "
9675 		    "required functions"));
9676 	}
9677 	return (SATA_SUCCESS);
9678 }
9679 
9680 /*
9681  * Remove HBA instance from sata_hba_list.
9682  */
9683 static void
9684 sata_remove_hba_instance(dev_info_t *dip)
9685 {
9686 	sata_hba_inst_t	*sata_hba_inst;
9687 
9688 	mutex_enter(&sata_mutex);
9689 	for (sata_hba_inst = sata_hba_list;
9690 	    sata_hba_inst != (struct sata_hba_inst *)NULL;
9691 	    sata_hba_inst = sata_hba_inst->satahba_next) {
9692 		if (sata_hba_inst->satahba_dip == dip)
9693 			break;
9694 	}
9695 
9696 	if (sata_hba_inst == (struct sata_hba_inst *)NULL) {
9697 #ifdef SATA_DEBUG
9698 		cmn_err(CE_WARN, "sata_remove_hba_instance: "
9699 		    "unknown HBA instance\n");
9700 #endif
9701 		ASSERT(FALSE);
9702 	}
9703 	if (sata_hba_inst == sata_hba_list) {
9704 		sata_hba_list = sata_hba_inst->satahba_next;
9705 		if (sata_hba_list) {
9706 			sata_hba_list->satahba_prev =
9707 			    (struct sata_hba_inst *)NULL;
9708 		}
9709 		if (sata_hba_inst == sata_hba_list_tail) {
9710 			sata_hba_list_tail = NULL;
9711 		}
9712 	} else if (sata_hba_inst == sata_hba_list_tail) {
9713 		sata_hba_list_tail = sata_hba_inst->satahba_prev;
9714 		if (sata_hba_list_tail) {
9715 			sata_hba_list_tail->satahba_next =
9716 			    (struct sata_hba_inst *)NULL;
9717 		}
9718 	} else {
9719 		sata_hba_inst->satahba_prev->satahba_next =
9720 		    sata_hba_inst->satahba_next;
9721 		sata_hba_inst->satahba_next->satahba_prev =
9722 		    sata_hba_inst->satahba_prev;
9723 	}
9724 	mutex_exit(&sata_mutex);
9725 }
9726 
9727 /*
9728  * Probe all SATA ports of the specified HBA instance.
9729  * The assumption is that there are no target and attachment point minor nodes
9730  * created by the boot subsystems, so we do not need to prune device tree.
9731  *
9732  * This function is called only from sata_hba_attach(). It does not have to
9733  * be protected by controller mutex, because the hba_attached flag is not set
9734  * yet and no one would be touching this HBA instance other than this thread.
9735  * Determines if port is active and what type of the device is attached
9736  * (if any). Allocates necessary structures for each port.
9737  *
9738  * An AP (Attachement Point) node is created for each SATA device port even
9739  * when there is no device attached.
9740  */
9741 
9742 static 	void
9743 sata_probe_ports(sata_hba_inst_t *sata_hba_inst)
9744 {
9745 	dev_info_t		*dip = SATA_DIP(sata_hba_inst);
9746 	int			ncport;
9747 	sata_cport_info_t 	*cportinfo;
9748 	sata_drive_info_t	*drive;
9749 	sata_device_t		sata_device;
9750 	int			rval;
9751 	dev_t			minor_number;
9752 	char			name[16];
9753 	clock_t			start_time, cur_time;
9754 
9755 	/*
9756 	 * Probe controller ports first, to find port status and
9757 	 * any port multiplier attached.
9758 	 */
9759 	for (ncport = 0; ncport < SATA_NUM_CPORTS(sata_hba_inst); ncport++) {
9760 		/* allocate cport structure */
9761 		cportinfo = kmem_zalloc(sizeof (sata_cport_info_t), KM_SLEEP);
9762 		ASSERT(cportinfo != NULL);
9763 		mutex_init(&cportinfo->cport_mutex, NULL, MUTEX_DRIVER, NULL);
9764 
9765 		mutex_enter(&cportinfo->cport_mutex);
9766 
9767 		cportinfo->cport_addr.cport = ncport;
9768 		cportinfo->cport_addr.pmport = 0;
9769 		cportinfo->cport_addr.qual = SATA_ADDR_CPORT;
9770 		cportinfo->cport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
9771 		cportinfo->cport_state |= SATA_STATE_PROBING;
9772 		SATA_CPORT_INFO(sata_hba_inst, ncport) = cportinfo;
9773 
9774 		/*
9775 		 * Regardless if a port is usable or not, create
9776 		 * an attachment point
9777 		 */
9778 		mutex_exit(&cportinfo->cport_mutex);
9779 		minor_number = SATA_MAKE_AP_MINOR(ddi_get_instance(dip),
9780 		    ncport, 0, SATA_ADDR_CPORT);
9781 		(void) sprintf(name, "%d", ncport);
9782 		if (ddi_create_minor_node(dip, name, S_IFCHR,
9783 		    minor_number, DDI_NT_SATA_ATTACHMENT_POINT, 0) !=
9784 		    DDI_SUCCESS) {
9785 			sata_log(sata_hba_inst, CE_WARN, "sata_hba_attach: "
9786 			    "cannot create SATA attachment point for port %d",
9787 			    ncport);
9788 		}
9789 
9790 		/* Probe port */
9791 		start_time = ddi_get_lbolt();
9792 	reprobe_cport:
9793 		sata_device.satadev_addr.cport = ncport;
9794 		sata_device.satadev_addr.pmport = 0;
9795 		sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
9796 		sata_device.satadev_rev = SATA_DEVICE_REV;
9797 
9798 		rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
9799 		    (dip, &sata_device);
9800 
9801 		mutex_enter(&cportinfo->cport_mutex);
9802 		cportinfo->cport_scr = sata_device.satadev_scr;
9803 		if (rval != SATA_SUCCESS) {
9804 			/* Something went wrong? Fail the port */
9805 			cportinfo->cport_state = SATA_PSTATE_FAILED;
9806 			mutex_exit(&cportinfo->cport_mutex);
9807 			continue;
9808 		}
9809 		cportinfo->cport_state &= ~SATA_STATE_PROBING;
9810 		cportinfo->cport_state |= SATA_STATE_PROBED;
9811 		cportinfo->cport_dev_type = sata_device.satadev_type;
9812 
9813 		cportinfo->cport_state |= SATA_STATE_READY;
9814 		if (cportinfo->cport_dev_type == SATA_DTYPE_NONE) {
9815 			mutex_exit(&cportinfo->cport_mutex);
9816 			continue;
9817 		}
9818 		if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
9819 			/*
9820 			 * There is some device attached.
9821 			 * Allocate device info structure
9822 			 */
9823 			if (SATA_CPORTINFO_DRV_INFO(cportinfo) == NULL) {
9824 				mutex_exit(&cportinfo->cport_mutex);
9825 				SATA_CPORTINFO_DRV_INFO(cportinfo) =
9826 				    kmem_zalloc(sizeof (sata_drive_info_t),
9827 				    KM_SLEEP);
9828 				mutex_enter(&cportinfo->cport_mutex);
9829 			}
9830 			drive = SATA_CPORTINFO_DRV_INFO(cportinfo);
9831 			drive->satadrv_addr = cportinfo->cport_addr;
9832 			drive->satadrv_addr.qual = SATA_ADDR_DCPORT;
9833 			drive->satadrv_type = cportinfo->cport_dev_type;
9834 			drive->satadrv_state = SATA_STATE_UNKNOWN;
9835 
9836 			mutex_exit(&cportinfo->cport_mutex);
9837 			if (sata_add_device(dip, sata_hba_inst, &sata_device) !=
9838 			    SATA_SUCCESS) {
9839 				/*
9840 				 * Plugged device was not correctly identified.
9841 				 * Retry, within a SATA_DEV_IDENTIFY_TIMEOUT
9842 				 */
9843 				cur_time = ddi_get_lbolt();
9844 				if ((cur_time - start_time) <
9845 				    drv_usectohz(SATA_DEV_IDENTIFY_TIMEOUT)) {
9846 					/* sleep for a while */
9847 					delay(drv_usectohz(
9848 					    SATA_DEV_RETRY_DLY));
9849 					goto reprobe_cport;
9850 				}
9851 			}
9852 		} else { /* SATA_DTYPE_PMULT */
9853 			mutex_exit(&cportinfo->cport_mutex);
9854 
9855 			/* Allocate sata_pmult_info and sata_pmport_info */
9856 			if (sata_alloc_pmult(sata_hba_inst, &sata_device) !=
9857 			    SATA_SUCCESS)
9858 				continue;
9859 
9860 			/* Log the information of the port multiplier */
9861 			sata_show_pmult_info(sata_hba_inst, &sata_device);
9862 
9863 			/* Probe its pmports */
9864 			sata_probe_pmports(sata_hba_inst, ncport);
9865 		}
9866 	}
9867 }
9868 
9869 /*
9870  * Probe all device ports behind a port multiplier.
9871  *
9872  * PMult-related structure should be allocated before by sata_alloc_pmult().
9873  *
9874  * NOTE1: Only called from sata_probe_ports()
9875  * NOTE2: No mutex should be hold.
9876  */
9877 static void
9878 sata_probe_pmports(sata_hba_inst_t *sata_hba_inst, uint8_t ncport)
9879 {
9880 	dev_info_t		*dip = SATA_DIP(sata_hba_inst);
9881 	sata_pmult_info_t	*pmultinfo = NULL;
9882 	sata_pmport_info_t 	*pmportinfo = NULL;
9883 	sata_drive_info_t	*drive = NULL;
9884 	sata_device_t		sata_device;
9885 
9886 	clock_t			start_time, cur_time;
9887 	int			npmport;
9888 	int			rval;
9889 
9890 	pmultinfo = SATA_PMULT_INFO(sata_hba_inst, ncport);
9891 
9892 	/* Probe Port Multiplier ports */
9893 	for (npmport = 0; npmport < pmultinfo->pmult_num_dev_ports; npmport++) {
9894 		pmportinfo = pmultinfo->pmult_dev_port[npmport];
9895 		start_time = ddi_get_lbolt();
9896 reprobe_pmport:
9897 		sata_device.satadev_addr.cport = ncport;
9898 		sata_device.satadev_addr.pmport = npmport;
9899 		sata_device.satadev_addr.qual = SATA_ADDR_PMPORT;
9900 		sata_device.satadev_rev = SATA_DEVICE_REV;
9901 
9902 		/* Let HBA driver probe it. */
9903 		rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
9904 		    (dip, &sata_device);
9905 		mutex_enter(&pmportinfo->pmport_mutex);
9906 
9907 		pmportinfo->pmport_scr = sata_device.satadev_scr;
9908 
9909 		if (rval != SATA_SUCCESS) {
9910 			pmportinfo->pmport_state =
9911 			    SATA_PSTATE_FAILED;
9912 			mutex_exit(&pmportinfo->pmport_mutex);
9913 			continue;
9914 		}
9915 		pmportinfo->pmport_state &= ~SATA_STATE_PROBING;
9916 		pmportinfo->pmport_state |= SATA_STATE_PROBED;
9917 		pmportinfo->pmport_dev_type = sata_device.satadev_type;
9918 
9919 		pmportinfo->pmport_state |= SATA_STATE_READY;
9920 		if (pmportinfo->pmport_dev_type ==
9921 		    SATA_DTYPE_NONE) {
9922 			SATADBG2(SATA_DBG_PMULT, sata_hba_inst,
9923 			    "no device found at port %d:%d", ncport, npmport);
9924 			mutex_exit(&pmportinfo->pmport_mutex);
9925 			continue;
9926 		}
9927 		/* Port multipliers cannot be chained */
9928 		ASSERT(pmportinfo->pmport_dev_type != SATA_DTYPE_PMULT);
9929 		/*
9930 		 * There is something attached to Port
9931 		 * Multiplier device port
9932 		 * Allocate device info structure
9933 		 */
9934 		if (pmportinfo->pmport_sata_drive == NULL) {
9935 			mutex_exit(&pmportinfo->pmport_mutex);
9936 			pmportinfo->pmport_sata_drive =
9937 			    kmem_zalloc(sizeof (sata_drive_info_t), KM_SLEEP);
9938 			mutex_enter(&pmportinfo->pmport_mutex);
9939 		}
9940 		drive = pmportinfo->pmport_sata_drive;
9941 		drive->satadrv_addr.cport = pmportinfo->pmport_addr.cport;
9942 		drive->satadrv_addr.pmport = npmport;
9943 		drive->satadrv_addr.qual = SATA_ADDR_DPMPORT;
9944 		drive->satadrv_type = pmportinfo-> pmport_dev_type;
9945 		drive->satadrv_state = SATA_STATE_UNKNOWN;
9946 
9947 		mutex_exit(&pmportinfo->pmport_mutex);
9948 		rval = sata_add_device(dip, sata_hba_inst, &sata_device);
9949 
9950 		if (rval != SATA_SUCCESS) {
9951 			/*
9952 			 * Plugged device was not correctly identified.
9953 			 * Retry, within the SATA_DEV_IDENTIFY_TIMEOUT
9954 			 */
9955 			cur_time = ddi_get_lbolt();
9956 			if ((cur_time - start_time) < drv_usectohz(
9957 			    SATA_DEV_IDENTIFY_TIMEOUT)) {
9958 				/* sleep for a while */
9959 				delay(drv_usectohz(SATA_DEV_RETRY_DLY));
9960 				goto reprobe_pmport;
9961 			}
9962 		}
9963 	}
9964 }
9965 
9966 /*
9967  * Add SATA device for specified HBA instance & port (SCSI target
9968  * device nodes).
9969  * This function is called (indirectly) only from sata_hba_attach().
9970  * A target node is created when there is a supported type device attached,
9971  * but may be removed if it cannot be put online.
9972  *
9973  * This function cannot be called from an interrupt context.
9974  *
9975  * Create target nodes for disk, CD/DVD, Tape and ATAPI disk devices
9976  *
9977  * Returns SATA_SUCCESS when port/device was fully processed, SATA_FAILURE when
9978  * device identification failed - adding a device could be retried.
9979  *
9980  */
9981 static 	int
9982 sata_add_device(dev_info_t *pdip, sata_hba_inst_t *sata_hba_inst,
9983     sata_device_t *sata_device)
9984 {
9985 	sata_cport_info_t 	*cportinfo;
9986 	sata_pmult_info_t	*pminfo;
9987 	sata_pmport_info_t	*pmportinfo;
9988 	dev_info_t		*cdip;		/* child dip */
9989 	sata_address_t		*saddr = &sata_device->satadev_addr;
9990 	uint8_t			cport, pmport;
9991 	int			rval;
9992 
9993 	cport = saddr->cport;
9994 	pmport = saddr->pmport;
9995 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
9996 	ASSERT(cportinfo->cport_dev_type != SATA_DTYPE_NONE);
9997 
9998 	/*
9999 	 * Some device is attached to a controller port.
10000 	 * We rely on controllers distinquishing between no-device,
10001 	 * attached port multiplier and other kind of attached device.
10002 	 * We need to get Identify Device data and determine
10003 	 * positively the dev type before trying to attach
10004 	 * the target driver.
10005 	 */
10006 	sata_device->satadev_rev = SATA_DEVICE_REV;
10007 	switch (saddr->qual) {
10008 	case SATA_ADDR_CPORT:
10009 		/*
10010 		 * Add a non-port-multiplier device at controller port.
10011 		 */
10012 		saddr->qual = SATA_ADDR_DCPORT;
10013 
10014 		rval = sata_probe_device(sata_hba_inst, sata_device);
10015 		if (rval != SATA_SUCCESS ||
10016 		    sata_device->satadev_type == SATA_DTYPE_UNKNOWN)
10017 			return (SATA_FAILURE);
10018 
10019 		mutex_enter(&cportinfo->cport_mutex);
10020 		sata_show_drive_info(sata_hba_inst,
10021 		    SATA_CPORTINFO_DRV_INFO(cportinfo));
10022 
10023 		if ((sata_device->satadev_type & SATA_VALID_DEV_TYPE) == 0) {
10024 			/*
10025 			 * Could not determine device type or
10026 			 * a device is not supported.
10027 			 * Degrade this device to unknown.
10028 			 */
10029 			cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
10030 			mutex_exit(&cportinfo->cport_mutex);
10031 			return (SATA_SUCCESS);
10032 		}
10033 		cportinfo->cport_dev_type = sata_device->satadev_type;
10034 		cportinfo->cport_tgtnode_clean = B_TRUE;
10035 		mutex_exit(&cportinfo->cport_mutex);
10036 
10037 		/*
10038 		 * Initialize device to the desired state. Even if it
10039 		 * fails, the device will still attach but syslog
10040 		 * will show the warning.
10041 		 */
10042 		if (sata_initialize_device(sata_hba_inst,
10043 		    SATA_CPORTINFO_DRV_INFO(cportinfo)) != SATA_SUCCESS) {
10044 			/* Retry */
10045 			rval = sata_initialize_device(sata_hba_inst,
10046 			    SATA_CPORTINFO_DRV_INFO(cportinfo));
10047 
10048 			if (rval == SATA_RETRY)
10049 				sata_log(sata_hba_inst, CE_WARN,
10050 				    "SATA device at port %d - "
10051 				    "default device features could not be set."
10052 				    " Device may not operate as expected.",
10053 				    cport);
10054 		}
10055 
10056 		cdip = sata_create_target_node(pdip, sata_hba_inst, saddr);
10057 		if (cdip == NULL) {
10058 			/*
10059 			 * Attaching target node failed.
10060 			 * We retain sata_drive_info structure...
10061 			 */
10062 			return (SATA_SUCCESS);
10063 		}
10064 
10065 		mutex_enter(&cportinfo->cport_mutex);
10066 		(SATA_CPORTINFO_DRV_INFO(cportinfo))->
10067 		    satadrv_state = SATA_STATE_READY;
10068 		mutex_exit(&cportinfo->cport_mutex);
10069 
10070 		break;
10071 
10072 	case SATA_ADDR_PMPORT:
10073 		saddr->qual = SATA_ADDR_DPMPORT;
10074 
10075 		mutex_enter(&cportinfo->cport_mutex);
10076 		/* It must be a Port Multiplier at the controller port */
10077 		ASSERT(cportinfo->cport_dev_type == SATA_DTYPE_PMULT);
10078 
10079 		pminfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
10080 		pmportinfo = pminfo->pmult_dev_port[saddr->pmport];
10081 		mutex_exit(&cportinfo->cport_mutex);
10082 
10083 		rval = sata_probe_device(sata_hba_inst, sata_device);
10084 		if (rval != SATA_SUCCESS ||
10085 		    sata_device->satadev_type == SATA_DTYPE_UNKNOWN) {
10086 			return (SATA_FAILURE);
10087 		}
10088 
10089 		mutex_enter(&pmportinfo->pmport_mutex);
10090 		sata_show_drive_info(sata_hba_inst,
10091 		    SATA_PMPORTINFO_DRV_INFO(pmportinfo));
10092 
10093 		if ((sata_device->satadev_type & SATA_VALID_DEV_TYPE) == 0) {
10094 			/*
10095 			 * Could not determine device type.
10096 			 * Degrade this device to unknown.
10097 			 */
10098 			pmportinfo->pmport_dev_type = SATA_DTYPE_UNKNOWN;
10099 			mutex_exit(&pmportinfo->pmport_mutex);
10100 			return (SATA_SUCCESS);
10101 		}
10102 		pmportinfo->pmport_dev_type = sata_device->satadev_type;
10103 		pmportinfo->pmport_tgtnode_clean = B_TRUE;
10104 		mutex_exit(&pmportinfo->pmport_mutex);
10105 
10106 		/*
10107 		 * Initialize device to the desired state.
10108 		 * Even if it fails, the device will still
10109 		 * attach but syslog will show the warning.
10110 		 */
10111 		if (sata_initialize_device(sata_hba_inst,
10112 		    pmportinfo->pmport_sata_drive) != SATA_SUCCESS) {
10113 			/* Retry */
10114 			rval = sata_initialize_device(sata_hba_inst,
10115 			    pmportinfo->pmport_sata_drive);
10116 
10117 			if (rval == SATA_RETRY)
10118 				sata_log(sata_hba_inst, CE_WARN,
10119 				    "SATA device at port %d:%d - "
10120 				    "default device features could not be set."
10121 				    " Device may not operate as expected.",
10122 				    cport, pmport);
10123 		}
10124 
10125 		cdip = sata_create_target_node(pdip, sata_hba_inst, saddr);
10126 		if (cdip == NULL) {
10127 			/*
10128 			 * Attaching target node failed.
10129 			 * We retain sata_drive_info structure...
10130 			 */
10131 			return (SATA_SUCCESS);
10132 		}
10133 		mutex_enter(&pmportinfo->pmport_mutex);
10134 		pmportinfo->pmport_sata_drive->satadrv_state |=
10135 		    SATA_STATE_READY;
10136 		mutex_exit(&pmportinfo->pmport_mutex);
10137 
10138 		break;
10139 
10140 	default:
10141 		return (SATA_FAILURE);
10142 	}
10143 
10144 	return (SATA_SUCCESS);
10145 }
10146 
10147 /*
10148  * Clean up target node at specific address.
10149  *
10150  * NOTE: No Mutex should be hold.
10151  */
10152 static int
10153 sata_offline_device(sata_hba_inst_t *sata_hba_inst,
10154     sata_device_t *sata_device, sata_drive_info_t *sdinfo)
10155 {
10156 	uint8_t cport, pmport, qual;
10157 	dev_info_t *tdip;
10158 
10159 	cport = sata_device->satadev_addr.cport;
10160 	pmport = sata_device->satadev_addr.pmport;
10161 	qual = sata_device->satadev_addr.qual;
10162 
10163 	if (qual == SATA_ADDR_DCPORT) {
10164 		SATA_LOG_D((sata_hba_inst, CE_WARN,
10165 		    "sata_hba_ioctl: disconnect device at port %d", cport));
10166 	} else {
10167 		SATA_LOG_D((sata_hba_inst, CE_WARN,
10168 		    "sata_hba_ioctl: disconnect device at port %d:%d",
10169 		    cport, pmport));
10170 	}
10171 
10172 	/* We are addressing attached device, not a port */
10173 	sata_device->satadev_addr.qual =
10174 	    sdinfo->satadrv_addr.qual;
10175 	tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
10176 	    &sata_device->satadev_addr);
10177 	if (tdip != NULL && ndi_devi_offline(tdip,
10178 	    NDI_DEVI_REMOVE) != NDI_SUCCESS) {
10179 		/*
10180 		 * Problem :
10181 		 * The target node remained attached.
10182 		 * This happens when the device file was open
10183 		 * or a node was waiting for resources.
10184 		 * Cannot do anything about it.
10185 		 */
10186 		if (qual == SATA_ADDR_DCPORT) {
10187 			SATA_LOG_D((sata_hba_inst, CE_WARN,
10188 			    "sata_hba_ioctl: disconnect: could "
10189 			    "not unconfigure device before "
10190 			    "disconnecting the SATA port %d",
10191 			    cport));
10192 		} else {
10193 			SATA_LOG_D((sata_hba_inst, CE_WARN,
10194 			    "sata_hba_ioctl: disconnect: could "
10195 			    "not unconfigure device before "
10196 			    "disconnecting the SATA port %d:%d",
10197 			    cport, pmport));
10198 		}
10199 		/*
10200 		 * Set DEVICE REMOVED state in the target
10201 		 * node. It will prevent access to the device
10202 		 * even when a new device is attached, until
10203 		 * the old target node is released, removed and
10204 		 * recreated for a new  device.
10205 		 */
10206 		sata_set_device_removed(tdip);
10207 
10208 		/*
10209 		 * Instruct event daemon to try the target
10210 		 * node cleanup later.
10211 		 */
10212 		sata_set_target_node_cleanup(
10213 		    sata_hba_inst, &sata_device->satadev_addr);
10214 	}
10215 
10216 
10217 	return (SATA_SUCCESS);
10218 }
10219 
10220 
10221 /*
10222  * Create scsi target node for attached device, create node properties and
10223  * attach the node.
10224  * The node could be removed if the device onlining fails.
10225  *
10226  * A dev_info_t pointer is returned if operation is successful, NULL is
10227  * returned otherwise.
10228  */
10229 
10230 static dev_info_t *
10231 sata_create_target_node(dev_info_t *dip, sata_hba_inst_t *sata_hba_inst,
10232 			sata_address_t *sata_addr)
10233 {
10234 	dev_info_t *cdip = NULL;
10235 	int rval;
10236 	char *nname = NULL;
10237 	char **compatible = NULL;
10238 	int ncompatible;
10239 	struct scsi_inquiry inq;
10240 	sata_device_t sata_device;
10241 	sata_drive_info_t *sdinfo;
10242 	int target;
10243 	int i;
10244 
10245 	sata_device.satadev_rev = SATA_DEVICE_REV;
10246 	sata_device.satadev_addr = *sata_addr;
10247 
10248 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, sata_addr->cport)));
10249 
10250 	sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
10251 
10252 	target = SATA_TO_SCSI_TARGET(sata_addr->cport,
10253 	    sata_addr->pmport, sata_addr->qual);
10254 
10255 	if (sdinfo == NULL) {
10256 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
10257 		    sata_addr->cport)));
10258 		SATA_LOG_D((sata_hba_inst, CE_WARN,
10259 		    "sata_create_target_node: no sdinfo for target %x",
10260 		    target));
10261 		return (NULL);
10262 	}
10263 
10264 	/*
10265 	 * create or get scsi inquiry data, expected by
10266 	 * scsi_hba_nodename_compatible_get()
10267 	 * SATA hard disks get Identify Data translated into Inguiry Data.
10268 	 * ATAPI devices respond directly to Inquiry request.
10269 	 */
10270 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
10271 		sata_identdev_to_inquiry(sata_hba_inst, sdinfo,
10272 		    (uint8_t *)&inq);
10273 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
10274 		    sata_addr->cport)));
10275 	} else { /* Assume supported ATAPI device */
10276 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
10277 		    sata_addr->cport)));
10278 		if (sata_get_atapi_inquiry_data(sata_hba_inst, sata_addr,
10279 		    &inq) == SATA_FAILURE)
10280 			return (NULL);
10281 		/*
10282 		 * Save supported ATAPI transport version
10283 		 */
10284 		sdinfo->satadrv_atapi_trans_ver =
10285 		    SATA_ATAPI_TRANS_VERSION(&inq);
10286 	}
10287 
10288 	/* determine the node name and compatible */
10289 	scsi_hba_nodename_compatible_get(&inq, NULL,
10290 	    inq.inq_dtype, NULL, &nname, &compatible, &ncompatible);
10291 
10292 #ifdef SATA_DEBUG
10293 	if (sata_debug_flags & SATA_DBG_NODES) {
10294 		if (nname == NULL) {
10295 			cmn_err(CE_NOTE, "sata_create_target_node: "
10296 			    "cannot determine nodename for target %d\n",
10297 			    target);
10298 		} else {
10299 			cmn_err(CE_WARN, "sata_create_target_node: "
10300 			    "target %d nodename: %s\n", target, nname);
10301 		}
10302 		if (compatible == NULL) {
10303 			cmn_err(CE_WARN,
10304 			    "sata_create_target_node: no compatible name\n");
10305 		} else {
10306 			for (i = 0; i < ncompatible; i++) {
10307 				cmn_err(CE_WARN, "sata_create_target_node: "
10308 				    "compatible name: %s\n", compatible[i]);
10309 			}
10310 		}
10311 	}
10312 #endif
10313 
10314 	/* if nodename can't be determined, log error and exit */
10315 	if (nname == NULL) {
10316 		SATA_LOG_D((sata_hba_inst, CE_WARN,
10317 		    "sata_create_target_node: cannot determine nodename "
10318 		    "for target %d\n", target));
10319 		scsi_hba_nodename_compatible_free(nname, compatible);
10320 		return (NULL);
10321 	}
10322 	/*
10323 	 * Create scsi target node
10324 	 */
10325 	ndi_devi_alloc_sleep(dip, nname, (pnode_t)DEVI_SID_NODEID, &cdip);
10326 	rval = ndi_prop_update_string(DDI_DEV_T_NONE, cdip,
10327 	    "device-type", "scsi");
10328 
10329 	if (rval != DDI_PROP_SUCCESS) {
10330 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
10331 		    "updating device_type prop failed %d", rval));
10332 		goto fail;
10333 	}
10334 
10335 	/*
10336 	 * Create target node properties: target & lun
10337 	 */
10338 	rval = ndi_prop_update_int(DDI_DEV_T_NONE, cdip, "target", target);
10339 	if (rval != DDI_PROP_SUCCESS) {
10340 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
10341 		    "updating target prop failed %d", rval));
10342 		goto fail;
10343 	}
10344 	rval = ndi_prop_update_int(DDI_DEV_T_NONE, cdip, "lun", 0);
10345 	if (rval != DDI_PROP_SUCCESS) {
10346 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
10347 		    "updating target prop failed %d", rval));
10348 		goto fail;
10349 	}
10350 
10351 	if (sdinfo->satadrv_type & SATA_DTYPE_ATAPI) {
10352 		/*
10353 		 * Add "variant" property
10354 		 */
10355 		rval = ndi_prop_update_string(DDI_DEV_T_NONE, cdip,
10356 		    "variant", "atapi");
10357 		if (rval != DDI_PROP_SUCCESS) {
10358 			SATA_LOG_D((sata_hba_inst, CE_WARN,
10359 			    "sata_create_target_node: variant atapi "
10360 			    "property could not be created: %d", rval));
10361 			goto fail;
10362 		}
10363 	}
10364 	/* decorate the node with compatible */
10365 	if (ndi_prop_update_string_array(DDI_DEV_T_NONE, cdip, "compatible",
10366 	    compatible, ncompatible) != DDI_PROP_SUCCESS) {
10367 		SATA_LOG_D((sata_hba_inst, CE_WARN,
10368 		    "sata_create_target_node: FAIL compatible props cdip 0x%p",
10369 		    (void *)cdip));
10370 		goto fail;
10371 	}
10372 
10373 
10374 	/*
10375 	 * Now, try to attach the driver. If probing of the device fails,
10376 	 * the target node may be removed
10377 	 */
10378 	rval = ndi_devi_online(cdip, NDI_ONLINE_ATTACH);
10379 
10380 	scsi_hba_nodename_compatible_free(nname, compatible);
10381 
10382 	if (rval == NDI_SUCCESS)
10383 		return (cdip);
10384 
10385 	/* target node was removed - are we sure? */
10386 	return (NULL);
10387 
10388 fail:
10389 	scsi_hba_nodename_compatible_free(nname, compatible);
10390 	ddi_prop_remove_all(cdip);
10391 	rval = ndi_devi_free(cdip);
10392 	if (rval != NDI_SUCCESS) {
10393 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
10394 		    "node removal failed %d", rval));
10395 	}
10396 	sata_log(sata_hba_inst, CE_WARN, "sata_create_target_node: "
10397 	    "cannot create target node for SATA device at port %d",
10398 	    sata_addr->cport);
10399 	return (NULL);
10400 }
10401 
10402 /*
10403  * Remove a target node.
10404  */
10405 static void
10406 sata_remove_target_node(sata_hba_inst_t *sata_hba_inst,
10407 			sata_address_t *sata_addr)
10408 {
10409 	dev_info_t *tdip;
10410 	uint8_t cport = sata_addr->cport;
10411 	uint8_t pmport = sata_addr->pmport;
10412 	uint8_t qual = sata_addr->qual;
10413 
10414 	/* Note the sata daemon uses the address of the port/pmport */
10415 	ASSERT(qual == SATA_ADDR_CPORT || qual == SATA_ADDR_PMPORT);
10416 
10417 	/* Remove target node */
10418 	tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst), cport, pmport);
10419 	if (tdip != NULL) {
10420 		/*
10421 		 * Target node exists.  Unconfigure device
10422 		 * then remove the target node (one ndi
10423 		 * operation).
10424 		 */
10425 		if (ndi_devi_offline(tdip, NDI_DEVI_REMOVE) != NDI_SUCCESS) {
10426 			/*
10427 			 * PROBLEM - no device, but target node remained. This
10428 			 * happens when the file was open or node was waiting
10429 			 * for resources.
10430 			 */
10431 			SATA_LOG_D((sata_hba_inst, CE_WARN,
10432 			    "sata_remove_target_node: "
10433 			    "Failed to remove target node for "
10434 			    "detached SATA device."));
10435 			/*
10436 			 * Set target node state to DEVI_DEVICE_REMOVED. But
10437 			 * re-check first that the node still exists.
10438 			 */
10439 			tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst),
10440 			    cport, pmport);
10441 			if (tdip != NULL) {
10442 				sata_set_device_removed(tdip);
10443 				/*
10444 				 * Instruct event daemon to retry the cleanup
10445 				 * later.
10446 				 */
10447 				sata_set_target_node_cleanup(sata_hba_inst,
10448 				    sata_addr);
10449 			}
10450 		}
10451 
10452 		if (qual == SATA_ADDR_CPORT)
10453 			sata_log(sata_hba_inst, CE_WARN,
10454 			    "SATA device detached at port %d", cport);
10455 		else
10456 			sata_log(sata_hba_inst, CE_WARN,
10457 			    "SATA device detached at port %d:%d",
10458 			    cport, pmport);
10459 	}
10460 #ifdef SATA_DEBUG
10461 	else {
10462 		if (qual == SATA_ADDR_CPORT)
10463 			sata_log(sata_hba_inst, CE_WARN,
10464 			    "target node not found at port %d", cport);
10465 		else
10466 			sata_log(sata_hba_inst, CE_WARN,
10467 			    "target node not found at port %d:%d",
10468 			    cport, pmport);
10469 	}
10470 #endif
10471 }
10472 
10473 
10474 /*
10475  * Re-probe sata port, check for a device and attach info
10476  * structures when necessary. Identify Device data is fetched, if possible.
10477  * Assumption: sata address is already validated.
10478  * SATA_SUCCESS is returned if port is re-probed sucessfully, regardless of
10479  * the presence of a device and its type.
10480  *
10481  * flag arg specifies that the function should try multiple times to identify
10482  * device type and to initialize it, or it should return immediately on failure.
10483  * SATA_DEV_IDENTIFY_RETRY - retry
10484  * SATA_DEV_IDENTIFY_NORETRY - no retry
10485  *
10486  * SATA_FAILURE is returned if one of the operations failed.
10487  *
10488  * This function cannot be called in interrupt context - it may sleep.
10489  *
10490  * Note: Port multiplier is supported.
10491  */
10492 static int
10493 sata_reprobe_port(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device,
10494     int flag)
10495 {
10496 	sata_cport_info_t *cportinfo;
10497 	sata_pmult_info_t *pmultinfo;
10498 	sata_drive_info_t *sdinfo, *osdinfo;
10499 	boolean_t init_device = B_FALSE;
10500 	int prev_device_type = SATA_DTYPE_NONE;
10501 	int prev_device_settings = 0;
10502 	int prev_device_state = 0;
10503 	clock_t start_time;
10504 	int retry = B_FALSE;
10505 	uint8_t cport = sata_device->satadev_addr.cport;
10506 	int rval_probe, rval_init;
10507 
10508 	/*
10509 	 * If target is pmport, sata_reprobe_pmport() will handle it.
10510 	 */
10511 	if (sata_device->satadev_addr.qual == SATA_ADDR_PMPORT ||
10512 	    sata_device->satadev_addr.qual == SATA_ADDR_DPMPORT)
10513 		return (sata_reprobe_pmport(sata_hba_inst, sata_device, flag));
10514 
10515 	/* We only care about host sata cport for now */
10516 	cportinfo = SATA_CPORT_INFO(sata_hba_inst,
10517 	    sata_device->satadev_addr.cport);
10518 
10519 	/*
10520 	 * If a port multiplier was previously attached (we have no idea it
10521 	 * still there or not), sata_reprobe_pmult() will handle it.
10522 	 */
10523 	if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT)
10524 		return (sata_reprobe_pmult(sata_hba_inst, sata_device, flag));
10525 
10526 	/* Store sata_drive_info when a non-pmult device was attached. */
10527 	osdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
10528 	if (osdinfo != NULL) {
10529 		/*
10530 		 * We are re-probing port with a previously attached device.
10531 		 * Save previous device type and settings.
10532 		 */
10533 		prev_device_type = cportinfo->cport_dev_type;
10534 		prev_device_settings = osdinfo->satadrv_settings;
10535 		prev_device_state = osdinfo->satadrv_state;
10536 	}
10537 	if (flag == SATA_DEV_IDENTIFY_RETRY) {
10538 		start_time = ddi_get_lbolt();
10539 		retry = B_TRUE;
10540 	}
10541 retry_probe:
10542 
10543 	/* probe port */
10544 	mutex_enter(&cportinfo->cport_mutex);
10545 	cportinfo->cport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
10546 	cportinfo->cport_state |= SATA_STATE_PROBING;
10547 	mutex_exit(&cportinfo->cport_mutex);
10548 
10549 	rval_probe = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
10550 	    (SATA_DIP(sata_hba_inst), sata_device);
10551 
10552 	mutex_enter(&cportinfo->cport_mutex);
10553 	if (rval_probe != SATA_SUCCESS) {
10554 		cportinfo->cport_state = SATA_PSTATE_FAILED;
10555 		mutex_exit(&cportinfo->cport_mutex);
10556 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_reprobe_port: "
10557 		    "SATA port %d probing failed",
10558 		    cportinfo->cport_addr.cport));
10559 		return (SATA_FAILURE);
10560 	}
10561 
10562 	/*
10563 	 * update sata port state and set device type
10564 	 */
10565 	sata_update_port_info(sata_hba_inst, sata_device);
10566 	cportinfo->cport_state &= ~SATA_STATE_PROBING;
10567 
10568 	/*
10569 	 * Sanity check - Port is active? Is the link active?
10570 	 * Is there any device attached?
10571 	 */
10572 	if ((cportinfo->cport_state &
10573 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
10574 	    (cportinfo->cport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
10575 	    SATA_PORT_DEVLINK_UP) {
10576 		/*
10577 		 * Port in non-usable state or no link active/no device.
10578 		 * Free info structure if necessary (direct attached drive
10579 		 * only, for now!
10580 		 */
10581 		sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
10582 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
10583 		/* Add here differentiation for device attached or not */
10584 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
10585 		mutex_exit(&cportinfo->cport_mutex);
10586 		if (sdinfo != NULL)
10587 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
10588 		return (SATA_SUCCESS);
10589 	}
10590 
10591 	cportinfo->cport_state |= SATA_STATE_READY;
10592 	cportinfo->cport_state |= SATA_STATE_PROBED;
10593 
10594 	cportinfo->cport_dev_type = sata_device->satadev_type;
10595 	sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
10596 
10597 	/*
10598 	 * If we are re-probing the port, there may be
10599 	 * sata_drive_info structure attached
10600 	 */
10601 	if (sata_device->satadev_type == SATA_DTYPE_NONE) {
10602 
10603 		/*
10604 		 * There is no device, so remove device info structure,
10605 		 * if necessary.
10606 		 */
10607 		/* Device change: Drive -> None */
10608 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
10609 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
10610 		if (sdinfo != NULL) {
10611 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
10612 			sata_log(sata_hba_inst, CE_WARN,
10613 			    "SATA device detached "
10614 			    "from port %d", cportinfo->cport_addr.cport);
10615 		}
10616 		mutex_exit(&cportinfo->cport_mutex);
10617 		return (SATA_SUCCESS);
10618 
10619 	}
10620 
10621 	if (sata_device->satadev_type != SATA_DTYPE_PMULT) {
10622 
10623 		/* Device (may) change: Drive -> Drive */
10624 		if (sdinfo == NULL) {
10625 			/*
10626 			 * There is some device attached, but there is
10627 			 * no sata_drive_info structure - allocate one
10628 			 */
10629 			mutex_exit(&cportinfo->cport_mutex);
10630 			sdinfo = kmem_zalloc(
10631 			    sizeof (sata_drive_info_t), KM_SLEEP);
10632 			mutex_enter(&cportinfo->cport_mutex);
10633 			/*
10634 			 * Recheck, that the port state did not change when we
10635 			 * released mutex.
10636 			 */
10637 			if (cportinfo->cport_state & SATA_STATE_READY) {
10638 				SATA_CPORTINFO_DRV_INFO(cportinfo) = sdinfo;
10639 				sdinfo->satadrv_addr = cportinfo->cport_addr;
10640 				sdinfo->satadrv_addr.qual = SATA_ADDR_DCPORT;
10641 				sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
10642 				sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
10643 			} else {
10644 				/*
10645 				 * Port is not in ready state, we
10646 				 * cannot attach a device.
10647 				 */
10648 				mutex_exit(&cportinfo->cport_mutex);
10649 				kmem_free(sdinfo, sizeof (sata_drive_info_t));
10650 				return (SATA_SUCCESS);
10651 			}
10652 			/*
10653 			 * Since we are adding device, presumably new one,
10654 			 * indicate that it  should be initalized,
10655 			 * as well as some internal framework states).
10656 			 */
10657 			init_device = B_TRUE;
10658 		}
10659 		cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
10660 		sata_device->satadev_addr.qual = sdinfo->satadrv_addr.qual;
10661 	} else {
10662 		/* Device change: Drive -> PMult */
10663 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
10664 		if (sdinfo != NULL) {
10665 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
10666 			sata_log(sata_hba_inst, CE_WARN,
10667 			    "SATA device detached "
10668 			    "from port %d", cportinfo->cport_addr.cport);
10669 		}
10670 
10671 		sata_log(sata_hba_inst, CE_WARN,
10672 		    "SATA port multiplier detected at port %d",
10673 		    cportinfo->cport_addr.cport);
10674 
10675 		mutex_exit(&cportinfo->cport_mutex);
10676 		if (sata_alloc_pmult(sata_hba_inst, sata_device) !=
10677 		    SATA_SUCCESS)
10678 			return (SATA_FAILURE);
10679 		sata_show_pmult_info(sata_hba_inst, sata_device);
10680 		mutex_enter(&cportinfo->cport_mutex);
10681 
10682 		/*
10683 		 * Mark all the port multiplier port behind the port
10684 		 * multiplier behind with link events, so that the sata daemon
10685 		 * will update their status.
10686 		 */
10687 		pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
10688 		pmultinfo->pmult_event_flags |= SATA_EVNT_DEVICE_RESET;
10689 		mutex_exit(&cportinfo->cport_mutex);
10690 		return (SATA_SUCCESS);
10691 	}
10692 	mutex_exit(&cportinfo->cport_mutex);
10693 
10694 	/*
10695 	 * Figure out what kind of device we are really
10696 	 * dealing with. Failure of identifying device does not fail this
10697 	 * function.
10698 	 */
10699 	rval_probe = sata_probe_device(sata_hba_inst, sata_device);
10700 	rval_init = SATA_FAILURE;
10701 	mutex_enter(&cportinfo->cport_mutex);
10702 	if (rval_probe == SATA_SUCCESS) {
10703 		/*
10704 		 * If we are dealing with the same type of a device as before,
10705 		 * restore its settings flags.
10706 		 */
10707 		if (osdinfo != NULL &&
10708 		    sata_device->satadev_type == prev_device_type)
10709 			sdinfo->satadrv_settings = prev_device_settings;
10710 
10711 		mutex_exit(&cportinfo->cport_mutex);
10712 		rval_init = SATA_SUCCESS;
10713 		/* Set initial device features, if necessary */
10714 		if (init_device == B_TRUE) {
10715 			rval_init = sata_initialize_device(sata_hba_inst,
10716 			    sdinfo);
10717 		}
10718 		if (rval_init == SATA_SUCCESS)
10719 			return (rval_init);
10720 		/* else we will retry if retry was asked for */
10721 
10722 	} else {
10723 		/*
10724 		 * If there was some device info before we probe the device,
10725 		 * restore previous device setting, so we can retry from scratch
10726 		 * later. Providing, of course, that device has not disapear
10727 		 * during probing process.
10728 		 */
10729 		if (sata_device->satadev_type != SATA_DTYPE_NONE) {
10730 			if (osdinfo != NULL) {
10731 				cportinfo->cport_dev_type = prev_device_type;
10732 				sdinfo->satadrv_type = prev_device_type;
10733 				sdinfo->satadrv_state = prev_device_state;
10734 			}
10735 		} else {
10736 			/* device is gone */
10737 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
10738 			cportinfo->cport_dev_type = SATA_DTYPE_NONE;
10739 			SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
10740 			mutex_exit(&cportinfo->cport_mutex);
10741 			return (SATA_SUCCESS);
10742 		}
10743 		mutex_exit(&cportinfo->cport_mutex);
10744 	}
10745 
10746 	if (retry) {
10747 		clock_t cur_time = ddi_get_lbolt();
10748 		/*
10749 		 * A device was not successfully identified or initialized.
10750 		 * Track retry time for device identification.
10751 		 */
10752 		if ((cur_time - start_time) <
10753 		    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
10754 			/* sleep for a while */
10755 			delay(drv_usectohz(SATA_DEV_RETRY_DLY));
10756 			goto retry_probe;
10757 		}
10758 		/* else no more retries */
10759 		mutex_enter(&cportinfo->cport_mutex);
10760 		if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
10761 			if (rval_init == SATA_RETRY) {
10762 				/*
10763 				 * Setting drive features have failed, but
10764 				 * because the drive is still accessible,
10765 				 * keep it and emit a warning message.
10766 				 */
10767 				sata_log(sata_hba_inst, CE_WARN,
10768 				    "SATA device at port %d - desired "
10769 				    "drive features could not be set. "
10770 				    "Device may not operate as expected.",
10771 				    cportinfo->cport_addr.cport);
10772 			} else {
10773 				SATA_CPORTINFO_DRV_INFO(cportinfo)->
10774 				    satadrv_state = SATA_DSTATE_FAILED;
10775 			}
10776 		}
10777 		mutex_exit(&cportinfo->cport_mutex);
10778 	}
10779 	return (SATA_SUCCESS);
10780 }
10781 
10782 /*
10783  * Reprobe a controller port that connected to a port multiplier.
10784  *
10785  * NOTE: No Mutex should be hold.
10786  */
10787 static int
10788 sata_reprobe_pmult(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device,
10789     int flag)
10790 {
10791 	_NOTE(ARGUNUSED(flag))
10792 	sata_cport_info_t *cportinfo;
10793 	sata_pmult_info_t *pmultinfo;
10794 	uint8_t cport = sata_device->satadev_addr.cport;
10795 	int rval_probe;
10796 
10797 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
10798 	pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
10799 
10800 	/* probe port */
10801 	mutex_enter(&cportinfo->cport_mutex);
10802 	cportinfo->cport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
10803 	cportinfo->cport_state |= SATA_STATE_PROBING;
10804 	mutex_exit(&cportinfo->cport_mutex);
10805 
10806 	rval_probe = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
10807 	    (SATA_DIP(sata_hba_inst), sata_device);
10808 
10809 	mutex_enter(&cportinfo->cport_mutex);
10810 	if (rval_probe != SATA_SUCCESS) {
10811 		cportinfo->cport_state = SATA_PSTATE_FAILED;
10812 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_reprobe_pmult: "
10813 		    "SATA port %d probing failed", cport));
10814 		sata_log(sata_hba_inst, CE_WARN,
10815 		    "SATA port multiplier detached at port %d", cport);
10816 		mutex_exit(&cportinfo->cport_mutex);
10817 		sata_free_pmult(sata_hba_inst, sata_device);
10818 		return (SATA_FAILURE);
10819 	}
10820 
10821 	/*
10822 	 * update sata port state and set device type
10823 	 */
10824 	sata_update_port_info(sata_hba_inst, sata_device);
10825 	cportinfo->cport_state &= ~SATA_STATE_PROBING;
10826 	cportinfo->cport_state |= SATA_STATE_PROBED;
10827 
10828 	/*
10829 	 * Sanity check - Port is active? Is the link active?
10830 	 * Is there any device attached?
10831 	 */
10832 	if ((cportinfo->cport_state &
10833 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
10834 	    (cportinfo->cport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
10835 	    SATA_PORT_DEVLINK_UP ||
10836 	    (sata_device->satadev_type == SATA_DTYPE_NONE)) {
10837 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
10838 		mutex_exit(&cportinfo->cport_mutex);
10839 		sata_free_pmult(sata_hba_inst, sata_device);
10840 		sata_log(sata_hba_inst, CE_WARN,
10841 		    "SATA port multiplier detached at port %d", cport);
10842 		return (SATA_SUCCESS);
10843 	}
10844 
10845 	/*
10846 	 * Device changed: PMult -> Non-PMult
10847 	 *
10848 	 * This situation is uncommon, most possibly being caused by errors
10849 	 * after which the port multiplier is not correct initialized and
10850 	 * recognized. In that case the new device will be marked as unknown
10851 	 * and will not be automatically probed in this routine. Instead
10852 	 * system administrator could manually restart it via cfgadm(1M).
10853 	 */
10854 	if (sata_device->satadev_type != SATA_DTYPE_PMULT) {
10855 		cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
10856 		mutex_exit(&cportinfo->cport_mutex);
10857 		sata_free_pmult(sata_hba_inst, sata_device);
10858 		sata_log(sata_hba_inst, CE_WARN,
10859 		    "SATA port multiplier detached at port %d", cport);
10860 		return (SATA_FAILURE);
10861 	}
10862 
10863 	/*
10864 	 * Now we know it is a port multiplier. However, if this is not the
10865 	 * previously attached port multiplier - they may have different
10866 	 * pmport numbers - we need to re-allocate data structures for every
10867 	 * pmport and drive.
10868 	 *
10869 	 * Port multipliers of the same model have identical values in these
10870 	 * registers, so it is still necessary to update the information of
10871 	 * all drives attached to the previous port multiplier afterwards.
10872 	 */
10873 	/* Device changed: PMult -> another PMult */
10874 	mutex_exit(&cportinfo->cport_mutex);
10875 	sata_free_pmult(sata_hba_inst, sata_device);
10876 	if (sata_alloc_pmult(sata_hba_inst, sata_device) != SATA_SUCCESS)
10877 		return (SATA_FAILURE);
10878 	mutex_enter(&cportinfo->cport_mutex);
10879 
10880 	SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
10881 	    "SATA port multiplier [changed] at port %d", cport);
10882 	sata_log(sata_hba_inst, CE_WARN,
10883 	    "SATA port multiplier detected at port %d", cport);
10884 
10885 	/*
10886 	 * Mark all the port multiplier port behind the port
10887 	 * multiplier behind with link events, so that the sata daemon
10888 	 * will update their status.
10889 	 */
10890 	pmultinfo->pmult_event_flags |= SATA_EVNT_DEVICE_RESET;
10891 	mutex_exit(&cportinfo->cport_mutex);
10892 
10893 	return (SATA_SUCCESS);
10894 }
10895 
10896 /*
10897  * Re-probe a port multiplier port, check for a device and attach info
10898  * structures when necessary. Identify Device data is fetched, if possible.
10899  * Assumption: sata address is already validated as port multiplier port.
10900  * SATA_SUCCESS is returned if port is re-probed sucessfully, regardless of
10901  * the presence of a device and its type.
10902  *
10903  * flag arg specifies that the function should try multiple times to identify
10904  * device type and to initialize it, or it should return immediately on failure.
10905  * SATA_DEV_IDENTIFY_RETRY - retry
10906  * SATA_DEV_IDENTIFY_NORETRY - no retry
10907  *
10908  * SATA_FAILURE is returned if one of the operations failed.
10909  *
10910  * This function cannot be called in interrupt context - it may sleep.
10911  *
10912  * NOTE: Should be only called by sata_probe_port() in case target port is a
10913  *       port multiplier port.
10914  * NOTE: No Mutex should be hold.
10915  */
10916 static int
10917 sata_reprobe_pmport(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device,
10918     int flag)
10919 {
10920 	sata_cport_info_t *cportinfo = NULL;
10921 	sata_pmport_info_t *pmportinfo = NULL;
10922 	sata_drive_info_t *sdinfo, *osdinfo;
10923 	sata_device_t sdevice;
10924 	boolean_t init_device = B_FALSE;
10925 	int prev_device_type = SATA_DTYPE_NONE;
10926 	int prev_device_settings = 0;
10927 	int prev_device_state = 0;
10928 	clock_t start_time;
10929 	uint8_t cport = sata_device->satadev_addr.cport;
10930 	uint8_t pmport = sata_device->satadev_addr.pmport;
10931 	int rval;
10932 
10933 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
10934 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
10935 	osdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
10936 
10937 	if (osdinfo != NULL) {
10938 		/*
10939 		 * We are re-probing port with a previously attached device.
10940 		 * Save previous device type and settings.
10941 		 */
10942 		prev_device_type = pmportinfo->pmport_dev_type;
10943 		prev_device_settings = osdinfo->satadrv_settings;
10944 		prev_device_state = osdinfo->satadrv_state;
10945 	}
10946 
10947 	start_time = ddi_get_lbolt();
10948 
10949 	/* check parent status */
10950 	mutex_enter(&cportinfo->cport_mutex);
10951 	if ((cportinfo->cport_state &
10952 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
10953 	    (cportinfo->cport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
10954 	    SATA_PORT_DEVLINK_UP) {
10955 		mutex_exit(&cportinfo->cport_mutex);
10956 		return (SATA_FAILURE);
10957 	}
10958 	mutex_exit(&cportinfo->cport_mutex);
10959 
10960 retry_probe_pmport:
10961 
10962 	/* probe port */
10963 	mutex_enter(&pmportinfo->pmport_mutex);
10964 	pmportinfo->pmport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
10965 	pmportinfo->pmport_state |= SATA_STATE_PROBING;
10966 	mutex_exit(&pmportinfo->pmport_mutex);
10967 
10968 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
10969 	    (SATA_DIP(sata_hba_inst), sata_device);
10970 
10971 	/* might need retry because we cannot touch registers. */
10972 	if (rval == SATA_FAILURE) {
10973 		mutex_enter(&pmportinfo->pmport_mutex);
10974 		pmportinfo->pmport_state = SATA_PSTATE_FAILED;
10975 		mutex_exit(&pmportinfo->pmport_mutex);
10976 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_reprobe_pmport: "
10977 		    "SATA port %d:%d probing failed",
10978 		    cport, pmport));
10979 		return (SATA_FAILURE);
10980 	} else if (rval == SATA_RETRY) {
10981 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_reprobe_pmport: "
10982 		    "SATA port %d:%d probing failed, retrying...",
10983 		    cport, pmport));
10984 		clock_t cur_time = ddi_get_lbolt();
10985 		/*
10986 		 * A device was not successfully identified or initialized.
10987 		 * Track retry time for device identification.
10988 		 */
10989 		if ((cur_time - start_time) <
10990 		    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
10991 			/* sleep for a while */
10992 			delay(drv_usectohz(SATA_DEV_RETRY_DLY));
10993 			goto retry_probe_pmport;
10994 		} else {
10995 			mutex_enter(&pmportinfo->pmport_mutex);
10996 			if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL)
10997 				SATA_PMPORTINFO_DRV_INFO(pmportinfo)->
10998 				    satadrv_state = SATA_DSTATE_FAILED;
10999 			mutex_exit(&pmportinfo->pmport_mutex);
11000 			return (SATA_SUCCESS);
11001 		}
11002 	}
11003 
11004 	/*
11005 	 * Sanity check - Controller port is active? Is the link active?
11006 	 * Is it still a port multiplier?
11007 	 */
11008 	if ((cportinfo->cport_state &
11009 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
11010 	    (cportinfo->cport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
11011 	    SATA_PORT_DEVLINK_UP ||
11012 	    (cportinfo->cport_dev_type != SATA_DTYPE_PMULT)) {
11013 		/*
11014 		 * Port in non-usable state or no link active/no
11015 		 * device. Free info structure.
11016 		 */
11017 		cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
11018 
11019 		sdevice.satadev_addr.cport = cport;
11020 		sdevice.satadev_addr.pmport = pmport;
11021 		sdevice.satadev_addr.qual = SATA_ADDR_PMULT;
11022 		mutex_exit(&cportinfo->cport_mutex);
11023 
11024 		sata_free_pmult(sata_hba_inst, &sdevice);
11025 		return (SATA_FAILURE);
11026 	}
11027 
11028 	/* SATA_SUCCESS NOW */
11029 	/*
11030 	 * update sata port state and set device type
11031 	 */
11032 	mutex_enter(&pmportinfo->pmport_mutex);
11033 	sata_update_pmport_info(sata_hba_inst, sata_device);
11034 	pmportinfo->pmport_state &= ~SATA_STATE_PROBING;
11035 
11036 	/*
11037 	 * Sanity check - Port is active? Is the link active?
11038 	 * Is there any device attached?
11039 	 */
11040 	if ((pmportinfo->pmport_state &
11041 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
11042 	    (pmportinfo->pmport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
11043 	    SATA_PORT_DEVLINK_UP) {
11044 		/*
11045 		 * Port in non-usable state or no link active/no device.
11046 		 * Free info structure if necessary (direct attached drive
11047 		 * only, for now!
11048 		 */
11049 		sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
11050 		SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
11051 		/* Add here differentiation for device attached or not */
11052 		pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
11053 		mutex_exit(&pmportinfo->pmport_mutex);
11054 		if (sdinfo != NULL)
11055 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
11056 		return (SATA_SUCCESS);
11057 	}
11058 
11059 	pmportinfo->pmport_state |= SATA_STATE_READY;
11060 	pmportinfo->pmport_dev_type = sata_device->satadev_type;
11061 	sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
11062 
11063 	/*
11064 	 * If we are re-probing the port, there may be
11065 	 * sata_drive_info structure attached
11066 	 * (or sata_pm_info, if PMult is supported).
11067 	 */
11068 	if (sata_device->satadev_type == SATA_DTYPE_NONE) {
11069 		/*
11070 		 * There is no device, so remove device info structure,
11071 		 * if necessary.
11072 		 */
11073 		SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
11074 		pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
11075 		if (sdinfo != NULL) {
11076 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
11077 			sata_log(sata_hba_inst, CE_WARN,
11078 			    "SATA device detached from port %d:%d",
11079 			    cport, pmport);
11080 		}
11081 		mutex_exit(&pmportinfo->pmport_mutex);
11082 		return (SATA_SUCCESS);
11083 	}
11084 
11085 	/* this should not be a pmult */
11086 	ASSERT(sata_device->satadev_type != SATA_DTYPE_PMULT);
11087 	if (sdinfo == NULL) {
11088 		/*
11089 		 * There is some device attached, but there is
11090 		 * no sata_drive_info structure - allocate one
11091 		 */
11092 		mutex_exit(&pmportinfo->pmport_mutex);
11093 		sdinfo = kmem_zalloc(sizeof (sata_drive_info_t),
11094 		    KM_SLEEP);
11095 		mutex_enter(&pmportinfo->pmport_mutex);
11096 		/*
11097 		 * Recheck, that the port state did not change when we
11098 		 * released mutex.
11099 		 */
11100 		if (pmportinfo->pmport_state & SATA_STATE_READY) {
11101 			SATA_PMPORTINFO_DRV_INFO(pmportinfo) = sdinfo;
11102 			sdinfo->satadrv_addr = pmportinfo->pmport_addr;
11103 			sdinfo->satadrv_addr.qual = SATA_ADDR_DPMPORT;
11104 			sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
11105 			sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
11106 		} else {
11107 			/*
11108 			 * Port is not in ready state, we
11109 			 * cannot attach a device.
11110 			 */
11111 			mutex_exit(&pmportinfo->pmport_mutex);
11112 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
11113 			return (SATA_SUCCESS);
11114 		}
11115 		/*
11116 		 * Since we are adding device, presumably new one,
11117 		 * indicate that it  should be initalized,
11118 		 * as well as some internal framework states).
11119 		 */
11120 		init_device = B_TRUE;
11121 	}
11122 
11123 	pmportinfo->pmport_dev_type = SATA_DTYPE_UNKNOWN;
11124 	sata_device->satadev_addr.qual = sdinfo->satadrv_addr.qual;
11125 
11126 	mutex_exit(&pmportinfo->pmport_mutex);
11127 	/*
11128 	 * Figure out what kind of device we are really
11129 	 * dealing with.
11130 	 */
11131 	rval = sata_probe_device(sata_hba_inst, sata_device);
11132 
11133 	mutex_enter(&pmportinfo->pmport_mutex);
11134 	if (rval == SATA_SUCCESS) {
11135 		/*
11136 		 * If we are dealing with the same type of a device as before,
11137 		 * restore its settings flags.
11138 		 */
11139 		if (osdinfo != NULL &&
11140 		    sata_device->satadev_type == prev_device_type)
11141 			sdinfo->satadrv_settings = prev_device_settings;
11142 
11143 		mutex_exit(&pmportinfo->pmport_mutex);
11144 		/* Set initial device features, if necessary */
11145 		if (init_device == B_TRUE) {
11146 			rval = sata_initialize_device(sata_hba_inst, sdinfo);
11147 		}
11148 		if (rval == SATA_SUCCESS)
11149 			return (rval);
11150 	} else {
11151 		/*
11152 		 * If there was some device info before we probe the device,
11153 		 * restore previous device setting, so we can retry from scratch
11154 		 * later. Providing, of course, that device has not disappeared
11155 		 * during probing process.
11156 		 */
11157 		if (sata_device->satadev_type != SATA_DTYPE_NONE) {
11158 			if (osdinfo != NULL) {
11159 				pmportinfo->pmport_dev_type = prev_device_type;
11160 				sdinfo->satadrv_type = prev_device_type;
11161 				sdinfo->satadrv_state = prev_device_state;
11162 			}
11163 		} else {
11164 			/* device is gone */
11165 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
11166 			pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
11167 			SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
11168 			mutex_exit(&pmportinfo->pmport_mutex);
11169 			return (SATA_SUCCESS);
11170 		}
11171 		mutex_exit(&pmportinfo->pmport_mutex);
11172 	}
11173 
11174 	if (flag == SATA_DEV_IDENTIFY_RETRY) {
11175 		clock_t cur_time = ddi_get_lbolt();
11176 		/*
11177 		 * A device was not successfully identified or initialized.
11178 		 * Track retry time for device identification.
11179 		 */
11180 		if ((cur_time - start_time) <
11181 		    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
11182 			/* sleep for a while */
11183 			delay(drv_usectohz(SATA_DEV_RETRY_DLY));
11184 			goto retry_probe_pmport;
11185 		} else {
11186 			mutex_enter(&pmportinfo->pmport_mutex);
11187 			if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL)
11188 				SATA_PMPORTINFO_DRV_INFO(pmportinfo)->
11189 				    satadrv_state = SATA_DSTATE_FAILED;
11190 			mutex_exit(&pmportinfo->pmport_mutex);
11191 		}
11192 	}
11193 	return (SATA_SUCCESS);
11194 }
11195 
11196 /*
11197  * Allocated related structure for a port multiplier and its device ports
11198  *
11199  * Port multiplier should be ready and probed, and related information like
11200  * the number of the device ports should be store in sata_device_t.
11201  *
11202  * NOTE: No Mutex should be hold.
11203  */
11204 static int
11205 sata_alloc_pmult(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device)
11206 {
11207 	dev_info_t *dip = SATA_DIP(sata_hba_inst);
11208 	sata_cport_info_t *cportinfo = NULL;
11209 	sata_pmult_info_t *pmultinfo = NULL;
11210 	sata_pmport_info_t *pmportinfo = NULL;
11211 	sata_device_t sd;
11212 	dev_t minor_number;
11213 	char name[16];
11214 	uint8_t cport = sata_device->satadev_addr.cport;
11215 	int rval;
11216 	int npmport;
11217 
11218 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
11219 
11220 	/* This function might be called while a port-mult is hot-plugged. */
11221 	mutex_enter(&cportinfo->cport_mutex);
11222 
11223 	/* dev_type's not updated when get called from sata_reprobe_port() */
11224 	if (SATA_CPORTINFO_PMULT_INFO(cportinfo) == NULL) {
11225 		/* Create a pmult_info structure */
11226 		SATA_CPORTINFO_PMULT_INFO(cportinfo) =
11227 		    kmem_zalloc(sizeof (sata_pmult_info_t), KM_SLEEP);
11228 	}
11229 	pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
11230 
11231 	pmultinfo->pmult_addr = sata_device->satadev_addr;
11232 	pmultinfo->pmult_addr.qual = SATA_ADDR_PMULT;
11233 	pmultinfo->pmult_state = SATA_STATE_PROBING;
11234 
11235 	/*
11236 	 * Probe the port multiplier with qualifier SATA_ADDR_PMULT_SPEC,
11237 	 * The HBA driver should initialize and register the port multiplier,
11238 	 * sata_register_pmult() will fill following fields,
11239 	 *   + sata_pmult_info.pmult_gscr
11240 	 *   + sata_pmult_info.pmult_num_dev_ports
11241 	 */
11242 	sd.satadev_addr = sata_device->satadev_addr;
11243 	sd.satadev_addr.qual = SATA_ADDR_PMULT_SPEC;
11244 	mutex_exit(&cportinfo->cport_mutex);
11245 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
11246 	    (SATA_DIP(sata_hba_inst), &sd);
11247 	mutex_enter(&cportinfo->cport_mutex);
11248 
11249 	if (rval != SATA_SUCCESS ||
11250 	    (sd.satadev_type != SATA_DTYPE_PMULT) ||
11251 	    !(sd.satadev_state & SATA_DSTATE_PMULT_INIT)) {
11252 		SATA_CPORTINFO_PMULT_INFO(cportinfo) = NULL;
11253 		kmem_free(pmultinfo, sizeof (sata_pmult_info_t));
11254 		cportinfo->cport_state = SATA_PSTATE_FAILED;
11255 		cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
11256 		mutex_exit(&cportinfo->cport_mutex);
11257 		SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
11258 		    "sata_alloc_pmult: failed to initialize pmult "
11259 		    "at port %d.", cport)
11260 		return (SATA_FAILURE);
11261 	}
11262 
11263 	/* Initialize pmport_info structure */
11264 	for (npmport = 0; npmport < pmultinfo->pmult_num_dev_ports;
11265 	    npmport++) {
11266 
11267 		/* if everything is allocated, skip */
11268 		if (SATA_PMPORT_INFO(sata_hba_inst, cport, npmport) != NULL)
11269 			continue;
11270 
11271 		pmportinfo = kmem_zalloc(sizeof (sata_pmport_info_t), KM_SLEEP);
11272 		mutex_init(&pmportinfo->pmport_mutex, NULL, MUTEX_DRIVER, NULL);
11273 		mutex_exit(&cportinfo->cport_mutex);
11274 
11275 		mutex_enter(&pmportinfo->pmport_mutex);
11276 		pmportinfo->pmport_addr.cport = cport;
11277 		pmportinfo->pmport_addr.pmport = (uint8_t)npmport;
11278 		pmportinfo->pmport_addr.qual = SATA_ADDR_PMPORT;
11279 		pmportinfo->pmport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
11280 		mutex_exit(&pmportinfo->pmport_mutex);
11281 
11282 		mutex_enter(&cportinfo->cport_mutex);
11283 		SATA_PMPORT_INFO(sata_hba_inst, cport, npmport) = pmportinfo;
11284 
11285 		/* Create an attachment point */
11286 		minor_number = SATA_MAKE_AP_MINOR(ddi_get_instance(dip),
11287 		    cport, (uint8_t)npmport, SATA_ADDR_PMPORT);
11288 		(void) sprintf(name, "%d.%d", cport, npmport);
11289 
11290 		if (ddi_create_minor_node(dip, name, S_IFCHR, minor_number,
11291 		    DDI_NT_SATA_ATTACHMENT_POINT, 0) != DDI_SUCCESS) {
11292 			sata_log(sata_hba_inst, CE_WARN, "sata_hba_attach: "
11293 			    "cannot create SATA attachment point for "
11294 			    "port %d:%d", cport, npmport);
11295 		}
11296 	}
11297 
11298 	pmultinfo->pmult_state &= ~SATA_STATE_PROBING;
11299 	pmultinfo->pmult_state |= (SATA_STATE_PROBED|SATA_STATE_READY);
11300 	cportinfo->cport_dev_type = SATA_DTYPE_PMULT;
11301 
11302 	mutex_exit(&cportinfo->cport_mutex);
11303 	return (SATA_SUCCESS);
11304 }
11305 
11306 /*
11307  * Free data structures when a port multiplier is removed.
11308  *
11309  * NOTE: No Mutex should be hold.
11310  */
11311 static void
11312 sata_free_pmult(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device)
11313 {
11314 	sata_cport_info_t *cportinfo;
11315 	sata_pmult_info_t *pmultinfo;
11316 	sata_pmport_info_t *pmportinfo;
11317 	sata_device_t pmport_device;
11318 	sata_drive_info_t *sdinfo;
11319 	dev_info_t *tdip;
11320 	char name[16];
11321 	uint8_t cport = sata_device->satadev_addr.cport;
11322 	int npmport;
11323 
11324 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
11325 
11326 	/* This function might be called while port-mult is hot plugged. */
11327 	mutex_enter(&cportinfo->cport_mutex);
11328 
11329 	cportinfo->cport_dev_type = SATA_DTYPE_NONE;
11330 	pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
11331 	ASSERT(pmultinfo != NULL);
11332 
11333 	/* Free pmport_info structure */
11334 	for (npmport = 0; npmport < pmultinfo->pmult_num_dev_ports;
11335 	    npmport++) {
11336 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, npmport);
11337 		if (pmportinfo == NULL)
11338 			continue;
11339 		mutex_exit(&cportinfo->cport_mutex);
11340 
11341 		mutex_enter(&pmportinfo->pmport_mutex);
11342 		sdinfo = pmportinfo->pmport_sata_drive;
11343 		SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
11344 		mutex_exit(&pmportinfo->pmport_mutex);
11345 
11346 		/* Remove attachment point. */
11347 		name[0] = '\0';
11348 		(void) sprintf(name, "%d.%d", cport, npmport);
11349 		ddi_remove_minor_node(SATA_DIP(sata_hba_inst), name);
11350 		sata_log(sata_hba_inst, CE_NOTE,
11351 		    "Remove attachment point of port %d:%d",
11352 		    cport, npmport);
11353 
11354 		/*
11355 		 * Rumove target node
11356 		 */
11357 		bzero(&pmport_device, sizeof (sata_device_t));
11358 		pmport_device.satadev_rev = SATA_DEVICE_REV;
11359 		pmport_device.satadev_addr.cport = cport;
11360 		pmport_device.satadev_addr.pmport = (uint8_t)npmport;
11361 		pmport_device.satadev_addr.qual = SATA_ADDR_DPMPORT;
11362 
11363 		tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
11364 		    &(pmport_device.satadev_addr));
11365 		if (tdip != NULL && ndi_devi_offline(tdip,
11366 		    NDI_DEVI_REMOVE) != NDI_SUCCESS) {
11367 			/*
11368 			 * Problem :
11369 			 * The target node remained attached.
11370 			 * This happens when the device file was open
11371 			 * or a node was waiting for resources.
11372 			 * Cannot do anything about it.
11373 			 */
11374 			SATA_LOG_D((sata_hba_inst, CE_WARN,
11375 			    "sata_free_pmult: could not unconfigure device "
11376 			    "before disconnecting the SATA port %d:%d",
11377 			    cport, npmport));
11378 
11379 			/*
11380 			 * Set DEVICE REMOVED state in the target
11381 			 * node. It will prevent access to the device
11382 			 * even when a new device is attached, until
11383 			 * the old target node is released, removed and
11384 			 * recreated for a new  device.
11385 			 */
11386 			sata_set_device_removed(tdip);
11387 
11388 			/*
11389 			 * Instruct event daemon to try the target
11390 			 * node cleanup later.
11391 			 */
11392 			sata_set_target_node_cleanup(
11393 			    sata_hba_inst, &(pmport_device.satadev_addr));
11394 
11395 		}
11396 		mutex_enter(&cportinfo->cport_mutex);
11397 
11398 		/*
11399 		 * Add here differentiation for device attached or not
11400 		 */
11401 		if (sdinfo != NULL)  {
11402 			sata_log(sata_hba_inst, CE_WARN,
11403 			    "SATA device detached from port %d:%d",
11404 			    cport, npmport);
11405 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
11406 		}
11407 
11408 		mutex_destroy(&pmportinfo->pmport_mutex);
11409 		kmem_free(pmportinfo, sizeof (sata_pmport_info_t));
11410 	}
11411 
11412 	kmem_free(pmultinfo, sizeof (sata_pmult_info_t));
11413 
11414 	cportinfo->cport_devp.cport_sata_pmult = NULL;
11415 
11416 	sata_log(sata_hba_inst, CE_WARN,
11417 	    "SATA port multiplier detached at port %d", cport);
11418 
11419 	mutex_exit(&cportinfo->cport_mutex);
11420 }
11421 
11422 /*
11423  * Initialize device
11424  * Specified device is initialized to a default state.
11425  *
11426  * Returns SATA_SUCCESS if all device features are set successfully,
11427  * SATA_RETRY if device is accessible but device features were not set
11428  * successfully, and SATA_FAILURE otherwise.
11429  */
11430 static int
11431 sata_initialize_device(sata_hba_inst_t *sata_hba_inst,
11432     sata_drive_info_t *sdinfo)
11433 {
11434 	int rval;
11435 
11436 	sata_save_drive_settings(sdinfo);
11437 
11438 	sdinfo->satadrv_settings |= SATA_DEV_READ_AHEAD;
11439 
11440 	sata_init_write_cache_mode(sdinfo);
11441 
11442 	rval = sata_set_drive_features(sata_hba_inst, sdinfo, 0);
11443 
11444 	/* Determine current data transfer mode */
11445 	if ((sdinfo->satadrv_id.ai_cap & SATA_DMA_SUPPORT) == 0) {
11446 		sdinfo->satadrv_settings &= ~SATA_DEV_DMA;
11447 	} else if ((sdinfo->satadrv_id.ai_validinfo &
11448 	    SATA_VALIDINFO_88) != 0 &&
11449 	    (sdinfo->satadrv_id.ai_ultradma & SATA_UDMA_SEL_MASK) != 0) {
11450 		sdinfo->satadrv_settings |= SATA_DEV_DMA;
11451 	} else if ((sdinfo->satadrv_id.ai_dworddma &
11452 	    SATA_MDMA_SEL_MASK) != 0) {
11453 		sdinfo->satadrv_settings |= SATA_DEV_DMA;
11454 	} else
11455 		/* DMA supported, not no DMA transfer mode is selected !? */
11456 		sdinfo->satadrv_settings &= ~SATA_DEV_DMA;
11457 
11458 	if ((sdinfo->satadrv_id.ai_cmdset83 & 0x20) &&
11459 	    (sdinfo->satadrv_id.ai_features86 & 0x20))
11460 		sdinfo->satadrv_power_level = SATA_POWER_STANDBY;
11461 	else
11462 		sdinfo->satadrv_power_level = SATA_POWER_ACTIVE;
11463 
11464 	return (rval);
11465 }
11466 
11467 
11468 /*
11469  * Initialize write cache mode.
11470  *
11471  * The default write cache setting for SATA HDD is provided by sata_write_cache
11472  * static variable. ATAPI CD/DVDs devices have write cache default is
11473  * determined by sata_atapicdvd_write_cache static variable.
11474  * ATAPI tape devices have write cache default is determined by
11475  * sata_atapitape_write_cache static variable.
11476  * ATAPI disk devices have write cache default is determined by
11477  * sata_atapidisk_write_cache static variable.
11478  * 1 - enable
11479  * 0 - disable
11480  * any other value - current drive setting
11481  *
11482  * Although there is not reason to disable write cache on CD/DVD devices,
11483  * tape devices and ATAPI disk devices, the default setting control is provided
11484  * for the maximun flexibility.
11485  *
11486  * In the future, it may be overridden by the
11487  * disk-write-cache-enable property setting, if it is defined.
11488  * Returns SATA_SUCCESS if all device features are set successfully,
11489  * SATA_FAILURE otherwise.
11490  */
11491 static void
11492 sata_init_write_cache_mode(sata_drive_info_t *sdinfo)
11493 {
11494 	switch (sdinfo->satadrv_type) {
11495 	case SATA_DTYPE_ATADISK:
11496 		if (sata_write_cache == 1)
11497 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
11498 		else if (sata_write_cache == 0)
11499 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
11500 		/*
11501 		 * When sata_write_cache value is not 0 or 1,
11502 		 * a current setting of the drive's write cache is used.
11503 		 */
11504 		break;
11505 	case SATA_DTYPE_ATAPICD:
11506 		if (sata_atapicdvd_write_cache == 1)
11507 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
11508 		else if (sata_atapicdvd_write_cache == 0)
11509 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
11510 		/*
11511 		 * When sata_atapicdvd_write_cache value is not 0 or 1,
11512 		 * a current setting of the drive's write cache is used.
11513 		 */
11514 		break;
11515 	case SATA_DTYPE_ATAPITAPE:
11516 		if (sata_atapitape_write_cache == 1)
11517 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
11518 		else if (sata_atapitape_write_cache == 0)
11519 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
11520 		/*
11521 		 * When sata_atapitape_write_cache value is not 0 or 1,
11522 		 * a current setting of the drive's write cache is used.
11523 		 */
11524 		break;
11525 	case SATA_DTYPE_ATAPIDISK:
11526 		if (sata_atapidisk_write_cache == 1)
11527 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
11528 		else if (sata_atapidisk_write_cache == 0)
11529 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
11530 		/*
11531 		 * When sata_atapidisk_write_cache value is not 0 or 1,
11532 		 * a current setting of the drive's write cache is used.
11533 		 */
11534 		break;
11535 	}
11536 }
11537 
11538 
11539 /*
11540  * Validate sata address.
11541  * Specified cport, pmport and qualifier has to match
11542  * passed sata_scsi configuration info.
11543  * The presence of an attached device is not verified.
11544  *
11545  * Returns 0 when address is valid, -1 otherwise.
11546  */
11547 static int
11548 sata_validate_sata_address(sata_hba_inst_t *sata_hba_inst, int cport,
11549 	int pmport, int qual)
11550 {
11551 	if (qual == SATA_ADDR_DCPORT && pmport != 0)
11552 		goto invalid_address;
11553 	if (cport >= SATA_NUM_CPORTS(sata_hba_inst))
11554 		goto invalid_address;
11555 	if ((qual == SATA_ADDR_DPMPORT || qual == SATA_ADDR_PMPORT) &&
11556 	    ((SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) != SATA_DTYPE_PMULT) ||
11557 	    (SATA_PMULT_INFO(sata_hba_inst, cport) == NULL) ||
11558 	    (pmport >= SATA_NUM_PMPORTS(sata_hba_inst, cport))))
11559 		goto invalid_address;
11560 
11561 	return (0);
11562 
11563 invalid_address:
11564 	return (-1);
11565 
11566 }
11567 
11568 /*
11569  * Validate scsi address
11570  * SCSI target address is translated into SATA cport/pmport and compared
11571  * with a controller port/device configuration. LUN has to be 0.
11572  * Returns 0 if a scsi target refers to an attached device,
11573  * returns 1 if address is valid but no valid device is attached,
11574  * returns 2 if address is valid but device type is unknown (not valid device),
11575  * returns -1 if bad address or device is of an unsupported type.
11576  * Upon return sata_device argument is set.
11577  *
11578  * Port multiplier is supported now.
11579  */
11580 static int
11581 sata_validate_scsi_address(sata_hba_inst_t *sata_hba_inst,
11582 	struct scsi_address *ap, sata_device_t *sata_device)
11583 {
11584 	int cport, pmport, qual, rval;
11585 
11586 	rval = -1;	/* Invalid address */
11587 	if (ap->a_lun != 0)
11588 		goto out;
11589 
11590 	qual = SCSI_TO_SATA_ADDR_QUAL(ap->a_target);
11591 	cport = SCSI_TO_SATA_CPORT(ap->a_target);
11592 	pmport = SCSI_TO_SATA_PMPORT(ap->a_target);
11593 
11594 	if (qual != SATA_ADDR_DCPORT && qual != SATA_ADDR_DPMPORT)
11595 		goto out;
11596 
11597 	if (sata_validate_sata_address(sata_hba_inst, cport, pmport, qual) ==
11598 	    0) {
11599 
11600 		sata_cport_info_t *cportinfo;
11601 		sata_pmult_info_t *pmultinfo;
11602 		sata_drive_info_t *sdinfo = NULL;
11603 
11604 		sata_device->satadev_addr.qual = qual;
11605 		sata_device->satadev_addr.cport = cport;
11606 		sata_device->satadev_addr.pmport = pmport;
11607 		sata_device->satadev_rev = SATA_DEVICE_REV_1;
11608 
11609 		rval = 1;	/* Valid sata address */
11610 
11611 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
11612 		if (qual == SATA_ADDR_DCPORT) {
11613 			if (cportinfo == NULL ||
11614 			    cportinfo->cport_dev_type == SATA_DTYPE_NONE)
11615 				goto out;
11616 
11617 			sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
11618 			if (cportinfo->cport_dev_type == SATA_DTYPE_UNKNOWN &&
11619 			    sdinfo != NULL) {
11620 				rval = 2;
11621 				goto out;
11622 			}
11623 
11624 			if ((cportinfo->cport_dev_type &
11625 			    SATA_VALID_DEV_TYPE) == 0) {
11626 				rval = -1;
11627 				goto out;
11628 			}
11629 
11630 		} else if (qual == SATA_ADDR_DPMPORT) {
11631 			pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
11632 			if (pmultinfo == NULL) {
11633 				rval = -1;
11634 				goto out;
11635 			}
11636 			if (SATA_PMPORT_INFO(sata_hba_inst, cport, pmport) ==
11637 			    NULL ||
11638 			    SATA_PMPORT_DEV_TYPE(sata_hba_inst, cport,
11639 			    pmport) == SATA_DTYPE_NONE)
11640 				goto out;
11641 
11642 			sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, cport,
11643 			    pmport);
11644 			if (SATA_PMPORT_DEV_TYPE(sata_hba_inst, cport,
11645 			    pmport) == SATA_DTYPE_UNKNOWN && sdinfo != NULL) {
11646 				rval = 2;
11647 				goto out;
11648 			}
11649 
11650 			if ((SATA_PMPORT_DEV_TYPE(sata_hba_inst, cport,
11651 			    pmport) && SATA_VALID_DEV_TYPE) == 0) {
11652 				rval = -1;
11653 				goto out;
11654 			}
11655 
11656 		} else {
11657 			rval = -1;
11658 			goto out;
11659 		}
11660 		if ((sdinfo == NULL) ||
11661 		    (sdinfo->satadrv_type & SATA_VALID_DEV_TYPE) == 0)
11662 			goto out;
11663 
11664 		sata_device->satadev_type = sdinfo->satadrv_type;
11665 
11666 		return (0);
11667 	}
11668 out:
11669 	if (rval > 0) {
11670 		SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
11671 		    "sata_validate_scsi_address: no valid target %x lun %x",
11672 		    ap->a_target, ap->a_lun);
11673 	}
11674 	return (rval);
11675 }
11676 
11677 /*
11678  * Find dip corresponding to passed device number
11679  *
11680  * Returns NULL if invalid device number is passed or device cannot be found,
11681  * Returns dip is device is found.
11682  */
11683 static dev_info_t *
11684 sata_devt_to_devinfo(dev_t dev)
11685 {
11686 	dev_info_t *dip;
11687 #ifndef __lock_lint
11688 	struct devnames *dnp;
11689 	major_t major = getmajor(dev);
11690 	int instance = SATA_MINOR2INSTANCE(getminor(dev));
11691 
11692 	if (major >= devcnt)
11693 		return (NULL);
11694 
11695 	dnp = &devnamesp[major];
11696 	LOCK_DEV_OPS(&(dnp->dn_lock));
11697 	dip = dnp->dn_head;
11698 	while (dip && (ddi_get_instance(dip) != instance)) {
11699 		dip = ddi_get_next(dip);
11700 	}
11701 	UNLOCK_DEV_OPS(&(dnp->dn_lock));
11702 #endif
11703 
11704 	return (dip);
11705 }
11706 
11707 
11708 /*
11709  * Probe device.
11710  * This function issues Identify Device command and initializes local
11711  * sata_drive_info structure if the device can be identified.
11712  * The device type is determined by examining Identify Device
11713  * command response.
11714  * If the sata_hba_inst has linked drive info structure for this
11715  * device address, the Identify Device data is stored into sata_drive_info
11716  * structure linked to the port info structure.
11717  *
11718  * sata_device has to refer to the valid sata port(s) for HBA described
11719  * by sata_hba_inst structure.
11720  *
11721  * Returns:
11722  *	SATA_SUCCESS if device type was successfully probed and port-linked
11723  *		drive info structure was updated;
11724  * 	SATA_FAILURE if there is no device, or device was not probed
11725  *		successully;
11726  *	SATA_RETRY if device probe can be retried later.
11727  * If a device cannot be identified, sata_device's dev_state and dev_type
11728  * fields are set to unknown.
11729  * There are no retries in this function. Any retries should be managed by
11730  * the caller.
11731  */
11732 
11733 
11734 static int
11735 sata_probe_device(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device)
11736 {
11737 	sata_pmport_info_t *pmportinfo;
11738 	sata_drive_info_t *sdinfo;
11739 	sata_drive_info_t new_sdinfo;	/* local drive info struct */
11740 	int rval;
11741 
11742 	ASSERT((SATA_CPORT_STATE(sata_hba_inst,
11743 	    sata_device->satadev_addr.cport) &
11744 	    (SATA_STATE_PROBED | SATA_STATE_READY)) != 0);
11745 
11746 	sata_device->satadev_type = SATA_DTYPE_NONE;
11747 
11748 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
11749 	    sata_device->satadev_addr.cport)));
11750 
11751 	if (sata_device->satadev_addr.qual == SATA_ADDR_DPMPORT) {
11752 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
11753 		    sata_device->satadev_addr.cport,
11754 		    sata_device->satadev_addr.pmport);
11755 		ASSERT(pmportinfo != NULL);
11756 	}
11757 
11758 	/* Get pointer to port-linked sata device info structure */
11759 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
11760 	if (sdinfo != NULL) {
11761 		sdinfo->satadrv_state &=
11762 		    ~(SATA_STATE_PROBED | SATA_STATE_READY);
11763 		sdinfo->satadrv_state |= SATA_STATE_PROBING;
11764 	} else {
11765 		/* No device to probe */
11766 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
11767 		    sata_device->satadev_addr.cport)));
11768 		sata_device->satadev_type = SATA_DTYPE_NONE;
11769 		sata_device->satadev_state = SATA_STATE_UNKNOWN;
11770 		return (SATA_FAILURE);
11771 	}
11772 	/*
11773 	 * Need to issue both types of identify device command and
11774 	 * determine device type by examining retreived data/status.
11775 	 * First, ATA Identify Device.
11776 	 */
11777 	bzero(&new_sdinfo, sizeof (sata_drive_info_t));
11778 	new_sdinfo.satadrv_addr = sata_device->satadev_addr;
11779 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
11780 	    sata_device->satadev_addr.cport)));
11781 	new_sdinfo.satadrv_type = SATA_DTYPE_ATADISK;
11782 	rval = sata_identify_device(sata_hba_inst, &new_sdinfo);
11783 	if (rval == SATA_RETRY) {
11784 		/* We may try to check for ATAPI device */
11785 		if (SATA_FEATURES(sata_hba_inst) & SATA_CTLF_ATAPI) {
11786 			/*
11787 			 * HBA supports ATAPI - try to issue Identify Packet
11788 			 * Device command.
11789 			 */
11790 			new_sdinfo.satadrv_type = SATA_DTYPE_ATAPI;
11791 			rval = sata_identify_device(sata_hba_inst, &new_sdinfo);
11792 		}
11793 	}
11794 	if (rval == SATA_SUCCESS) {
11795 		/*
11796 		 * Got something responding positively to ATA Identify Device
11797 		 * or to Identify Packet Device cmd.
11798 		 * Save last used device type.
11799 		 */
11800 		sata_device->satadev_type = new_sdinfo.satadrv_type;
11801 
11802 		/* save device info, if possible */
11803 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
11804 		    sata_device->satadev_addr.cport)));
11805 		sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
11806 		if (sdinfo == NULL) {
11807 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
11808 			    sata_device->satadev_addr.cport)));
11809 			return (SATA_FAILURE);
11810 		}
11811 		/*
11812 		 * Copy drive info into the port-linked drive info structure.
11813 		 */
11814 		*sdinfo = new_sdinfo;
11815 		sdinfo->satadrv_state &= ~SATA_STATE_PROBING;
11816 		sdinfo->satadrv_state |= SATA_STATE_PROBED;
11817 		if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
11818 			SATA_CPORT_DEV_TYPE(sata_hba_inst,
11819 			    sata_device->satadev_addr.cport) =
11820 			    sdinfo->satadrv_type;
11821 		else { /* SATA_ADDR_DPMPORT */
11822 			mutex_enter(&pmportinfo->pmport_mutex);
11823 			SATA_PMPORT_DEV_TYPE(sata_hba_inst,
11824 			    sata_device->satadev_addr.cport,
11825 			    sata_device->satadev_addr.pmport) =
11826 			    sdinfo->satadrv_type;
11827 			mutex_exit(&pmportinfo->pmport_mutex);
11828 		}
11829 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
11830 		    sata_device->satadev_addr.cport)));
11831 		return (SATA_SUCCESS);
11832 	}
11833 
11834 	/*
11835 	 * It may be SATA_RETRY or SATA_FAILURE return.
11836 	 * Looks like we cannot determine the device type at this time.
11837 	 */
11838 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
11839 	    sata_device->satadev_addr.cport)));
11840 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
11841 	if (sdinfo != NULL) {
11842 		sata_device->satadev_type = SATA_DTYPE_UNKNOWN;
11843 		sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
11844 		sdinfo->satadrv_state &= ~SATA_STATE_PROBING;
11845 		sdinfo->satadrv_state |= SATA_STATE_PROBED;
11846 		if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
11847 			SATA_CPORT_DEV_TYPE(sata_hba_inst,
11848 			    sata_device->satadev_addr.cport) =
11849 			    SATA_DTYPE_UNKNOWN;
11850 		else {
11851 			/* SATA_ADDR_DPMPORT */
11852 			mutex_enter(&pmportinfo->pmport_mutex);
11853 			if ((SATA_PMULT_INFO(sata_hba_inst,
11854 			    sata_device->satadev_addr.cport) != NULL) &&
11855 			    (SATA_PMPORT_INFO(sata_hba_inst,
11856 			    sata_device->satadev_addr.cport,
11857 			    sata_device->satadev_addr.pmport) != NULL))
11858 				SATA_PMPORT_DEV_TYPE(sata_hba_inst,
11859 				    sata_device->satadev_addr.cport,
11860 				    sata_device->satadev_addr.pmport) =
11861 				    SATA_DTYPE_UNKNOWN;
11862 			mutex_exit(&pmportinfo->pmport_mutex);
11863 		}
11864 	}
11865 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
11866 	    sata_device->satadev_addr.cport)));
11867 	return (rval);
11868 }
11869 
11870 
11871 /*
11872  * Get pointer to sata_drive_info structure.
11873  *
11874  * The sata_device has to contain address (cport, pmport and qualifier) for
11875  * specified sata_scsi structure.
11876  *
11877  * Returns NULL if device address is not valid for this HBA configuration.
11878  * Otherwise, returns a pointer to sata_drive_info structure.
11879  *
11880  * This function should be called with a port mutex held.
11881  */
11882 static sata_drive_info_t *
11883 sata_get_device_info(sata_hba_inst_t *sata_hba_inst,
11884     sata_device_t *sata_device)
11885 {
11886 	uint8_t cport = sata_device->satadev_addr.cport;
11887 	uint8_t pmport = sata_device->satadev_addr.pmport;
11888 	uint8_t qual = sata_device->satadev_addr.qual;
11889 
11890 	if (cport >= SATA_NUM_CPORTS(sata_hba_inst))
11891 		return (NULL);
11892 
11893 	if (!(SATA_CPORT_STATE(sata_hba_inst, cport) &
11894 	    (SATA_STATE_PROBED | SATA_STATE_READY)))
11895 		/* Port not probed yet */
11896 		return (NULL);
11897 
11898 	if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) == SATA_DTYPE_NONE)
11899 		return (NULL);
11900 
11901 	if (qual == SATA_ADDR_DCPORT) {
11902 		/* Request for a device on a controller port */
11903 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) ==
11904 		    SATA_DTYPE_PMULT)
11905 			/* Port multiplier attached */
11906 			return (NULL);
11907 		return (SATA_CPORT_DRV_INFO(sata_hba_inst, cport));
11908 	}
11909 	if (qual == SATA_ADDR_DPMPORT) {
11910 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) !=
11911 		    SATA_DTYPE_PMULT)
11912 			return (NULL);
11913 
11914 		if (pmport > SATA_NUM_PMPORTS(sata_hba_inst, cport))
11915 			return (NULL);
11916 
11917 		if (!(SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) &
11918 		    (SATA_STATE_PROBED | SATA_STATE_READY)))
11919 			/* Port multiplier port not probed yet */
11920 			return (NULL);
11921 
11922 		return (SATA_PMPORT_DRV_INFO(sata_hba_inst, cport, pmport));
11923 	}
11924 
11925 	/* we should not get here */
11926 	return (NULL);
11927 }
11928 
11929 
11930 /*
11931  * sata_identify_device.
11932  * Send Identify Device command to SATA HBA driver.
11933  * If command executes successfully, update sata_drive_info structure pointed
11934  * to by sdinfo argument, including Identify Device data.
11935  * If command fails, invalidate data in sata_drive_info.
11936  *
11937  * Cannot be called from interrupt level.
11938  *
11939  * Returns:
11940  * SATA_SUCCESS if the device was identified as a supported device,
11941  * SATA_RETRY if the device was not identified but could be retried,
11942  * SATA_FAILURE if the device was not identified and identify attempt
11943  *	should not be retried.
11944  */
11945 static int
11946 sata_identify_device(sata_hba_inst_t *sata_hba_inst,
11947     sata_drive_info_t *sdinfo)
11948 {
11949 	uint16_t cfg_word;
11950 	int rval;
11951 
11952 	/* fetch device identify data */
11953 	if ((rval = sata_fetch_device_identify_data(sata_hba_inst,
11954 	    sdinfo)) != SATA_SUCCESS)
11955 		goto fail_unknown;
11956 
11957 	cfg_word = sdinfo->satadrv_id.ai_config;
11958 
11959 	/* Set the correct device type */
11960 	if ((cfg_word & SATA_ATA_TYPE_MASK) == SATA_ATA_TYPE) {
11961 		sdinfo->satadrv_type = SATA_DTYPE_ATADISK;
11962 	} else if (cfg_word == SATA_CFA_TYPE) {
11963 		/* It's a Compact Flash media via CF-to-SATA HDD adapter */
11964 		sdinfo->satadrv_type = SATA_DTYPE_ATADISK;
11965 	} else if ((cfg_word & SATA_ATAPI_TYPE_MASK) == SATA_ATAPI_TYPE) {
11966 		switch (cfg_word & SATA_ATAPI_ID_DEV_TYPE) {
11967 		case SATA_ATAPI_CDROM_DEV:
11968 			sdinfo->satadrv_type = SATA_DTYPE_ATAPICD;
11969 			break;
11970 		case SATA_ATAPI_SQACC_DEV:
11971 			sdinfo->satadrv_type = SATA_DTYPE_ATAPITAPE;
11972 			break;
11973 		case SATA_ATAPI_DIRACC_DEV:
11974 			sdinfo->satadrv_type = SATA_DTYPE_ATAPIDISK;
11975 			break;
11976 		default:
11977 			sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
11978 		}
11979 	} else {
11980 			sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
11981 	}
11982 
11983 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
11984 		if (sdinfo->satadrv_capacity == 0) {
11985 			/* Non-LBA disk. Too bad... */
11986 			sata_log(sata_hba_inst, CE_WARN,
11987 			    "SATA disk device at port %d does not support LBA",
11988 			    sdinfo->satadrv_addr.cport);
11989 			rval = SATA_FAILURE;
11990 			goto fail_unknown;
11991 		}
11992 	}
11993 #if 0
11994 	/* Left for historical reason */
11995 	/*
11996 	 * Some initial version of SATA spec indicated that at least
11997 	 * UDMA mode 4 has to be supported. It is not metioned in
11998 	 * SerialATA 2.6, so this restriction is removed.
11999 	 */
12000 	/* Check for Ultra DMA modes 6 through 0 being supported */
12001 	for (i = 6; i >= 0; --i) {
12002 		if (sdinfo->satadrv_id.ai_ultradma & (1 << i))
12003 			break;
12004 	}
12005 
12006 	/*
12007 	 * At least UDMA 4 mode has to be supported. If mode 4 or
12008 	 * higher are not supported by the device, fail this
12009 	 * device.
12010 	 */
12011 	if (i < 4) {
12012 		/* No required Ultra DMA mode supported */
12013 		sata_log(sata_hba_inst, CE_WARN,
12014 		    "SATA disk device at port %d does not support UDMA "
12015 		    "mode 4 or higher", sdinfo->satadrv_addr.cport);
12016 		SATA_LOG_D((sata_hba_inst, CE_WARN,
12017 		    "mode 4 or higher required, %d supported", i));
12018 		rval = SATA_FAILURE;
12019 		goto fail_unknown;
12020 	}
12021 #endif
12022 
12023 	/*
12024 	 * For Disk devices, if it doesn't support UDMA mode, we would
12025 	 * like to return failure directly.
12026 	 */
12027 	if ((sdinfo->satadrv_type == SATA_DTYPE_ATADISK) &&
12028 	    !((sdinfo->satadrv_id.ai_validinfo & SATA_VALIDINFO_88) != 0 &&
12029 	    (sdinfo->satadrv_id.ai_ultradma & SATA_UDMA_SUP_MASK) != 0)) {
12030 		sata_log(sata_hba_inst, CE_WARN,
12031 		    "SATA disk device at port %d does not support UDMA",
12032 		    sdinfo->satadrv_addr.cport);
12033 		rval = SATA_FAILURE;
12034 		goto fail_unknown;
12035 	}
12036 
12037 	return (SATA_SUCCESS);
12038 
12039 fail_unknown:
12040 	/* Invalidate sata_drive_info ? */
12041 	sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
12042 	sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
12043 	return (rval);
12044 }
12045 
12046 /*
12047  * Log/display device information
12048  */
12049 static void
12050 sata_show_drive_info(sata_hba_inst_t *sata_hba_inst,
12051     sata_drive_info_t *sdinfo)
12052 {
12053 	int valid_version;
12054 	char msg_buf[MAXPATHLEN];
12055 	int i;
12056 
12057 	/* Show HBA path */
12058 	(void) ddi_pathname(SATA_DIP(sata_hba_inst), msg_buf);
12059 
12060 	cmn_err(CE_CONT, "?%s :\n", msg_buf);
12061 
12062 	switch (sdinfo->satadrv_type) {
12063 	case SATA_DTYPE_ATADISK:
12064 		(void) sprintf(msg_buf, "SATA disk device at");
12065 		break;
12066 
12067 	case SATA_DTYPE_ATAPICD:
12068 		(void) sprintf(msg_buf, "SATA CD/DVD (ATAPI) device at");
12069 		break;
12070 
12071 	case SATA_DTYPE_ATAPITAPE:
12072 		(void) sprintf(msg_buf, "SATA tape (ATAPI) device at");
12073 		break;
12074 
12075 	case SATA_DTYPE_ATAPIDISK:
12076 		(void) sprintf(msg_buf, "SATA disk (ATAPI) device at");
12077 		break;
12078 
12079 	case SATA_DTYPE_UNKNOWN:
12080 		(void) sprintf(msg_buf,
12081 		    "Unsupported SATA device type (cfg 0x%x) at ",
12082 		    sdinfo->satadrv_id.ai_config);
12083 		break;
12084 	}
12085 
12086 	if (sdinfo->satadrv_addr.qual == SATA_ADDR_DCPORT)
12087 		cmn_err(CE_CONT, "?\t%s port %d\n",
12088 		    msg_buf, sdinfo->satadrv_addr.cport);
12089 	else
12090 		cmn_err(CE_CONT, "?\t%s port %d:%d\n",
12091 		    msg_buf, sdinfo->satadrv_addr.cport,
12092 		    sdinfo->satadrv_addr.pmport);
12093 
12094 	bcopy(&sdinfo->satadrv_id.ai_model, msg_buf,
12095 	    sizeof (sdinfo->satadrv_id.ai_model));
12096 	swab(msg_buf, msg_buf, sizeof (sdinfo->satadrv_id.ai_model));
12097 	msg_buf[sizeof (sdinfo->satadrv_id.ai_model)] = '\0';
12098 	cmn_err(CE_CONT, "?\tmodel %s\n", msg_buf);
12099 
12100 	bcopy(&sdinfo->satadrv_id.ai_fw, msg_buf,
12101 	    sizeof (sdinfo->satadrv_id.ai_fw));
12102 	swab(msg_buf, msg_buf, sizeof (sdinfo->satadrv_id.ai_fw));
12103 	msg_buf[sizeof (sdinfo->satadrv_id.ai_fw)] = '\0';
12104 	cmn_err(CE_CONT, "?\tfirmware %s\n", msg_buf);
12105 
12106 	bcopy(&sdinfo->satadrv_id.ai_drvser, msg_buf,
12107 	    sizeof (sdinfo->satadrv_id.ai_drvser));
12108 	swab(msg_buf, msg_buf, sizeof (sdinfo->satadrv_id.ai_drvser));
12109 	msg_buf[sizeof (sdinfo->satadrv_id.ai_drvser)] = '\0';
12110 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
12111 		cmn_err(CE_CONT, "?\tserial number %s\n", msg_buf);
12112 	} else {
12113 		/*
12114 		 * Some drives do not implement serial number and may
12115 		 * violate the spec by providing spaces rather than zeros
12116 		 * in serial number field. Scan the buffer to detect it.
12117 		 */
12118 		for (i = 0; i < sizeof (sdinfo->satadrv_id.ai_drvser); i++) {
12119 			if (msg_buf[i] != '\0' && msg_buf[i] != ' ')
12120 				break;
12121 		}
12122 		if (i == sizeof (sdinfo->satadrv_id.ai_drvser)) {
12123 			cmn_err(CE_CONT, "?\tserial number - none\n");
12124 		} else {
12125 			cmn_err(CE_CONT, "?\tserial number %s\n", msg_buf);
12126 		}
12127 	}
12128 
12129 #ifdef SATA_DEBUG
12130 	if (sdinfo->satadrv_id.ai_majorversion != 0 &&
12131 	    sdinfo->satadrv_id.ai_majorversion != 0xffff) {
12132 		int i;
12133 		for (i = 14; i >= 2; i--) {
12134 			if (sdinfo->satadrv_id.ai_majorversion & (1 << i)) {
12135 				valid_version = i;
12136 				break;
12137 			}
12138 		}
12139 		cmn_err(CE_CONT,
12140 		    "?\tATA/ATAPI-%d supported, majver 0x%x minver 0x%x\n",
12141 		    valid_version,
12142 		    sdinfo->satadrv_id.ai_majorversion,
12143 		    sdinfo->satadrv_id.ai_minorversion);
12144 	}
12145 #endif
12146 	/* Log some info */
12147 	cmn_err(CE_CONT, "?\tsupported features:\n");
12148 	msg_buf[0] = '\0';
12149 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
12150 		if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48)
12151 			(void) strlcat(msg_buf, "48-bit LBA, ", MAXPATHLEN);
12152 		else if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA28)
12153 			(void) strlcat(msg_buf, "28-bit LBA, ", MAXPATHLEN);
12154 	}
12155 	if (sdinfo->satadrv_features_support & SATA_DEV_F_DMA)
12156 		(void) strlcat(msg_buf, "DMA", MAXPATHLEN);
12157 	if (sdinfo->satadrv_features_support & SATA_DEV_F_NCQ)
12158 		(void) strlcat(msg_buf, ", Native Command Queueing",
12159 		    MAXPATHLEN);
12160 	if (sdinfo->satadrv_features_support & SATA_DEV_F_TCQ)
12161 		(void) strlcat(msg_buf, ", Legacy Tagged Queuing", MAXPATHLEN);
12162 	if ((sdinfo->satadrv_id.ai_cmdset82 & SATA_SMART_SUPPORTED) &&
12163 	    (sdinfo->satadrv_id.ai_features85 & SATA_SMART_ENABLED))
12164 		(void) strlcat(msg_buf, ", SMART", MAXPATHLEN);
12165 	if ((sdinfo->satadrv_id.ai_cmdset84 & SATA_SMART_SELF_TEST_SUPPORTED) &&
12166 	    (sdinfo->satadrv_id.ai_features87 & SATA_SMART_SELF_TEST_SUPPORTED))
12167 		(void) strlcat(msg_buf, ", SMART self-test", MAXPATHLEN);
12168 	cmn_err(CE_CONT, "?\t %s\n", msg_buf);
12169 	if (sdinfo->satadrv_features_support & SATA_DEV_F_SATA2)
12170 		cmn_err(CE_CONT, "?\tSATA Gen2 signaling speed (3.0Gbps)\n");
12171 	else if (sdinfo->satadrv_features_support & SATA_DEV_F_SATA1)
12172 		cmn_err(CE_CONT, "?\tSATA Gen1 signaling speed (1.5Gbps)\n");
12173 	if (sdinfo->satadrv_features_support &
12174 	    (SATA_DEV_F_TCQ | SATA_DEV_F_NCQ)) {
12175 		msg_buf[0] = '\0';
12176 		(void) snprintf(msg_buf, MAXPATHLEN,
12177 		    "Supported queue depth %d",
12178 		    sdinfo->satadrv_queue_depth);
12179 		if (!(sata_func_enable &
12180 		    (SATA_ENABLE_QUEUING | SATA_ENABLE_NCQ)))
12181 			(void) strlcat(msg_buf,
12182 			    " - queueing disabled globally", MAXPATHLEN);
12183 		else if (sdinfo->satadrv_queue_depth >
12184 		    sdinfo->satadrv_max_queue_depth) {
12185 			(void) snprintf(&msg_buf[strlen(msg_buf)],
12186 			    MAXPATHLEN - strlen(msg_buf), ", limited to %d",
12187 			    (int)sdinfo->satadrv_max_queue_depth);
12188 		}
12189 		cmn_err(CE_CONT, "?\t%s\n", msg_buf);
12190 	}
12191 
12192 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
12193 #ifdef __i386
12194 		(void) sprintf(msg_buf, "\tcapacity = %llu sectors\n",
12195 		    sdinfo->satadrv_capacity);
12196 #else
12197 		(void) sprintf(msg_buf, "\tcapacity = %lu sectors\n",
12198 		    sdinfo->satadrv_capacity);
12199 #endif
12200 		cmn_err(CE_CONT, "?%s", msg_buf);
12201 	}
12202 }
12203 
12204 /*
12205  * Log/display port multiplier information
12206  * No Mutex should be hold.
12207  */
12208 static void
12209 sata_show_pmult_info(sata_hba_inst_t *sata_hba_inst,
12210     sata_device_t *sata_device)
12211 {
12212 	_NOTE(ARGUNUSED(sata_hba_inst))
12213 
12214 	int cport = sata_device->satadev_addr.cport;
12215 	sata_pmult_info_t *pmultinfo;
12216 	char msg_buf[MAXPATHLEN];
12217 	uint32_t gscr0, gscr1, gscr2, gscr64;
12218 
12219 	mutex_enter(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
12220 	pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
12221 	if (pmultinfo == NULL) {
12222 		mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
12223 		return;
12224 	}
12225 
12226 	gscr0 = pmultinfo->pmult_gscr.gscr0;
12227 	gscr1 = pmultinfo->pmult_gscr.gscr1;
12228 	gscr2 = pmultinfo->pmult_gscr.gscr2;
12229 	gscr64 = pmultinfo->pmult_gscr.gscr64;
12230 	mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
12231 
12232 	cmn_err(CE_CONT, "?Port Multiplier %d device-ports found at port %d",
12233 	    sata_device->satadev_add_info, sata_device->satadev_addr.cport);
12234 
12235 	(void) sprintf(msg_buf, "\tVendor_ID 0x%04x, Module_ID 0x%04x",
12236 	    gscr0 & 0xffff, (gscr0 >> 16) & 0xffff);
12237 	cmn_err(CE_CONT, "?%s", msg_buf);
12238 
12239 	(void) strcpy(msg_buf, "\tSupport SATA PMP Spec ");
12240 	if (gscr1 & (1 << 3))
12241 		(void) strlcat(msg_buf, "1.2", MAXPATHLEN);
12242 	else if (gscr1 & (1 << 2))
12243 		(void) strlcat(msg_buf, "1.1", MAXPATHLEN);
12244 	else if (gscr1 & (1 << 1))
12245 		(void) strlcat(msg_buf, "1.0", MAXPATHLEN);
12246 	else
12247 		(void) strlcat(msg_buf, "unknown", MAXPATHLEN);
12248 	cmn_err(CE_CONT, "?%s", msg_buf);
12249 
12250 	(void) strcpy(msg_buf, "\tSupport ");
12251 	if (gscr64 & (1 << 3))
12252 		(void) strlcat(msg_buf, "Asy-Notif, ",
12253 		    MAXPATHLEN);
12254 	if (gscr64 & (1 << 2))
12255 		(void) strlcat(msg_buf, "Dyn-SSC, ", MAXPATHLEN);
12256 	if (gscr64 & (1 << 1))
12257 		(void) strlcat(msg_buf, "Iss-PMREQ, ", MAXPATHLEN);
12258 	if (gscr64 & (1 << 0))
12259 		(void) strlcat(msg_buf, "BIST", MAXPATHLEN);
12260 	if ((gscr64 & 0xf) == 0)
12261 		(void) strlcat(msg_buf, "nothing", MAXPATHLEN);
12262 	cmn_err(CE_CONT, "?%s", msg_buf);
12263 
12264 	(void) sprintf(msg_buf, "\tNumber of exposed device fan-out ports: %d",
12265 	    gscr2 & SATA_PMULT_PORTNUM_MASK);
12266 	cmn_err(CE_CONT, "?%s", msg_buf);
12267 }
12268 
12269 /*
12270  * sata_save_drive_settings extracts current setting of the device and stores
12271  * it for future reference, in case the device setup would need to be restored
12272  * after the device reset.
12273  *
12274  * For all devices read ahead and write cache settings are saved, if the
12275  * device supports these features at all.
12276  * For ATAPI devices the Removable Media Status Notification setting is saved.
12277  */
12278 static void
12279 sata_save_drive_settings(sata_drive_info_t *sdinfo)
12280 {
12281 	if (SATA_READ_AHEAD_SUPPORTED(sdinfo->satadrv_id) ||
12282 	    SATA_WRITE_CACHE_SUPPORTED(sdinfo->satadrv_id)) {
12283 
12284 		/* Current setting of Read Ahead (and Read Cache) */
12285 		if (SATA_READ_AHEAD_ENABLED(sdinfo->satadrv_id))
12286 			sdinfo->satadrv_settings |= SATA_DEV_READ_AHEAD;
12287 		else
12288 			sdinfo->satadrv_settings &= ~SATA_DEV_READ_AHEAD;
12289 
12290 		/* Current setting of Write Cache */
12291 		if (SATA_WRITE_CACHE_ENABLED(sdinfo->satadrv_id))
12292 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
12293 		else
12294 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
12295 	}
12296 
12297 	if (sdinfo->satadrv_type == SATA_DTYPE_ATAPICD) {
12298 		if (SATA_RM_NOTIFIC_SUPPORTED(sdinfo->satadrv_id))
12299 			sdinfo->satadrv_settings |= SATA_DEV_RMSN;
12300 		else
12301 			sdinfo->satadrv_settings &= ~SATA_DEV_RMSN;
12302 	}
12303 }
12304 
12305 
12306 /*
12307  * sata_check_capacity function determines a disk capacity
12308  * and addressing mode (LBA28/LBA48) by examining a disk identify device data.
12309  *
12310  * NOTE: CHS mode is not supported! If a device does not support LBA,
12311  * this function is not called.
12312  *
12313  * Returns device capacity in number of blocks, i.e. largest addressable LBA+1
12314  */
12315 static uint64_t
12316 sata_check_capacity(sata_drive_info_t *sdinfo)
12317 {
12318 	uint64_t capacity = 0;
12319 	int i;
12320 
12321 	if (sdinfo->satadrv_type != SATA_DTYPE_ATADISK ||
12322 	    !sdinfo->satadrv_id.ai_cap & SATA_LBA_SUPPORT)
12323 		/* Capacity valid only for LBA-addressable disk devices */
12324 		return (0);
12325 
12326 	if ((sdinfo->satadrv_id.ai_validinfo & SATA_VALIDINFO_88) &&
12327 	    (sdinfo->satadrv_id.ai_cmdset83 & SATA_EXT48) &&
12328 	    (sdinfo->satadrv_id.ai_features86 & SATA_EXT48)) {
12329 		/* LBA48 mode supported and enabled */
12330 		sdinfo->satadrv_features_support |= SATA_DEV_F_LBA48 |
12331 		    SATA_DEV_F_LBA28;
12332 		for (i = 3;  i >= 0;  --i) {
12333 			capacity <<= 16;
12334 			capacity += sdinfo->satadrv_id.ai_addrsecxt[i];
12335 		}
12336 	} else {
12337 		capacity = sdinfo->satadrv_id.ai_addrsec[1];
12338 		capacity <<= 16;
12339 		capacity += sdinfo->satadrv_id.ai_addrsec[0];
12340 		if (capacity >= 0x1000000)
12341 			/* LBA28 mode */
12342 			sdinfo->satadrv_features_support |= SATA_DEV_F_LBA28;
12343 	}
12344 	return (capacity);
12345 }
12346 
12347 
12348 /*
12349  * Allocate consistent buffer for DMA transfer
12350  *
12351  * Cannot be called from interrupt level or with mutex held - it may sleep.
12352  *
12353  * Returns pointer to allocated buffer structure, or NULL if allocation failed.
12354  */
12355 static struct buf *
12356 sata_alloc_local_buffer(sata_pkt_txlate_t *spx, int len)
12357 {
12358 	struct scsi_address ap;
12359 	struct buf *bp;
12360 	ddi_dma_attr_t	cur_dma_attr;
12361 
12362 	ASSERT(spx->txlt_sata_pkt != NULL);
12363 	ap.a_hba_tran = spx->txlt_sata_hba_inst->satahba_scsi_tran;
12364 	ap.a_target = SATA_TO_SCSI_TARGET(
12365 	    spx->txlt_sata_pkt->satapkt_device.satadev_addr.cport,
12366 	    spx->txlt_sata_pkt->satapkt_device.satadev_addr.pmport,
12367 	    spx->txlt_sata_pkt->satapkt_device.satadev_addr.qual);
12368 	ap.a_lun = 0;
12369 
12370 	bp = scsi_alloc_consistent_buf(&ap, NULL, len,
12371 	    B_READ, SLEEP_FUNC, NULL);
12372 
12373 	if (bp != NULL) {
12374 		/* Allocate DMA resources for this buffer */
12375 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = bp;
12376 		/*
12377 		 * We use a local version of the dma_attr, to account
12378 		 * for a device addressing limitations.
12379 		 * sata_adjust_dma_attr() will handle sdinfo == NULL which
12380 		 * will cause dma attributes to be adjusted to a lowest
12381 		 * acceptable level.
12382 		 */
12383 		sata_adjust_dma_attr(NULL,
12384 		    SATA_DMA_ATTR(spx->txlt_sata_hba_inst), &cur_dma_attr);
12385 
12386 		if (sata_dma_buf_setup(spx, PKT_CONSISTENT,
12387 		    SLEEP_FUNC, NULL, &cur_dma_attr) != DDI_SUCCESS) {
12388 			scsi_free_consistent_buf(bp);
12389 			spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
12390 			bp = NULL;
12391 		}
12392 	}
12393 	return (bp);
12394 }
12395 
12396 /*
12397  * Release local buffer (consistent buffer for DMA transfer) allocated
12398  * via sata_alloc_local_buffer().
12399  */
12400 static void
12401 sata_free_local_buffer(sata_pkt_txlate_t *spx)
12402 {
12403 	ASSERT(spx->txlt_sata_pkt != NULL);
12404 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp != NULL);
12405 
12406 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies = 0;
12407 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_dma_cookie_list = NULL;
12408 
12409 	sata_common_free_dma_rsrcs(spx);
12410 
12411 	/* Free buffer */
12412 	scsi_free_consistent_buf(spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp);
12413 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
12414 }
12415 
12416 /*
12417  * Allocate sata_pkt
12418  * Pkt structure version and embedded strcutures version are initialized.
12419  * sata_pkt and sata_pkt_txlate structures are cross-linked.
12420  *
12421  * Since this may be called in interrupt context by sata_scsi_init_pkt,
12422  * callback argument determines if it can sleep or not.
12423  * Hence, it should not be called from interrupt context.
12424  *
12425  * If successful, non-NULL pointer to a sata pkt is returned.
12426  * Upon failure, NULL pointer is returned.
12427  */
12428 static sata_pkt_t *
12429 sata_pkt_alloc(sata_pkt_txlate_t *spx, int (*callback)(caddr_t))
12430 {
12431 	sata_pkt_t *spkt;
12432 	int kmsflag;
12433 
12434 	kmsflag = (callback == SLEEP_FUNC) ? KM_SLEEP : KM_NOSLEEP;
12435 	spkt = kmem_zalloc(sizeof (sata_pkt_t), kmsflag);
12436 	if (spkt == NULL) {
12437 		SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
12438 		    "sata_pkt_alloc: failed"));
12439 		return (NULL);
12440 	}
12441 	spkt->satapkt_rev = SATA_PKT_REV;
12442 	spkt->satapkt_cmd.satacmd_rev = SATA_CMD_REV;
12443 	spkt->satapkt_device.satadev_rev = SATA_DEVICE_REV;
12444 	spkt->satapkt_framework_private = spx;
12445 	spx->txlt_sata_pkt = spkt;
12446 	return (spkt);
12447 }
12448 
12449 /*
12450  * Free sata pkt allocated via sata_pkt_alloc()
12451  */
12452 static void
12453 sata_pkt_free(sata_pkt_txlate_t *spx)
12454 {
12455 	ASSERT(spx->txlt_sata_pkt != NULL);
12456 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp == NULL);
12457 	kmem_free(spx->txlt_sata_pkt, sizeof (sata_pkt_t));
12458 	spx->txlt_sata_pkt = NULL;
12459 }
12460 
12461 
12462 /*
12463  * Adjust DMA attributes.
12464  * SCSI cmds block count is up to 24 bits, SATA cmd block count vary
12465  * from 8 bits to 16 bits, depending on a command being used.
12466  * Limiting max block count arbitrarily to 256 for all read/write
12467  * commands may affects performance, so check both the device and
12468  * controller capability before adjusting dma attributes.
12469  */
12470 void
12471 sata_adjust_dma_attr(sata_drive_info_t *sdinfo, ddi_dma_attr_t *dma_attr,
12472     ddi_dma_attr_t *adj_dma_attr)
12473 {
12474 	uint32_t count_max;
12475 
12476 	/* Copy original attributes */
12477 	*adj_dma_attr = *dma_attr;
12478 	/*
12479 	 * Things to consider: device addressing capability,
12480 	 * "excessive" controller DMA capabilities.
12481 	 * If a device is being probed/initialized, there are
12482 	 * no device info - use default limits then.
12483 	 */
12484 	if (sdinfo == NULL) {
12485 		count_max = dma_attr->dma_attr_granular * 0x100;
12486 		if (dma_attr->dma_attr_count_max > count_max)
12487 			adj_dma_attr->dma_attr_count_max = count_max;
12488 		if (dma_attr->dma_attr_maxxfer > count_max)
12489 			adj_dma_attr->dma_attr_maxxfer = count_max;
12490 		return;
12491 	}
12492 
12493 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
12494 		if (sdinfo->satadrv_features_support & (SATA_DEV_F_LBA48)) {
12495 			/*
12496 			 * 16-bit sector count may be used - we rely on
12497 			 * the assumption that only read and write cmds
12498 			 * will request more than 256 sectors worth of data
12499 			 */
12500 			count_max = adj_dma_attr->dma_attr_granular * 0x10000;
12501 		} else {
12502 			/*
12503 			 * 8-bit sector count will be used - default limits
12504 			 * for dma attributes
12505 			 */
12506 			count_max = adj_dma_attr->dma_attr_granular * 0x100;
12507 		}
12508 		/*
12509 		 * Adjust controler dma attributes, if necessary
12510 		 */
12511 		if (dma_attr->dma_attr_count_max > count_max)
12512 			adj_dma_attr->dma_attr_count_max = count_max;
12513 		if (dma_attr->dma_attr_maxxfer > count_max)
12514 			adj_dma_attr->dma_attr_maxxfer = count_max;
12515 	}
12516 }
12517 
12518 
12519 /*
12520  * Allocate DMA resources for the buffer
12521  * This function handles initial DMA resource allocation as well as
12522  * DMA window shift and may be called repeatedly for the same DMA window
12523  * until all DMA cookies in the DMA window are processed.
12524  * To guarantee that there is always a coherent set of cookies to process
12525  * by SATA HBA driver (observing alignment, device granularity, etc.),
12526  * the number of slots for DMA cookies is equal to lesser of  a number of
12527  * cookies in a DMA window and a max number of scatter/gather entries.
12528  *
12529  * Returns DDI_SUCCESS upon successful operation.
12530  * Return failure code of a failing command or DDI_FAILURE when
12531  * internal cleanup failed.
12532  */
12533 static int
12534 sata_dma_buf_setup(sata_pkt_txlate_t *spx, int flags,
12535     int (*callback)(caddr_t), caddr_t arg,
12536     ddi_dma_attr_t *cur_dma_attr)
12537 {
12538 	int	rval;
12539 	off_t	offset;
12540 	size_t	size;
12541 	int	max_sg_len, req_len, i;
12542 	uint_t	dma_flags;
12543 	struct buf	*bp;
12544 	uint64_t	cur_txfer_len;
12545 
12546 
12547 	ASSERT(spx->txlt_sata_pkt != NULL);
12548 	bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
12549 	ASSERT(bp != NULL);
12550 
12551 
12552 	if (spx->txlt_buf_dma_handle == NULL) {
12553 		/*
12554 		 * No DMA resources allocated so far - this is a first call
12555 		 * for this sata pkt.
12556 		 */
12557 		rval = ddi_dma_alloc_handle(SATA_DIP(spx->txlt_sata_hba_inst),
12558 		    cur_dma_attr, callback, arg, &spx->txlt_buf_dma_handle);
12559 
12560 		if (rval != DDI_SUCCESS) {
12561 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
12562 			    "sata_dma_buf_setup: no buf DMA resources %x",
12563 			    rval));
12564 			return (rval);
12565 		}
12566 
12567 		if (bp->b_flags & B_READ)
12568 			dma_flags = DDI_DMA_READ;
12569 		else
12570 			dma_flags = DDI_DMA_WRITE;
12571 
12572 		if (flags & PKT_CONSISTENT)
12573 			dma_flags |= DDI_DMA_CONSISTENT;
12574 
12575 		if (flags & PKT_DMA_PARTIAL)
12576 			dma_flags |= DDI_DMA_PARTIAL;
12577 
12578 		/*
12579 		 * Check buffer alignment and size against dma attributes
12580 		 * Consider dma_attr_align only. There may be requests
12581 		 * with the size lower than device granularity, but they
12582 		 * will not read/write from/to the device, so no adjustment
12583 		 * is necessary. The dma_attr_minxfer theoretically should
12584 		 * be considered, but no HBA driver is checking it.
12585 		 */
12586 		if (IS_P2ALIGNED(bp->b_un.b_addr,
12587 		    cur_dma_attr->dma_attr_align)) {
12588 			rval = ddi_dma_buf_bind_handle(
12589 			    spx->txlt_buf_dma_handle,
12590 			    bp, dma_flags, callback, arg,
12591 			    &spx->txlt_dma_cookie,
12592 			    &spx->txlt_curwin_num_dma_cookies);
12593 		} else { /* Buffer is not aligned */
12594 
12595 			int	(*ddicallback)(caddr_t);
12596 			size_t	bufsz;
12597 
12598 			/* Check id sleeping is allowed */
12599 			ddicallback = (callback == NULL_FUNC) ?
12600 			    DDI_DMA_DONTWAIT : DDI_DMA_SLEEP;
12601 
12602 			SATADBG2(SATA_DBG_DMA_SETUP, spx->txlt_sata_hba_inst,
12603 			    "mis-aligned buffer: addr=0x%p, cnt=%lu",
12604 			    (void *)bp->b_un.b_addr, bp->b_bcount);
12605 
12606 			if (bp->b_flags & (B_PAGEIO|B_PHYS))
12607 				/*
12608 				 * CPU will need to access data in the buffer
12609 				 * (for copying) so map it.
12610 				 */
12611 				bp_mapin(bp);
12612 
12613 			ASSERT(spx->txlt_tmp_buf == NULL);
12614 
12615 			/* Buffer may be padded by ddi_dma_mem_alloc()! */
12616 			rval = ddi_dma_mem_alloc(
12617 			    spx->txlt_buf_dma_handle,
12618 			    bp->b_bcount,
12619 			    &sata_acc_attr,
12620 			    DDI_DMA_STREAMING,
12621 			    ddicallback, NULL,
12622 			    &spx->txlt_tmp_buf,
12623 			    &bufsz,
12624 			    &spx->txlt_tmp_buf_handle);
12625 
12626 			if (rval != DDI_SUCCESS) {
12627 				/* DMA mapping failed */
12628 				(void) ddi_dma_free_handle(
12629 				    &spx->txlt_buf_dma_handle);
12630 				spx->txlt_buf_dma_handle = NULL;
12631 #ifdef SATA_DEBUG
12632 				mbuffail_count++;
12633 #endif
12634 				SATADBG1(SATA_DBG_DMA_SETUP,
12635 				    spx->txlt_sata_hba_inst,
12636 				    "sata_dma_buf_setup: "
12637 				    "buf dma mem alloc failed %x\n", rval);
12638 				return (rval);
12639 			}
12640 			ASSERT(IS_P2ALIGNED(spx->txlt_tmp_buf,
12641 			    cur_dma_attr->dma_attr_align));
12642 
12643 #ifdef SATA_DEBUG
12644 			mbuf_count++;
12645 
12646 			if (bp->b_bcount != bufsz)
12647 				/*
12648 				 * This will require special handling, because
12649 				 * DMA cookies will be based on the temporary
12650 				 * buffer size, not the original buffer
12651 				 * b_bcount, so the residue may have to
12652 				 * be counted differently.
12653 				 */
12654 				SATADBG2(SATA_DBG_DMA_SETUP,
12655 				    spx->txlt_sata_hba_inst,
12656 				    "sata_dma_buf_setup: bp size %x != "
12657 				    "bufsz %x\n", bp->b_bcount, bufsz);
12658 #endif
12659 			if (dma_flags & DDI_DMA_WRITE) {
12660 				/*
12661 				 * Write operation - copy data into
12662 				 * an aligned temporary buffer. Buffer will be
12663 				 * synced for device by ddi_dma_addr_bind_handle
12664 				 */
12665 				bcopy(bp->b_un.b_addr, spx->txlt_tmp_buf,
12666 				    bp->b_bcount);
12667 			}
12668 
12669 			rval = ddi_dma_addr_bind_handle(
12670 			    spx->txlt_buf_dma_handle,
12671 			    NULL,
12672 			    spx->txlt_tmp_buf,
12673 			    bufsz, dma_flags, ddicallback, 0,
12674 			    &spx->txlt_dma_cookie,
12675 			    &spx->txlt_curwin_num_dma_cookies);
12676 		}
12677 
12678 		switch (rval) {
12679 		case DDI_DMA_PARTIAL_MAP:
12680 			SATADBG1(SATA_DBG_DMA_SETUP, spx->txlt_sata_hba_inst,
12681 			    "sata_dma_buf_setup: DMA Partial Map\n", NULL);
12682 			/*
12683 			 * Partial DMA mapping.
12684 			 * Retrieve number of DMA windows for this request.
12685 			 */
12686 			if (ddi_dma_numwin(spx->txlt_buf_dma_handle,
12687 			    &spx->txlt_num_dma_win) != DDI_SUCCESS) {
12688 				if (spx->txlt_tmp_buf != NULL) {
12689 					ddi_dma_mem_free(
12690 					    &spx->txlt_tmp_buf_handle);
12691 					spx->txlt_tmp_buf = NULL;
12692 				}
12693 				(void) ddi_dma_unbind_handle(
12694 				    spx->txlt_buf_dma_handle);
12695 				(void) ddi_dma_free_handle(
12696 				    &spx->txlt_buf_dma_handle);
12697 				spx->txlt_buf_dma_handle = NULL;
12698 				SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
12699 				    "sata_dma_buf_setup: numwin failed\n"));
12700 				return (DDI_FAILURE);
12701 			}
12702 			SATADBG2(SATA_DBG_DMA_SETUP,
12703 			    spx->txlt_sata_hba_inst,
12704 			    "sata_dma_buf_setup: windows: %d, cookies: %d\n",
12705 			    spx->txlt_num_dma_win,
12706 			    spx->txlt_curwin_num_dma_cookies);
12707 			spx->txlt_cur_dma_win = 0;
12708 			break;
12709 
12710 		case DDI_DMA_MAPPED:
12711 			/* DMA fully mapped */
12712 			spx->txlt_num_dma_win = 1;
12713 			spx->txlt_cur_dma_win = 0;
12714 			SATADBG1(SATA_DBG_DMA_SETUP,
12715 			    spx->txlt_sata_hba_inst,
12716 			    "sata_dma_buf_setup: windows: 1 "
12717 			    "cookies: %d\n", spx->txlt_curwin_num_dma_cookies);
12718 			break;
12719 
12720 		default:
12721 			/* DMA mapping failed */
12722 			if (spx->txlt_tmp_buf != NULL) {
12723 				ddi_dma_mem_free(
12724 				    &spx->txlt_tmp_buf_handle);
12725 				spx->txlt_tmp_buf = NULL;
12726 			}
12727 			(void) ddi_dma_free_handle(&spx->txlt_buf_dma_handle);
12728 			spx->txlt_buf_dma_handle = NULL;
12729 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
12730 			    "sata_dma_buf_setup: buf dma handle binding "
12731 			    "failed %x\n", rval));
12732 			return (rval);
12733 		}
12734 		spx->txlt_curwin_processed_dma_cookies = 0;
12735 		spx->txlt_dma_cookie_list = NULL;
12736 	} else {
12737 		/*
12738 		 * DMA setup is reused. Check if we need to process more
12739 		 * cookies in current window, or to get next window, if any.
12740 		 */
12741 
12742 		ASSERT(spx->txlt_curwin_processed_dma_cookies <=
12743 		    spx->txlt_curwin_num_dma_cookies);
12744 
12745 		if (spx->txlt_curwin_processed_dma_cookies ==
12746 		    spx->txlt_curwin_num_dma_cookies) {
12747 			/*
12748 			 * All cookies from current DMA window were processed.
12749 			 * Get next DMA window.
12750 			 */
12751 			spx->txlt_cur_dma_win++;
12752 			if (spx->txlt_cur_dma_win < spx->txlt_num_dma_win) {
12753 				(void) ddi_dma_getwin(spx->txlt_buf_dma_handle,
12754 				    spx->txlt_cur_dma_win, &offset, &size,
12755 				    &spx->txlt_dma_cookie,
12756 				    &spx->txlt_curwin_num_dma_cookies);
12757 				spx->txlt_curwin_processed_dma_cookies = 0;
12758 			} else {
12759 				/* No more windows! End of request! */
12760 				/* What to do? - panic for now */
12761 				ASSERT(spx->txlt_cur_dma_win >=
12762 				    spx->txlt_num_dma_win);
12763 
12764 				spx->txlt_curwin_num_dma_cookies = 0;
12765 				spx->txlt_curwin_processed_dma_cookies = 0;
12766 				spx->txlt_sata_pkt->
12767 				    satapkt_cmd.satacmd_num_dma_cookies = 0;
12768 				return (DDI_SUCCESS);
12769 			}
12770 		}
12771 	}
12772 	/* There better be at least one DMA cookie outstanding */
12773 	ASSERT((spx->txlt_curwin_num_dma_cookies -
12774 	    spx->txlt_curwin_processed_dma_cookies) > 0);
12775 
12776 	if (spx->txlt_dma_cookie_list == &spx->txlt_dma_cookie) {
12777 		/* The default cookie slot was used in previous run */
12778 		ASSERT(spx->txlt_curwin_processed_dma_cookies == 0);
12779 		spx->txlt_dma_cookie_list = NULL;
12780 		spx->txlt_dma_cookie_list_len = 0;
12781 	}
12782 	if (spx->txlt_curwin_processed_dma_cookies == 0) {
12783 		/*
12784 		 * Processing a new DMA window - set-up dma cookies list.
12785 		 * We may reuse previously allocated cookie array if it is
12786 		 * possible.
12787 		 */
12788 		if (spx->txlt_dma_cookie_list != NULL &&
12789 		    spx->txlt_dma_cookie_list_len <
12790 		    spx->txlt_curwin_num_dma_cookies) {
12791 			/*
12792 			 * New DMA window contains more cookies than
12793 			 * the previous one. We need larger cookie list - free
12794 			 * the old one.
12795 			 */
12796 			(void) kmem_free(spx->txlt_dma_cookie_list,
12797 			    spx->txlt_dma_cookie_list_len *
12798 			    sizeof (ddi_dma_cookie_t));
12799 			spx->txlt_dma_cookie_list = NULL;
12800 			spx->txlt_dma_cookie_list_len = 0;
12801 		}
12802 		if (spx->txlt_dma_cookie_list == NULL) {
12803 			/*
12804 			 * Calculate lesser of number of cookies in this
12805 			 * DMA window and number of s/g entries.
12806 			 */
12807 			max_sg_len = cur_dma_attr->dma_attr_sgllen;
12808 			req_len = MIN(max_sg_len,
12809 			    spx->txlt_curwin_num_dma_cookies);
12810 
12811 			/* Allocate new dma cookie array if necessary */
12812 			if (req_len == 1) {
12813 				/* Only one cookie - no need for a list */
12814 				spx->txlt_dma_cookie_list =
12815 				    &spx->txlt_dma_cookie;
12816 				spx->txlt_dma_cookie_list_len = 1;
12817 			} else {
12818 				/*
12819 				 * More than one cookie - try to allocate space.
12820 				 */
12821 				spx->txlt_dma_cookie_list = kmem_zalloc(
12822 				    sizeof (ddi_dma_cookie_t) * req_len,
12823 				    callback == NULL_FUNC ? KM_NOSLEEP :
12824 				    KM_SLEEP);
12825 				if (spx->txlt_dma_cookie_list == NULL) {
12826 					SATADBG1(SATA_DBG_DMA_SETUP,
12827 					    spx->txlt_sata_hba_inst,
12828 					    "sata_dma_buf_setup: cookie list "
12829 					    "allocation failed\n", NULL);
12830 					/*
12831 					 * We could not allocate space for
12832 					 * neccessary number of dma cookies in
12833 					 * this window, so we fail this request.
12834 					 * Next invocation would try again to
12835 					 * allocate space for cookie list.
12836 					 * Note:Packet residue was not modified.
12837 					 */
12838 					return (DDI_DMA_NORESOURCES);
12839 				} else {
12840 					spx->txlt_dma_cookie_list_len = req_len;
12841 				}
12842 			}
12843 		}
12844 		/*
12845 		 * Fetch DMA cookies into cookie list in sata_pkt_txlate.
12846 		 * First cookie was already fetched.
12847 		 */
12848 		*(&spx->txlt_dma_cookie_list[0]) = spx->txlt_dma_cookie;
12849 		cur_txfer_len =
12850 		    (uint64_t)spx->txlt_dma_cookie_list[0].dmac_size;
12851 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies = 1;
12852 		spx->txlt_curwin_processed_dma_cookies++;
12853 		for (i = 1; (i < spx->txlt_dma_cookie_list_len) &&
12854 		    (i < spx->txlt_curwin_num_dma_cookies); i++) {
12855 			ddi_dma_nextcookie(spx->txlt_buf_dma_handle,
12856 			    &spx->txlt_dma_cookie_list[i]);
12857 			cur_txfer_len +=
12858 			    (uint64_t)spx->txlt_dma_cookie_list[i].dmac_size;
12859 			spx->txlt_curwin_processed_dma_cookies++;
12860 			spx->txlt_sata_pkt->
12861 			    satapkt_cmd.satacmd_num_dma_cookies += 1;
12862 		}
12863 	} else {
12864 		SATADBG2(SATA_DBG_DMA_SETUP, spx->txlt_sata_hba_inst,
12865 		    "sata_dma_buf_setup: sliding within DMA window, "
12866 		    "cur cookie %d, total cookies %d\n",
12867 		    spx->txlt_curwin_processed_dma_cookies,
12868 		    spx->txlt_curwin_num_dma_cookies);
12869 
12870 		/*
12871 		 * Not all cookies from the current dma window were used because
12872 		 * of s/g limitation.
12873 		 * There is no need to re-size the list - it was set at
12874 		 * optimal size, or only default entry is used (s/g = 1).
12875 		 */
12876 		if (spx->txlt_dma_cookie_list == NULL) {
12877 			spx->txlt_dma_cookie_list = &spx->txlt_dma_cookie;
12878 			spx->txlt_dma_cookie_list_len = 1;
12879 		}
12880 		/*
12881 		 * Since we are processing remaining cookies in a DMA window,
12882 		 * there may be less of them than the number of entries in the
12883 		 * current dma cookie list.
12884 		 */
12885 		req_len = MIN(spx->txlt_dma_cookie_list_len,
12886 		    (spx->txlt_curwin_num_dma_cookies -
12887 		    spx->txlt_curwin_processed_dma_cookies));
12888 
12889 		/* Fetch the next batch of cookies */
12890 		for (i = 0, cur_txfer_len = 0; i < req_len; i++) {
12891 			ddi_dma_nextcookie(spx->txlt_buf_dma_handle,
12892 			    &spx->txlt_dma_cookie_list[i]);
12893 			cur_txfer_len +=
12894 			    (uint64_t)spx->txlt_dma_cookie_list[i].dmac_size;
12895 			spx->txlt_sata_pkt->
12896 			    satapkt_cmd.satacmd_num_dma_cookies++;
12897 			spx->txlt_curwin_processed_dma_cookies++;
12898 		}
12899 	}
12900 
12901 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies > 0);
12902 
12903 	/* Point sata_cmd to the cookie list */
12904 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_dma_cookie_list =
12905 	    &spx->txlt_dma_cookie_list[0];
12906 
12907 	/* Remember number of DMA cookies passed in sata packet */
12908 	spx->txlt_num_dma_cookies =
12909 	    spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies;
12910 
12911 	ASSERT(cur_txfer_len != 0);
12912 	if (cur_txfer_len <= bp->b_bcount)
12913 		spx->txlt_total_residue -= cur_txfer_len;
12914 	else {
12915 		/*
12916 		 * Temporary DMA buffer has been padded by
12917 		 * ddi_dma_mem_alloc()!
12918 		 * This requires special handling, because DMA cookies are
12919 		 * based on the temporary buffer size, not the b_bcount,
12920 		 * and we have extra bytes to transfer - but the packet
12921 		 * residue has to stay correct because we will copy only
12922 		 * the requested number of bytes.
12923 		 */
12924 		spx->txlt_total_residue -= bp->b_bcount;
12925 	}
12926 
12927 	return (DDI_SUCCESS);
12928 }
12929 
12930 /*
12931  * Common routine for releasing DMA resources
12932  */
12933 static void
12934 sata_common_free_dma_rsrcs(sata_pkt_txlate_t *spx)
12935 {
12936 	if (spx->txlt_buf_dma_handle != NULL) {
12937 		if (spx->txlt_tmp_buf != NULL)  {
12938 			/*
12939 			 * Intermediate DMA buffer was allocated.
12940 			 * Free allocated buffer and associated access handle.
12941 			 */
12942 			ddi_dma_mem_free(&spx->txlt_tmp_buf_handle);
12943 			spx->txlt_tmp_buf = NULL;
12944 		}
12945 		/*
12946 		 * Free DMA resources - cookies and handles
12947 		 */
12948 		/* ASSERT(spx->txlt_dma_cookie_list != NULL); */
12949 		if (spx->txlt_dma_cookie_list != NULL) {
12950 			if (spx->txlt_dma_cookie_list !=
12951 			    &spx->txlt_dma_cookie) {
12952 				(void) kmem_free(spx->txlt_dma_cookie_list,
12953 				    spx->txlt_dma_cookie_list_len *
12954 				    sizeof (ddi_dma_cookie_t));
12955 				spx->txlt_dma_cookie_list = NULL;
12956 			}
12957 		}
12958 		(void) ddi_dma_unbind_handle(spx->txlt_buf_dma_handle);
12959 		(void) ddi_dma_free_handle(&spx->txlt_buf_dma_handle);
12960 		spx->txlt_buf_dma_handle = NULL;
12961 	}
12962 }
12963 
12964 /*
12965  * Free DMA resources
12966  * Used by the HBA driver to release DMA resources that it does not use.
12967  *
12968  * Returns Void
12969  */
12970 void
12971 sata_free_dma_resources(sata_pkt_t *sata_pkt)
12972 {
12973 	sata_pkt_txlate_t *spx;
12974 
12975 	if (sata_pkt == NULL)
12976 		return;
12977 
12978 	spx = (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
12979 
12980 	sata_common_free_dma_rsrcs(spx);
12981 }
12982 
12983 /*
12984  * Fetch Device Identify data.
12985  * Send DEVICE IDENTIFY or IDENTIFY PACKET DEVICE (depending on a device type)
12986  * command to a device and get the device identify data.
12987  * The device_info structure has to be set to device type (for selecting proper
12988  * device identify command).
12989  *
12990  * Returns:
12991  * SATA_SUCCESS if cmd succeeded
12992  * SATA_RETRY if cmd was rejected and could be retried,
12993  * SATA_FAILURE if cmd failed and should not be retried (port error)
12994  *
12995  * Cannot be called in an interrupt context.
12996  */
12997 
12998 static int
12999 sata_fetch_device_identify_data(sata_hba_inst_t *sata_hba_inst,
13000     sata_drive_info_t *sdinfo)
13001 {
13002 	struct buf *bp;
13003 	sata_pkt_t *spkt;
13004 	sata_cmd_t *scmd;
13005 	sata_pkt_txlate_t *spx;
13006 	int rval;
13007 
13008 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
13009 	spx->txlt_sata_hba_inst = sata_hba_inst;
13010 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
13011 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
13012 	if (spkt == NULL) {
13013 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
13014 		return (SATA_RETRY); /* may retry later */
13015 	}
13016 	/* address is needed now */
13017 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13018 
13019 	/*
13020 	 * Allocate buffer for Identify Data return data
13021 	 */
13022 	bp = sata_alloc_local_buffer(spx, sizeof (sata_id_t));
13023 	if (bp == NULL) {
13024 		sata_pkt_free(spx);
13025 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
13026 		SATA_LOG_D((sata_hba_inst, CE_WARN,
13027 		    "sata_fetch_device_identify_data: "
13028 		    "cannot allocate buffer for ID"));
13029 		return (SATA_RETRY); /* may retry later */
13030 	}
13031 
13032 	/* Fill sata_pkt */
13033 	sdinfo->satadrv_state = SATA_STATE_PROBING;
13034 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13035 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
13036 	/* Synchronous mode, no callback */
13037 	spkt->satapkt_comp = NULL;
13038 	/* Timeout 30s */
13039 	spkt->satapkt_time = sata_default_pkt_time;
13040 
13041 	scmd = &spkt->satapkt_cmd;
13042 	scmd->satacmd_bp = bp;
13043 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
13044 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
13045 
13046 	/* Build Identify Device cmd in the sata_pkt */
13047 	scmd->satacmd_addr_type = 0;		/* N/A */
13048 	scmd->satacmd_sec_count_lsb = 0;	/* N/A */
13049 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
13050 	scmd->satacmd_lba_mid_lsb = 0;		/* N/A */
13051 	scmd->satacmd_lba_high_lsb = 0;		/* N/A */
13052 	scmd->satacmd_features_reg = 0;		/* N/A */
13053 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
13054 	if (sdinfo->satadrv_type & SATA_DTYPE_ATAPI) {
13055 		/* Identify Packet Device cmd */
13056 		scmd->satacmd_cmd_reg = SATAC_ID_PACKET_DEVICE;
13057 	} else {
13058 		/* Identify Device cmd - mandatory for all other devices */
13059 		scmd->satacmd_cmd_reg = SATAC_ID_DEVICE;
13060 	}
13061 
13062 	/* Send pkt to SATA HBA driver */
13063 	rval = (*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt);
13064 
13065 #ifdef SATA_INJECT_FAULTS
13066 	sata_inject_pkt_fault(spkt, &rval, sata_fault_type);
13067 #endif
13068 
13069 	if (rval == SATA_TRAN_ACCEPTED &&
13070 	    spkt->satapkt_reason == SATA_PKT_COMPLETED) {
13071 		if (spx->txlt_buf_dma_handle != NULL) {
13072 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
13073 			    DDI_DMA_SYNC_FORKERNEL);
13074 			ASSERT(rval == DDI_SUCCESS);
13075 		}
13076 		if ((((sata_id_t *)(bp->b_un.b_addr))->ai_config &
13077 		    SATA_INCOMPLETE_DATA) == SATA_INCOMPLETE_DATA) {
13078 			SATA_LOG_D((sata_hba_inst, CE_WARN,
13079 			    "SATA disk device at port %d - "
13080 			    "partial Identify Data",
13081 			    sdinfo->satadrv_addr.cport));
13082 			rval = SATA_RETRY; /* may retry later */
13083 			goto fail;
13084 		}
13085 		/* Update sata_drive_info */
13086 		bcopy(bp->b_un.b_addr, &sdinfo->satadrv_id,
13087 		    sizeof (sata_id_t));
13088 
13089 		sdinfo->satadrv_features_support = 0;
13090 		if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
13091 			/*
13092 			 * Retrieve capacity (disks only) and addressing mode
13093 			 */
13094 			sdinfo->satadrv_capacity = sata_check_capacity(sdinfo);
13095 		} else {
13096 			/*
13097 			 * For ATAPI devices one would have to issue
13098 			 * Get Capacity cmd for media capacity. Not here.
13099 			 */
13100 			sdinfo->satadrv_capacity = 0;
13101 			/*
13102 			 * Check what cdb length is supported
13103 			 */
13104 			if ((sdinfo->satadrv_id.ai_config &
13105 			    SATA_ATAPI_ID_PKT_SZ) == SATA_ATAPI_ID_PKT_16B)
13106 				sdinfo->satadrv_atapi_cdb_len = 16;
13107 			else
13108 				sdinfo->satadrv_atapi_cdb_len = 12;
13109 		}
13110 		/* Setup supported features flags */
13111 		if (sdinfo->satadrv_id.ai_cap & SATA_DMA_SUPPORT)
13112 			sdinfo->satadrv_features_support |= SATA_DEV_F_DMA;
13113 
13114 		/* Check for SATA GEN and NCQ support */
13115 		if (sdinfo->satadrv_id.ai_satacap != 0 &&
13116 		    sdinfo->satadrv_id.ai_satacap != 0xffff) {
13117 			/* SATA compliance */
13118 			if (sdinfo->satadrv_id.ai_satacap & SATA_NCQ)
13119 				sdinfo->satadrv_features_support |=
13120 				    SATA_DEV_F_NCQ;
13121 			if (sdinfo->satadrv_id.ai_satacap &
13122 			    (SATA_1_SPEED | SATA_2_SPEED)) {
13123 				if (sdinfo->satadrv_id.ai_satacap &
13124 				    SATA_2_SPEED)
13125 					sdinfo->satadrv_features_support |=
13126 					    SATA_DEV_F_SATA2;
13127 				if (sdinfo->satadrv_id.ai_satacap &
13128 				    SATA_1_SPEED)
13129 					sdinfo->satadrv_features_support |=
13130 					    SATA_DEV_F_SATA1;
13131 			} else {
13132 				sdinfo->satadrv_features_support |=
13133 				    SATA_DEV_F_SATA1;
13134 			}
13135 		}
13136 		if ((sdinfo->satadrv_id.ai_cmdset83 & SATA_RW_DMA_QUEUED_CMD) &&
13137 		    (sdinfo->satadrv_id.ai_features86 & SATA_RW_DMA_QUEUED_CMD))
13138 			sdinfo->satadrv_features_support |= SATA_DEV_F_TCQ;
13139 
13140 		sdinfo->satadrv_queue_depth = sdinfo->satadrv_id.ai_qdepth;
13141 		if ((sdinfo->satadrv_features_support & SATA_DEV_F_NCQ) ||
13142 		    (sdinfo->satadrv_features_support & SATA_DEV_F_TCQ)) {
13143 			++sdinfo->satadrv_queue_depth;
13144 			/* Adjust according to controller capabilities */
13145 			sdinfo->satadrv_max_queue_depth = MIN(
13146 			    sdinfo->satadrv_queue_depth,
13147 			    SATA_QDEPTH(sata_hba_inst));
13148 			/* Adjust according to global queue depth limit */
13149 			sdinfo->satadrv_max_queue_depth = MIN(
13150 			    sdinfo->satadrv_max_queue_depth,
13151 			    sata_current_max_qdepth);
13152 			if (sdinfo->satadrv_max_queue_depth == 0)
13153 				sdinfo->satadrv_max_queue_depth = 1;
13154 		} else
13155 			sdinfo->satadrv_max_queue_depth = 1;
13156 
13157 		rval = SATA_SUCCESS;
13158 	} else {
13159 		/*
13160 		 * Woops, no Identify Data.
13161 		 */
13162 		if (rval == SATA_TRAN_BUSY || rval == SATA_TRAN_QUEUE_FULL) {
13163 			rval = SATA_RETRY; /* may retry later */
13164 		} else if (rval == SATA_TRAN_ACCEPTED) {
13165 			if (spkt->satapkt_reason == SATA_PKT_DEV_ERROR ||
13166 			    spkt->satapkt_reason == SATA_PKT_ABORTED ||
13167 			    spkt->satapkt_reason == SATA_PKT_TIMEOUT ||
13168 			    spkt->satapkt_reason == SATA_PKT_RESET)
13169 				rval = SATA_RETRY; /* may retry later */
13170 			else
13171 				rval = SATA_FAILURE;
13172 		} else {
13173 			rval = SATA_FAILURE;
13174 		}
13175 	}
13176 fail:
13177 	/* Free allocated resources */
13178 	sata_free_local_buffer(spx);
13179 	sata_pkt_free(spx);
13180 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
13181 
13182 	return (rval);
13183 }
13184 
13185 
13186 /*
13187  * Some devices may not come-up with default DMA mode (UDMA or MWDMA).
13188  * UDMA mode is checked first, followed by MWDMA mode.
13189  * set correctly, so this function is setting it to the highest supported level.
13190  * Older SATA spec required that the device supports at least DMA 4 mode and
13191  * UDMA mode is selected.  It is not mentioned in SerialATA 2.6, so this
13192  * restriction has been removed.
13193  *
13194  * Returns SATA_SUCCESS if proper DMA mode is selected or no DMA is supported.
13195  * Returns SATA_FAILURE if proper DMA mode could not be selected.
13196  *
13197  * NOTE: This function should be called only if DMA mode is supported.
13198  */
13199 static int
13200 sata_set_dma_mode(sata_hba_inst_t *sata_hba_inst, sata_drive_info_t *sdinfo)
13201 {
13202 	sata_pkt_t *spkt;
13203 	sata_cmd_t *scmd;
13204 	sata_pkt_txlate_t *spx;
13205 	int i, mode;
13206 	uint8_t subcmd;
13207 	int rval = SATA_SUCCESS;
13208 
13209 	ASSERT(sdinfo != NULL);
13210 	ASSERT(sata_hba_inst != NULL);
13211 
13212 	if ((sdinfo->satadrv_id.ai_validinfo & SATA_VALIDINFO_88) != 0 &&
13213 	    (sdinfo->satadrv_id.ai_ultradma & SATA_UDMA_SUP_MASK) != 0) {
13214 		/* Find highest Ultra DMA mode supported */
13215 		for (mode = 6; mode >= 0; --mode) {
13216 			if (sdinfo->satadrv_id.ai_ultradma & (1 << mode))
13217 				break;
13218 		}
13219 #if 0
13220 		/* Left for historical reasons */
13221 		/*
13222 		 * Some initial version of SATA spec indicated that at least
13223 		 * UDMA mode 4 has to be supported. It is not mentioned in
13224 		 * SerialATA 2.6, so this restriction is removed.
13225 		 */
13226 		if (mode < 4)
13227 			return (SATA_FAILURE);
13228 #endif
13229 
13230 		/*
13231 		 * For disk, we're still going to set DMA mode whatever is
13232 		 * selected by default
13233 		 *
13234 		 * We saw an old maxtor sata drive will select Ultra DMA and
13235 		 * Multi-Word DMA simultaneouly by default, which is going
13236 		 * to cause DMA command timed out, so we need to select DMA
13237 		 * mode even when it's already done by default
13238 		 */
13239 		if (sdinfo->satadrv_type != SATA_DTYPE_ATADISK) {
13240 
13241 			/* Find UDMA mode currently selected */
13242 			for (i = 6; i >= 0; --i) {
13243 				if (sdinfo->satadrv_id.ai_ultradma &
13244 				    (1 << (i + 8)))
13245 					break;
13246 			}
13247 			if (i >= mode)
13248 				/* Nothing to do */
13249 				return (SATA_SUCCESS);
13250 		}
13251 
13252 		subcmd = SATAC_TRANSFER_MODE_ULTRA_DMA;
13253 
13254 	} else if ((sdinfo->satadrv_id.ai_dworddma & SATA_MDMA_SUP_MASK) != 0) {
13255 		/* Find highest MultiWord DMA mode supported */
13256 		for (mode = 2; mode >= 0; --mode) {
13257 			if (sdinfo->satadrv_id.ai_dworddma & (1 << mode))
13258 				break;
13259 		}
13260 
13261 		/*
13262 		 * For disk, We're still going to set DMA mode whatever is
13263 		 * selected by default
13264 		 *
13265 		 * We saw an old maxtor sata drive will select Ultra DMA and
13266 		 * Multi-Word DMA simultaneouly by default, which is going
13267 		 * to cause DMA command timed out, so we need to select DMA
13268 		 * mode even when it's already done by default
13269 		 */
13270 		if (sdinfo->satadrv_type != SATA_DTYPE_ATADISK) {
13271 
13272 			/* Find highest MultiWord DMA mode selected */
13273 			for (i = 2; i >= 0; --i) {
13274 				if (sdinfo->satadrv_id.ai_dworddma &
13275 				    (1 << (i + 8)))
13276 					break;
13277 			}
13278 			if (i >= mode)
13279 				/* Nothing to do */
13280 				return (SATA_SUCCESS);
13281 		}
13282 
13283 		subcmd = SATAC_TRANSFER_MODE_MULTI_WORD_DMA;
13284 	} else
13285 		return (SATA_SUCCESS);
13286 
13287 	/*
13288 	 * Set DMA mode via SET FEATURES COMMAND.
13289 	 * Prepare packet for SET FEATURES COMMAND.
13290 	 */
13291 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
13292 	spx->txlt_sata_hba_inst = sata_hba_inst;
13293 	spx->txlt_scsi_pkt = NULL;	/* No scsi pkt involved */
13294 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
13295 	if (spkt == NULL) {
13296 		SATA_LOG_D((sata_hba_inst, CE_WARN,
13297 		    "sata_set_dma_mode: could not set DMA mode %d", mode));
13298 		rval = SATA_FAILURE;
13299 		goto done;
13300 	}
13301 	/* Fill sata_pkt */
13302 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13303 	/* Timeout 30s */
13304 	spkt->satapkt_time = sata_default_pkt_time;
13305 	/* Synchronous mode, no callback, interrupts */
13306 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
13307 	spkt->satapkt_comp = NULL;
13308 	scmd = &spkt->satapkt_cmd;
13309 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
13310 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
13311 	scmd->satacmd_addr_type = 0;
13312 	scmd->satacmd_device_reg = 0;
13313 	scmd->satacmd_status_reg = 0;
13314 	scmd->satacmd_error_reg = 0;
13315 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
13316 	scmd->satacmd_features_reg = SATAC_SF_TRANSFER_MODE;
13317 	scmd->satacmd_sec_count_lsb = subcmd | mode;
13318 
13319 	/* Transfer command to HBA */
13320 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst),
13321 	    spkt) != SATA_TRAN_ACCEPTED ||
13322 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
13323 		/* Pkt execution failed */
13324 		rval = SATA_FAILURE;
13325 	}
13326 done:
13327 
13328 	/* Free allocated resources */
13329 	if (spkt != NULL)
13330 		sata_pkt_free(spx);
13331 	(void) kmem_free(spx, sizeof (sata_pkt_txlate_t));
13332 
13333 	return (rval);
13334 }
13335 
13336 
13337 /*
13338  * Set device caching mode.
13339  * One of the following operations should be specified:
13340  * SATAC_SF_ENABLE_READ_AHEAD
13341  * SATAC_SF_DISABLE_READ_AHEAD
13342  * SATAC_SF_ENABLE_WRITE_CACHE
13343  * SATAC_SF_DISABLE_WRITE_CACHE
13344  *
13345  * If operation fails, system log messgage is emitted.
13346  * Returns SATA_SUCCESS when the operation succeeds, SATA_RETRY if
13347  * command was sent but did not succeed, and SATA_FAILURE otherwise.
13348  */
13349 
13350 static int
13351 sata_set_cache_mode(sata_hba_inst_t *sata_hba_inst, sata_drive_info_t *sdinfo,
13352     int cache_op)
13353 {
13354 	sata_pkt_t *spkt;
13355 	sata_cmd_t *scmd;
13356 	sata_pkt_txlate_t *spx;
13357 	int rval = SATA_SUCCESS;
13358 	int hba_rval;
13359 	char *infop;
13360 
13361 	ASSERT(sdinfo != NULL);
13362 	ASSERT(sata_hba_inst != NULL);
13363 	ASSERT(cache_op == SATAC_SF_ENABLE_READ_AHEAD ||
13364 	    cache_op == SATAC_SF_DISABLE_READ_AHEAD ||
13365 	    cache_op == SATAC_SF_ENABLE_WRITE_CACHE ||
13366 	    cache_op == SATAC_SF_DISABLE_WRITE_CACHE);
13367 
13368 
13369 	/* Prepare packet for SET FEATURES COMMAND */
13370 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
13371 	spx->txlt_sata_hba_inst = sata_hba_inst;
13372 	spx->txlt_scsi_pkt = NULL;	/* No scsi pkt involved */
13373 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
13374 	if (spkt == NULL) {
13375 		rval = SATA_FAILURE;
13376 		goto failure;
13377 	}
13378 	/* Fill sata_pkt */
13379 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13380 	/* Timeout 30s */
13381 	spkt->satapkt_time = sata_default_pkt_time;
13382 	/* Synchronous mode, no callback, interrupts */
13383 	spkt->satapkt_op_mode =
13384 	    SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
13385 	spkt->satapkt_comp = NULL;
13386 	scmd = &spkt->satapkt_cmd;
13387 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
13388 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
13389 	scmd->satacmd_addr_type = 0;
13390 	scmd->satacmd_device_reg = 0;
13391 	scmd->satacmd_status_reg = 0;
13392 	scmd->satacmd_error_reg = 0;
13393 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
13394 	scmd->satacmd_features_reg = cache_op;
13395 
13396 	/* Transfer command to HBA */
13397 	hba_rval = (*SATA_START_FUNC(sata_hba_inst))(
13398 	    SATA_DIP(sata_hba_inst), spkt);
13399 
13400 #ifdef SATA_INJECT_FAULTS
13401 	sata_inject_pkt_fault(spkt, &rval, sata_fault_type);
13402 #endif
13403 
13404 	if ((hba_rval != SATA_TRAN_ACCEPTED) ||
13405 	    (spkt->satapkt_reason != SATA_PKT_COMPLETED)) {
13406 		/* Pkt execution failed */
13407 		switch (cache_op) {
13408 		case SATAC_SF_ENABLE_READ_AHEAD:
13409 			infop = "enabling read ahead failed";
13410 			break;
13411 		case SATAC_SF_DISABLE_READ_AHEAD:
13412 			infop = "disabling read ahead failed";
13413 			break;
13414 		case SATAC_SF_ENABLE_WRITE_CACHE:
13415 			infop = "enabling write cache failed";
13416 			break;
13417 		case SATAC_SF_DISABLE_WRITE_CACHE:
13418 			infop = "disabling write cache failed";
13419 			break;
13420 		}
13421 		SATA_LOG_D((sata_hba_inst, CE_WARN, "%s", infop));
13422 		rval = SATA_RETRY;
13423 	}
13424 failure:
13425 	/* Free allocated resources */
13426 	if (spkt != NULL)
13427 		sata_pkt_free(spx);
13428 	(void) kmem_free(spx, sizeof (sata_pkt_txlate_t));
13429 	return (rval);
13430 }
13431 
13432 /*
13433  * Set Removable Media Status Notification (enable/disable)
13434  * state == 0 , disable
13435  * state != 0 , enable
13436  *
13437  * If operation fails, system log messgage is emitted.
13438  * Returns SATA_SUCCESS when the operation succeeds, SATA_FAILURE otherwise.
13439  */
13440 
13441 static int
13442 sata_set_rmsn(sata_hba_inst_t *sata_hba_inst, sata_drive_info_t *sdinfo,
13443     int state)
13444 {
13445 	sata_pkt_t *spkt;
13446 	sata_cmd_t *scmd;
13447 	sata_pkt_txlate_t *spx;
13448 	int rval = SATA_SUCCESS;
13449 	char *infop;
13450 
13451 	ASSERT(sdinfo != NULL);
13452 	ASSERT(sata_hba_inst != NULL);
13453 
13454 	/* Prepare packet for SET FEATURES COMMAND */
13455 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
13456 	spx->txlt_sata_hba_inst = sata_hba_inst;
13457 	spx->txlt_scsi_pkt = NULL;	/* No scsi pkt involved */
13458 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
13459 	if (spkt == NULL) {
13460 		rval = SATA_FAILURE;
13461 		goto failure;
13462 	}
13463 	/* Fill sata_pkt */
13464 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13465 	/* Timeout 30s */
13466 	spkt->satapkt_time = sata_default_pkt_time;
13467 	/* Synchronous mode, no callback, interrupts */
13468 	spkt->satapkt_op_mode =
13469 	    SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
13470 	spkt->satapkt_comp = NULL;
13471 	scmd = &spkt->satapkt_cmd;
13472 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
13473 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
13474 	scmd->satacmd_addr_type = 0;
13475 	scmd->satacmd_device_reg = 0;
13476 	scmd->satacmd_status_reg = 0;
13477 	scmd->satacmd_error_reg = 0;
13478 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
13479 	if (state == 0)
13480 		scmd->satacmd_features_reg = SATAC_SF_DISABLE_RMSN;
13481 	else
13482 		scmd->satacmd_features_reg = SATAC_SF_ENABLE_RMSN;
13483 
13484 	/* Transfer command to HBA */
13485 	if (((*SATA_START_FUNC(sata_hba_inst))(
13486 	    SATA_DIP(sata_hba_inst), spkt) != SATA_TRAN_ACCEPTED) ||
13487 	    (spkt->satapkt_reason != SATA_PKT_COMPLETED)) {
13488 		/* Pkt execution failed */
13489 		if (state == 0)
13490 			infop = "disabling Removable Media Status "
13491 			    "Notification failed";
13492 		else
13493 			infop = "enabling Removable Media Status "
13494 			    "Notification failed";
13495 
13496 		SATA_LOG_D((sata_hba_inst, CE_WARN, "%s", infop));
13497 		rval = SATA_FAILURE;
13498 	}
13499 failure:
13500 	/* Free allocated resources */
13501 	if (spkt != NULL)
13502 		sata_pkt_free(spx);
13503 	(void) kmem_free(spx, sizeof (sata_pkt_txlate_t));
13504 	return (rval);
13505 }
13506 
13507 
13508 /*
13509  * Update state and copy port ss* values from passed sata_device structure.
13510  * sata_address is validated - if not valid, nothing is changed in sata_scsi
13511  * configuration struct.
13512  *
13513  * SATA_PSTATE_SHUTDOWN in port state is not reset to 0 by this function
13514  * regardless of the state in device argument.
13515  *
13516  * Port mutex should be held while calling this function.
13517  */
13518 static void
13519 sata_update_port_info(sata_hba_inst_t *sata_hba_inst,
13520     sata_device_t *sata_device)
13521 {
13522 	sata_cport_info_t *cportinfo;
13523 
13524 	if (sata_device->satadev_addr.qual == SATA_ADDR_CPORT ||
13525 	    sata_device->satadev_addr.qual == SATA_ADDR_DCPORT) {
13526 		if (SATA_NUM_CPORTS(sata_hba_inst) <=
13527 		    sata_device->satadev_addr.cport)
13528 			return;
13529 
13530 		cportinfo = SATA_CPORT_INFO(sata_hba_inst,
13531 		    sata_device->satadev_addr.cport);
13532 
13533 		ASSERT(mutex_owned(&cportinfo->cport_mutex));
13534 		cportinfo->cport_scr = sata_device->satadev_scr;
13535 
13536 		/* Preserve SATA_PSTATE_SHUTDOWN flag */
13537 		cportinfo->cport_state &= ~(SATA_PSTATE_PWRON |
13538 		    SATA_PSTATE_PWROFF | SATA_PSTATE_FAILED);
13539 		cportinfo->cport_state |=
13540 		    sata_device->satadev_state & SATA_PSTATE_VALID;
13541 	}
13542 }
13543 
13544 void
13545 sata_update_pmport_info(sata_hba_inst_t *sata_hba_inst,
13546     sata_device_t *sata_device)
13547 {
13548 	sata_pmport_info_t *pmportinfo;
13549 
13550 	if ((sata_device->satadev_addr.qual != SATA_ADDR_PMPORT &&
13551 	    sata_device->satadev_addr.qual != SATA_ADDR_DPMPORT) ||
13552 	    SATA_NUM_PMPORTS(sata_hba_inst,
13553 	    sata_device->satadev_addr.cport) <
13554 	    sata_device->satadev_addr.pmport) {
13555 		SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
13556 		    "sata_update_port_info: error address %p.",
13557 		    &sata_device->satadev_addr);
13558 		return;
13559 	}
13560 
13561 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
13562 	    sata_device->satadev_addr.cport,
13563 	    sata_device->satadev_addr.pmport);
13564 
13565 	ASSERT(mutex_owned(&pmportinfo->pmport_mutex));
13566 	pmportinfo->pmport_scr = sata_device->satadev_scr;
13567 
13568 	/* Preserve SATA_PSTATE_SHUTDOWN flag */
13569 	pmportinfo->pmport_state &=
13570 	    ~(SATA_PSTATE_PWRON | SATA_PSTATE_PWROFF | SATA_PSTATE_FAILED);
13571 	pmportinfo->pmport_state |=
13572 	    sata_device->satadev_state & SATA_PSTATE_VALID;
13573 }
13574 
13575 /*
13576  * Extract SATA port specification from an IOCTL argument.
13577  *
13578  * This function return the port the user land send us as is, unless it
13579  * cannot retrieve port spec, then -1 is returned.
13580  *
13581  * Support port multiplier.
13582  */
13583 static int32_t
13584 sata_get_port_num(sata_hba_inst_t *sata_hba_inst, struct devctl_iocdata *dcp)
13585 {
13586 	int32_t port;
13587 
13588 	/* Extract port number from nvpair in dca structure  */
13589 	if (nvlist_lookup_int32(ndi_dc_get_ap_data(dcp), "port", &port) != 0) {
13590 		SATA_LOG_D((sata_hba_inst, CE_NOTE,
13591 		    "sata_get_port_num: invalid port spec 0x%x in ioctl",
13592 		    port));
13593 		port = -1;
13594 	}
13595 
13596 	return (port);
13597 }
13598 
13599 /*
13600  * Get dev_info_t pointer to the device node pointed to by port argument.
13601  * NOTE: target argument is a value used in ioctls to identify
13602  * the AP - it is not a sata_address.
13603  * It is a combination of cport, pmport and address qualifier, encodded same
13604  * way as a scsi target number.
13605  * At this moment it carries only cport number.
13606  *
13607  * PMult hotplug is supported now.
13608  *
13609  * Returns dev_info_t pointer if target device was found, NULL otherwise.
13610  */
13611 
13612 static dev_info_t *
13613 sata_get_target_dip(dev_info_t *dip, uint8_t cport, uint8_t pmport)
13614 {
13615 	dev_info_t	*cdip = NULL;
13616 	int		target, tgt;
13617 	int 		circ;
13618 	uint8_t		qual;
13619 
13620 	sata_hba_inst_t	*sata_hba_inst;
13621 	scsi_hba_tran_t *scsi_hba_tran;
13622 
13623 	/* Get target id */
13624 	scsi_hba_tran = ddi_get_driver_private(dip);
13625 	if (scsi_hba_tran == NULL)
13626 		return (NULL);
13627 
13628 	sata_hba_inst = scsi_hba_tran->tran_hba_private;
13629 
13630 	if (sata_hba_inst == NULL)
13631 		return (NULL);
13632 
13633 	/* Identify a port-mult by cport_info.cport_dev_type */
13634 	if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) == SATA_DTYPE_PMULT)
13635 		qual = SATA_ADDR_DPMPORT;
13636 	else
13637 		qual = SATA_ADDR_DCPORT;
13638 
13639 	target = SATA_TO_SCSI_TARGET(cport, pmport, qual);
13640 
13641 	/* Retrieve target dip */
13642 	ndi_devi_enter(dip, &circ);
13643 	for (cdip = ddi_get_child(dip); cdip != NULL; ) {
13644 		dev_info_t *next = ddi_get_next_sibling(cdip);
13645 
13646 		tgt = ddi_prop_get_int(DDI_DEV_T_ANY, cdip,
13647 		    DDI_PROP_DONTPASS, "target", -1);
13648 		if (tgt == -1) {
13649 			/*
13650 			 * This is actually an error condition, but not
13651 			 * a fatal one. Just continue the search.
13652 			 */
13653 			cdip = next;
13654 			continue;
13655 		}
13656 
13657 		if (tgt == target)
13658 			break;
13659 
13660 		cdip = next;
13661 	}
13662 	ndi_devi_exit(dip, circ);
13663 
13664 	return (cdip);
13665 }
13666 
13667 /*
13668  * Get dev_info_t pointer to the device node pointed to by port argument.
13669  * NOTE: target argument is a value used in ioctls to identify
13670  * the AP - it is not a sata_address.
13671  * It is a combination of cport, pmport and address qualifier, encoded same
13672  * way as a scsi target number.
13673  *
13674  * Returns dev_info_t pointer if target device was found, NULL otherwise.
13675  */
13676 
13677 static dev_info_t *
13678 sata_get_scsi_target_dip(dev_info_t *dip, sata_address_t *saddr)
13679 {
13680 	dev_info_t	*cdip = NULL;
13681 	int		target, tgt;
13682 	int 		circ;
13683 
13684 	target = SATA_TO_SCSI_TARGET(saddr->cport, saddr->pmport, saddr->qual);
13685 
13686 	ndi_devi_enter(dip, &circ);
13687 	for (cdip = ddi_get_child(dip); cdip != NULL; ) {
13688 		dev_info_t *next = ddi_get_next_sibling(cdip);
13689 
13690 		tgt = ddi_prop_get_int(DDI_DEV_T_ANY, cdip,
13691 		    DDI_PROP_DONTPASS, "target", -1);
13692 		if (tgt == -1) {
13693 			/*
13694 			 * This is actually an error condition, but not
13695 			 * a fatal one. Just continue the search.
13696 			 */
13697 			cdip = next;
13698 			continue;
13699 		}
13700 
13701 		if (tgt == target)
13702 			break;
13703 
13704 		cdip = next;
13705 	}
13706 	ndi_devi_exit(dip, circ);
13707 
13708 	return (cdip);
13709 }
13710 
13711 /*
13712  * Process sata port disconnect request.
13713  * Normally, cfgadm sata plugin will try to offline (unconfigure) the device
13714  * before this request. Nevertheless, if a device is still configured,
13715  * we need to attempt to offline and unconfigure device.
13716  * Regardless of the unconfigure operation results the port is marked as
13717  * deactivated and no access to the attached device is possible.
13718  * If the target node remains because unconfigure operation failed, its state
13719  * will be set to DEVICE_REMOVED, preventing it to be used again when a device
13720  * is inserted/re-inserted. The event daemon will repeatedly try to unconfigure
13721  * the device and remove old target node.
13722  *
13723  * This function invokes sata_hba_inst->satahba_tran->
13724  * sata_tran_hotplug_ops->sata_tran_port_deactivate().
13725  * If successful, the device structure (if any) attached to the specified port
13726  * is removed and state of the port marked appropriately.
13727  * Failure of the port_deactivate may keep port in the physically active state,
13728  * or may fail the port.
13729  *
13730  * NOTE: Port multiplier is supported.
13731  */
13732 
13733 static int
13734 sata_ioctl_disconnect(sata_hba_inst_t *sata_hba_inst,
13735     sata_device_t *sata_device)
13736 {
13737 	sata_drive_info_t *sdinfo = NULL, *subsdinfo = NULL;
13738 	sata_cport_info_t *cportinfo = NULL;
13739 	sata_pmport_info_t *pmportinfo = NULL;
13740 	sata_pmult_info_t *pmultinfo = NULL;
13741 	sata_device_t subsdevice;
13742 	int cport, pmport, qual;
13743 	int rval = SATA_SUCCESS;
13744 	int npmport = 0;
13745 	int rv = 0;
13746 
13747 	cport = sata_device->satadev_addr.cport;
13748 	pmport = sata_device->satadev_addr.pmport;
13749 	qual = sata_device->satadev_addr.qual;
13750 
13751 	ASSERT(qual == SATA_ADDR_DCPORT || qual == SATA_ADDR_DPMPORT);
13752 	if (qual == SATA_ADDR_DCPORT)
13753 		qual = SATA_ADDR_CPORT;
13754 	else
13755 		qual = SATA_ADDR_PMPORT;
13756 
13757 	/*
13758 	 * DEVCTL_AP_DISCONNECT invokes sata_hba_inst->satahba_tran->
13759 	 * sata_tran_hotplug_ops->sata_tran_port_deactivate().
13760 	 * Do the sanity check.
13761 	 */
13762 	if (SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst) == NULL) {
13763 		/* No physical port deactivation supported. */
13764 		return (EINVAL);
13765 	}
13766 
13767 	/* Check the current state of the port */
13768 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
13769 	    (SATA_DIP(sata_hba_inst), sata_device);
13770 
13771 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
13772 
13773 	/*
13774 	 * Processing port mulitiplier
13775 	 */
13776 	if (qual == SATA_ADDR_CPORT &&
13777 	    SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) == SATA_DTYPE_PMULT) {
13778 		mutex_enter(&cportinfo->cport_mutex);
13779 
13780 		/* Check controller port status */
13781 		sata_update_port_info(sata_hba_inst, sata_device);
13782 		if (rval != SATA_SUCCESS ||
13783 		    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
13784 			/*
13785 			 * Device port status is unknown or it is in failed
13786 			 * state
13787 			 */
13788 			SATA_CPORT_STATE(sata_hba_inst, cport) =
13789 			    SATA_PSTATE_FAILED;
13790 			SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
13791 			    "sata_hba_ioctl: connect: failed to deactivate "
13792 			    "SATA port %d", cport);
13793 			mutex_exit(&cportinfo->cport_mutex);
13794 			return (EIO);
13795 		}
13796 
13797 		/* Disconnect all sub-devices. */
13798 		pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
13799 		if (pmultinfo != NULL) {
13800 
13801 			for (npmport = 0; npmport < SATA_NUM_PMPORTS(
13802 			    sata_hba_inst, cport); npmport ++) {
13803 				subsdinfo = SATA_PMPORT_DRV_INFO(
13804 				    sata_hba_inst, cport, npmport);
13805 				if (subsdinfo == NULL)
13806 					continue;
13807 
13808 				subsdevice.satadev_addr = subsdinfo->
13809 				    satadrv_addr;
13810 
13811 				mutex_exit(&cportinfo->cport_mutex);
13812 				if (sata_ioctl_disconnect(sata_hba_inst,
13813 				    &subsdevice) == SATA_SUCCESS) {
13814 					SATADBG2(SATA_DBG_PMULT, sata_hba_inst,
13815 					"[Remove] device at port %d:%d "
13816 					"successfully.", cport, npmport);
13817 				}
13818 				mutex_enter(&cportinfo->cport_mutex);
13819 			}
13820 		}
13821 
13822 		/* Disconnect the port multiplier */
13823 		cportinfo->cport_state &= ~SATA_STATE_READY;
13824 		mutex_exit(&cportinfo->cport_mutex);
13825 
13826 		sata_device->satadev_addr.qual = qual;
13827 		rval = (*SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst))
13828 		    (SATA_DIP(sata_hba_inst), sata_device);
13829 
13830 		sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
13831 		    SE_NO_HINT);
13832 
13833 		mutex_enter(&cportinfo->cport_mutex);
13834 		sata_update_port_info(sata_hba_inst, sata_device);
13835 		if (rval != SATA_SUCCESS &&
13836 		    sata_device->satadev_state & SATA_PSTATE_FAILED) {
13837 			cportinfo->cport_state = SATA_PSTATE_FAILED;
13838 			rv = EIO;
13839 		} else {
13840 			cportinfo->cport_state |= SATA_PSTATE_SHUTDOWN;
13841 		}
13842 		mutex_exit(&cportinfo->cport_mutex);
13843 
13844 		return (rv);
13845 	}
13846 
13847 	/*
13848 	 * Process non-port-multiplier device - it could be a drive connected
13849 	 * to a port multiplier port or a controller port.
13850 	 */
13851 	if (qual == SATA_ADDR_PMPORT) {
13852 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
13853 		mutex_enter(&pmportinfo->pmport_mutex);
13854 		sata_update_pmport_info(sata_hba_inst, sata_device);
13855 		if (rval != SATA_SUCCESS ||
13856 		    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
13857 			SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) =
13858 			    SATA_PSTATE_FAILED;
13859 			SATADBG2(SATA_DBG_IOCTL_IF, sata_hba_inst,
13860 			    "sata_hba_ioctl: connect: failed to deactivate "
13861 			    "SATA port %d:%d", cport, pmport);
13862 			mutex_exit(&pmportinfo->pmport_mutex);
13863 			return (EIO);
13864 		}
13865 
13866 		if (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE) {
13867 			sdinfo = pmportinfo->pmport_sata_drive;
13868 			ASSERT(sdinfo != NULL);
13869 		}
13870 
13871 		/*
13872 		 * Set port's dev_state to not ready - this will disable
13873 		 * an access to a potentially attached device.
13874 		 */
13875 		pmportinfo->pmport_state &= ~SATA_STATE_READY;
13876 
13877 		/* Remove and release sata_drive info structure. */
13878 		if (sdinfo != NULL) {
13879 			if ((sdinfo->satadrv_type &
13880 			    SATA_VALID_DEV_TYPE) != 0) {
13881 				/*
13882 				 * If a target node exists, try to offline
13883 				 * a device and remove target node.
13884 				 */
13885 				mutex_exit(&pmportinfo->pmport_mutex);
13886 				(void) sata_offline_device(sata_hba_inst,
13887 				    sata_device, sdinfo);
13888 				mutex_enter(&pmportinfo->pmport_mutex);
13889 			}
13890 
13891 			SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
13892 			pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
13893 			(void) kmem_free((void *)sdinfo,
13894 			    sizeof (sata_drive_info_t));
13895 		}
13896 		mutex_exit(&pmportinfo->pmport_mutex);
13897 
13898 	} else if (qual == SATA_ADDR_CPORT) {
13899 		mutex_enter(&cportinfo->cport_mutex);
13900 		sata_update_port_info(sata_hba_inst, sata_device);
13901 		if (rval != SATA_SUCCESS ||
13902 		    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
13903 			/*
13904 			 * Device port status is unknown or it is in failed
13905 			 * state
13906 			 */
13907 			SATA_CPORT_STATE(sata_hba_inst, cport) =
13908 			    SATA_PSTATE_FAILED;
13909 			SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
13910 			    "sata_hba_ioctl: connect: failed to deactivate "
13911 			    "SATA port %d", cport);
13912 			mutex_exit(&cportinfo->cport_mutex);
13913 			return (EIO);
13914 		}
13915 
13916 		if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT) {
13917 			pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
13918 			ASSERT(pmultinfo != NULL);
13919 		} else if (cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
13920 			sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
13921 			ASSERT(sdinfo != NULL);
13922 		}
13923 		cportinfo->cport_state &= ~SATA_STATE_READY;
13924 
13925 		if (sdinfo != NULL) {
13926 			if ((sdinfo->satadrv_type &
13927 			    SATA_VALID_DEV_TYPE) != 0) {
13928 				/*
13929 				 * If a target node exists, try to offline
13930 				 * a device and remove target node.
13931 				 */
13932 				mutex_exit(&cportinfo->cport_mutex);
13933 				(void) sata_offline_device(sata_hba_inst,
13934 				    sata_device, sdinfo);
13935 				mutex_enter(&cportinfo->cport_mutex);
13936 			}
13937 
13938 			SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
13939 			cportinfo->cport_dev_type = SATA_DTYPE_NONE;
13940 			(void) kmem_free((void *)sdinfo,
13941 			    sizeof (sata_drive_info_t));
13942 		}
13943 		mutex_exit(&cportinfo->cport_mutex);
13944 	}
13945 
13946 	/* Just ask HBA driver to deactivate port */
13947 	sata_device->satadev_addr.qual = qual;
13948 
13949 	rval = (*SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst))
13950 	    (SATA_DIP(sata_hba_inst), sata_device);
13951 
13952 	/*
13953 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
13954 	 * without the hint (to force listener to investivate the state).
13955 	 */
13956 	sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
13957 	    SE_NO_HINT);
13958 
13959 	if (qual == SATA_ADDR_PMPORT) {
13960 		mutex_enter(&pmportinfo->pmport_mutex);
13961 		sata_update_pmport_info(sata_hba_inst, sata_device);
13962 
13963 		if (rval != SATA_SUCCESS &&
13964 		    sata_device->satadev_state & SATA_PSTATE_FAILED) {
13965 			/*
13966 			 * Port deactivation failure - do not change port
13967 			 * state unless the state returned by HBA indicates a
13968 			 * port failure.
13969 			 *
13970 			 * NOTE: device structures were released, so devices
13971 			 * now are invisible! Port reset is needed to
13972 			 * re-enumerate devices.
13973 			 */
13974 			pmportinfo->pmport_state = SATA_PSTATE_FAILED;
13975 			rv = EIO;
13976 		} else {
13977 			/*
13978 			 * Deactivation succeded. From now on the sata framework
13979 			 * will not care what is happening to the device, until
13980 			 * the port is activated again.
13981 			 */
13982 			pmportinfo->pmport_state |= SATA_PSTATE_SHUTDOWN;
13983 		}
13984 		mutex_exit(&pmportinfo->pmport_mutex);
13985 	} else if (qual == SATA_ADDR_CPORT) {
13986 		mutex_enter(&cportinfo->cport_mutex);
13987 		sata_update_port_info(sata_hba_inst, sata_device);
13988 
13989 		if (rval != SATA_SUCCESS &&
13990 		    sata_device->satadev_state & SATA_PSTATE_FAILED) {
13991 			cportinfo->cport_state = SATA_PSTATE_FAILED;
13992 			rv = EIO;
13993 		} else {
13994 			cportinfo->cport_state |= SATA_PSTATE_SHUTDOWN;
13995 		}
13996 		mutex_exit(&cportinfo->cport_mutex);
13997 	}
13998 
13999 	return (rv);
14000 }
14001 
14002 
14003 
14004 /*
14005  * Process sata port connect request
14006  * The sata cfgadm pluging will invoke this operation only if port was found
14007  * in the disconnect state (failed state is also treated as the disconnected
14008  * state).
14009  * DEVCTL_AP_CONNECT would invoke  sata_hba_inst->satahba_tran->
14010  * sata_tran_hotplug_ops->sata_tran_port_activate().
14011  * If successful and a device is found attached to the port,
14012  * the initialization sequence is executed to attach a device structure to
14013  * a port structure. The state of the port and a device would be set
14014  * appropriately.
14015  * The device is not set in configured state (system-wise) by this operation.
14016  *
14017  * Note, that activating the port may generate link events,
14018  * so it is important that following processing and the
14019  * event processing does not interfere with each other!
14020  *
14021  * This operation may remove port failed state and will
14022  * try to make port active and in good standing.
14023  *
14024  * NOTE: Port multiplier is supported.
14025  */
14026 
14027 static int
14028 sata_ioctl_connect(sata_hba_inst_t *sata_hba_inst,
14029     sata_device_t *sata_device)
14030 {
14031 	sata_pmport_info_t	*pmportinfo = NULL;
14032 	uint8_t cport, pmport, qual;
14033 	int rv = 0;
14034 
14035 	cport = sata_device->satadev_addr.cport;
14036 	pmport = sata_device->satadev_addr.pmport;
14037 	qual = sata_device->satadev_addr.qual;
14038 
14039 	ASSERT(qual == SATA_ADDR_DCPORT || qual == SATA_ADDR_DPMPORT);
14040 	if (qual == SATA_ADDR_DCPORT)
14041 		qual = SATA_ADDR_CPORT;
14042 	else
14043 		qual = SATA_ADDR_PMPORT;
14044 
14045 	if (qual == SATA_ADDR_PMPORT)
14046 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
14047 
14048 	/*
14049 	 * DEVCTL_AP_CONNECT would invoke sata_hba_inst->
14050 	 * satahba_tran->sata_tran_hotplug_ops->sata_tran_port_activate().
14051 	 * Perform sanity check now.
14052 	 */
14053 	if (SATA_PORT_ACTIVATE_FUNC(sata_hba_inst) == NULL) {
14054 		/* No physical port activation supported. */
14055 		return (EINVAL);
14056 	}
14057 
14058 	/* Just ask HBA driver to activate port */
14059 	if ((*SATA_PORT_ACTIVATE_FUNC(sata_hba_inst))
14060 	    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
14061 		/*
14062 		 * Port activation failure.
14063 		 */
14064 		if (qual == SATA_ADDR_CPORT) {
14065 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14066 			    cport)->cport_mutex);
14067 			sata_update_port_info(sata_hba_inst, sata_device);
14068 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
14069 				SATA_CPORT_STATE(sata_hba_inst, cport) =
14070 				    SATA_PSTATE_FAILED;
14071 				SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
14072 				    "sata_hba_ioctl: connect: failed to "
14073 				    "activate SATA port %d", cport);
14074 			}
14075 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14076 			    cport)->cport_mutex);
14077 		} else { /* port multiplier device port */
14078 			mutex_enter(&pmportinfo->pmport_mutex);
14079 			sata_update_pmport_info(sata_hba_inst, sata_device);
14080 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
14081 				SATA_PMPORT_STATE(sata_hba_inst, cport,
14082 				    pmport) = SATA_PSTATE_FAILED;
14083 				SATADBG2(SATA_DBG_IOCTL_IF, sata_hba_inst,
14084 				    "sata_hba_ioctl: connect: failed to "
14085 				    "activate SATA port %d:%d", cport, pmport);
14086 			}
14087 			mutex_exit(&pmportinfo->pmport_mutex);
14088 		}
14089 		return (EIO);
14090 	}
14091 
14092 	/* Virgin port state - will be updated by the port re-probe. */
14093 	if (qual == SATA_ADDR_CPORT) {
14094 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14095 		    cport)->cport_mutex);
14096 		SATA_CPORT_STATE(sata_hba_inst, cport) = 0;
14097 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14098 		    cport)->cport_mutex);
14099 	} else { /* port multiplier device port */
14100 		mutex_enter(&pmportinfo->pmport_mutex);
14101 		SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) = 0;
14102 		mutex_exit(&pmportinfo->pmport_mutex);
14103 	}
14104 
14105 	/*
14106 	 * Probe the port to find its state and attached device.
14107 	 */
14108 	if (sata_reprobe_port(sata_hba_inst, sata_device,
14109 	    SATA_DEV_IDENTIFY_RETRY) == SATA_FAILURE)
14110 		rv = EIO;
14111 
14112 	/*
14113 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
14114 	 * without the hint
14115 	 */
14116 	sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
14117 	    SE_NO_HINT);
14118 
14119 	/*
14120 	 * If there is a device attached to the port, emit
14121 	 * a message.
14122 	 */
14123 	if (sata_device->satadev_type != SATA_DTYPE_NONE) {
14124 
14125 		if (qual == SATA_ADDR_CPORT) {
14126 			if (sata_device->satadev_type == SATA_DTYPE_PMULT) {
14127 				sata_log(sata_hba_inst, CE_WARN,
14128 				    "SATA port multiplier detected "
14129 				    "at port %d", cport);
14130 			} else {
14131 				sata_log(sata_hba_inst, CE_WARN,
14132 				    "SATA device detected at port %d", cport);
14133 				if (sata_device->satadev_type ==
14134 				    SATA_DTYPE_UNKNOWN) {
14135 				/*
14136 				 * A device was not successfully identified
14137 				 */
14138 				sata_log(sata_hba_inst, CE_WARN,
14139 				    "Could not identify SATA "
14140 				    "device at port %d", cport);
14141 				}
14142 			}
14143 		} else { /* port multiplier device port */
14144 			sata_log(sata_hba_inst, CE_WARN,
14145 			    "SATA device detected at port %d:%d",
14146 			    cport, pmport);
14147 			if (sata_device->satadev_type == SATA_DTYPE_UNKNOWN) {
14148 				/*
14149 				 * A device was not successfully identified
14150 				 */
14151 				sata_log(sata_hba_inst, CE_WARN,
14152 				    "Could not identify SATA "
14153 				    "device at port %d:%d", cport, pmport);
14154 			}
14155 		}
14156 	}
14157 
14158 	return (rv);
14159 }
14160 
14161 
14162 /*
14163  * Process sata device unconfigure request.
14164  * The unconfigure operation uses generic nexus operation to
14165  * offline a device. It leaves a target device node attached.
14166  * and obviously sata_drive_info attached as well, because
14167  * from the hardware point of view nothing has changed.
14168  */
14169 static int
14170 sata_ioctl_unconfigure(sata_hba_inst_t *sata_hba_inst,
14171     sata_device_t *sata_device)
14172 {
14173 	int rv = 0;
14174 	dev_info_t *tdip;
14175 
14176 	/* We are addressing attached device, not a port */
14177 	if (sata_device->satadev_addr.qual == SATA_ADDR_CPORT)
14178 		sata_device->satadev_addr.qual = SATA_ADDR_DCPORT;
14179 	else if (sata_device->satadev_addr.qual == SATA_ADDR_PMPORT)
14180 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
14181 
14182 	if ((tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
14183 	    &sata_device->satadev_addr)) != NULL) {
14184 
14185 		if (ndi_devi_offline(tdip, NDI_UNCONFIG) != NDI_SUCCESS) {
14186 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14187 			    "sata_hba_ioctl: unconfigure: "
14188 			    "failed to unconfigure device at SATA port %d:%d",
14189 			    sata_device->satadev_addr.cport,
14190 			    sata_device->satadev_addr.pmport));
14191 			rv = EIO;
14192 		}
14193 		/*
14194 		 * The target node devi_state should be marked with
14195 		 * DEVI_DEVICE_OFFLINE by ndi_devi_offline().
14196 		 * This would be the indication for cfgadm that
14197 		 * the AP node occupant state is 'unconfigured'.
14198 		 */
14199 
14200 	} else {
14201 		/*
14202 		 * This would indicate a failure on the part of cfgadm
14203 		 * to detect correct state of the node prior to this
14204 		 * call - one cannot unconfigure non-existing device.
14205 		 */
14206 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14207 		    "sata_hba_ioctl: unconfigure: "
14208 		    "attempt to unconfigure non-existing device "
14209 		    "at SATA port %d:%d",
14210 		    sata_device->satadev_addr.cport,
14211 		    sata_device->satadev_addr.pmport));
14212 		rv = ENXIO;
14213 	}
14214 	return (rv);
14215 }
14216 
14217 /*
14218  * Process sata device configure request
14219  * If port is in a failed state, operation is aborted - one has to use
14220  * an explicit connect or port activate request to try to get a port into
14221  * non-failed mode. Port reset wil also work in such situation.
14222  * If the port is in disconnected (shutdown) state, the connect operation is
14223  * attempted prior to any other action.
14224  * When port is in the active state, there is a device attached and the target
14225  * node exists, a device was most likely offlined.
14226  * If target node does not exist, a new target node is created. In both cases
14227  * an attempt is made to online (configure) the device.
14228  *
14229  * NOTE: Port multiplier is supported.
14230  */
14231 static int
14232 sata_ioctl_configure(sata_hba_inst_t *sata_hba_inst,
14233     sata_device_t *sata_device)
14234 {
14235 	int cport, pmport, qual;
14236 	int rval;
14237 	boolean_t target = TRUE;
14238 	sata_cport_info_t *cportinfo;
14239 	sata_pmport_info_t *pmportinfo = NULL;
14240 	dev_info_t *tdip;
14241 	sata_drive_info_t *sdinfo;
14242 
14243 	cport = sata_device->satadev_addr.cport;
14244 	pmport = sata_device->satadev_addr.pmport;
14245 	qual = sata_device->satadev_addr.qual;
14246 
14247 	/* Get current port state */
14248 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
14249 	    (SATA_DIP(sata_hba_inst), sata_device);
14250 
14251 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
14252 	if (qual == SATA_ADDR_DPMPORT) {
14253 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
14254 		mutex_enter(&pmportinfo->pmport_mutex);
14255 		sata_update_pmport_info(sata_hba_inst, sata_device);
14256 		if (rval != SATA_SUCCESS ||
14257 		    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
14258 			/*
14259 			 * Obviously, device on a failed port is not visible
14260 			 */
14261 			mutex_exit(&pmportinfo->pmport_mutex);
14262 			return (ENXIO);
14263 		}
14264 		mutex_exit(&pmportinfo->pmport_mutex);
14265 	} else {
14266 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14267 		    cport)->cport_mutex);
14268 		sata_update_port_info(sata_hba_inst, sata_device);
14269 		if (rval != SATA_SUCCESS ||
14270 		    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
14271 			/*
14272 			 * Obviously, device on a failed port is not visible
14273 			 */
14274 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14275 			    cport)->cport_mutex);
14276 			return (ENXIO);
14277 		}
14278 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14279 		    cport)->cport_mutex);
14280 	}
14281 
14282 	if ((sata_device->satadev_state & SATA_PSTATE_SHUTDOWN) != 0) {
14283 		/* need to activate port */
14284 		target = FALSE;
14285 
14286 		/* Sanity check */
14287 		if (SATA_PORT_ACTIVATE_FUNC(sata_hba_inst) == NULL)
14288 			return (ENXIO);
14289 
14290 		/* Just let HBA driver to activate port */
14291 		if ((*SATA_PORT_ACTIVATE_FUNC(sata_hba_inst))
14292 		    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
14293 			/*
14294 			 * Port activation failure - do not change port state
14295 			 * unless the state returned by HBA indicates a port
14296 			 * failure.
14297 			 */
14298 			if (qual == SATA_ADDR_DPMPORT) {
14299 				mutex_enter(&pmportinfo->pmport_mutex);
14300 				sata_update_pmport_info(sata_hba_inst,
14301 				    sata_device);
14302 				if (sata_device->satadev_state &
14303 				    SATA_PSTATE_FAILED)
14304 					pmportinfo->pmport_state =
14305 					    SATA_PSTATE_FAILED;
14306 				mutex_exit(&pmportinfo->pmport_mutex);
14307 			} else {
14308 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14309 				    cport)->cport_mutex);
14310 				sata_update_port_info(sata_hba_inst,
14311 				    sata_device);
14312 				if (sata_device->satadev_state &
14313 				    SATA_PSTATE_FAILED)
14314 					cportinfo->cport_state =
14315 					    SATA_PSTATE_FAILED;
14316 				mutex_exit(&SATA_CPORT_INFO(
14317 				    sata_hba_inst, cport)->cport_mutex);
14318 			}
14319 		}
14320 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14321 		    "sata_hba_ioctl: configure: "
14322 		    "failed to activate SATA port %d:%d",
14323 		    cport, pmport));
14324 		return (EIO);
14325 	}
14326 	/*
14327 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
14328 	 * without the hint.
14329 	 */
14330 	sata_gen_sysevent(sata_hba_inst,
14331 	    &sata_device->satadev_addr, SE_NO_HINT);
14332 
14333 	/* Virgin port state */
14334 	if (qual == SATA_ADDR_DPMPORT) {
14335 		mutex_enter(&pmportinfo->pmport_mutex);
14336 		pmportinfo->pmport_state = 0;
14337 		mutex_exit(&pmportinfo->pmport_mutex);
14338 	} else {
14339 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14340 		    cport)-> cport_mutex);
14341 		cportinfo->cport_state = 0;
14342 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14343 		    cport)->cport_mutex);
14344 	}
14345 	/*
14346 	 * Always reprobe port, to get current device info.
14347 	 */
14348 	if (sata_reprobe_port(sata_hba_inst, sata_device,
14349 	    SATA_DEV_IDENTIFY_RETRY) != SATA_SUCCESS)
14350 		return (EIO);
14351 
14352 	if (sata_device->satadev_type != SATA_DTYPE_NONE && target == FALSE) {
14353 		if (qual == SATA_ADDR_DPMPORT) {
14354 			/*
14355 			 * That's the transition from "inactive" port
14356 			 * to active one with device attached.
14357 			 */
14358 			sata_log(sata_hba_inst, CE_WARN,
14359 			    "SATA device detected at port %d:%d",
14360 			    cport, pmport);
14361 		} else {
14362 			/*
14363 			 * When PM is attached to the cport and cport is
14364 			 * activated, every PM device port needs to be reprobed.
14365 			 * We need to emit message for all devices detected
14366 			 * at port multiplier's device ports.
14367 			 * Add such code here.
14368 			 * For now, just inform about device attached to
14369 			 * cport.
14370 			 */
14371 			sata_log(sata_hba_inst, CE_WARN,
14372 			    "SATA device detected at port %d", cport);
14373 		}
14374 	}
14375 
14376 	/*
14377 	 * This is where real configuration operation starts.
14378 	 *
14379 	 * When PM is attached to the cport and cport is activated,
14380 	 * devices attached PM device ports may have to be configured
14381 	 * explicitly. This may change when port multiplier is supported.
14382 	 * For now, configure only disks and other valid target devices.
14383 	 */
14384 	if (!(sata_device->satadev_type & SATA_VALID_DEV_TYPE)) {
14385 		if (qual == SATA_ADDR_DCPORT) {
14386 			if (sata_device->satadev_type == SATA_DTYPE_UNKNOWN) {
14387 				/*
14388 				 * A device was not successfully identified
14389 				 */
14390 				sata_log(sata_hba_inst, CE_WARN,
14391 				    "Could not identify SATA "
14392 				    "device at port %d", cport);
14393 			}
14394 		} else { /* port multiplier device port */
14395 			if (sata_device->satadev_type == SATA_DTYPE_UNKNOWN) {
14396 				/*
14397 				 * A device was not successfully identified
14398 				 */
14399 				sata_log(sata_hba_inst, CE_WARN,
14400 				    "Could not identify SATA "
14401 				    "device at port %d:%d", cport, pmport);
14402 			}
14403 		}
14404 		return (ENXIO);		/* No device to configure */
14405 	}
14406 
14407 	/*
14408 	 * Here we may have a device in reset condition,
14409 	 * but because we are just configuring it, there is
14410 	 * no need to process the reset other than just
14411 	 * to clear device reset condition in the HBA driver.
14412 	 * Setting the flag SATA_EVNT_CLEAR_DEVICE_RESET will
14413 	 * cause a first command sent the HBA driver with the request
14414 	 * to clear device reset condition.
14415 	 */
14416 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14417 	if (qual == SATA_ADDR_DPMPORT)
14418 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
14419 	else
14420 		sata_device->satadev_addr.qual = SATA_ADDR_DCPORT;
14421 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
14422 	if (sdinfo == NULL) {
14423 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14424 		return (ENXIO);
14425 	}
14426 	if (sdinfo->satadrv_event_flags &
14427 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) {
14428 		sdinfo->satadrv_event_flags = 0;
14429 	}
14430 	sdinfo->satadrv_event_flags |= SATA_EVNT_CLEAR_DEVICE_RESET;
14431 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14432 
14433 	if ((tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
14434 	    &sata_device->satadev_addr)) != NULL) {
14435 		/*
14436 		 * Target node exists. Verify, that it belongs
14437 		 * to existing, attached device and not to
14438 		 * a removed device.
14439 		 */
14440 		if (sata_check_device_removed(tdip) == B_TRUE) {
14441 			if (qual == SATA_ADDR_DPMPORT)
14442 				sata_log(sata_hba_inst, CE_WARN,
14443 				    "SATA device at port %d cannot be "
14444 				    "configured. "
14445 				    "Application(s) accessing "
14446 				    "previously attached device "
14447 				    "have to release it before newly "
14448 				    "inserted device can be made accessible.",
14449 				    cport);
14450 			else
14451 				sata_log(sata_hba_inst, CE_WARN,
14452 				    "SATA device at port %d:%d cannot be"
14453 				    "configured. "
14454 				    "Application(s) accessing "
14455 				    "previously attached device "
14456 				    "have to release it before newly "
14457 				    "inserted device can be made accessible.",
14458 				    cport, pmport);
14459 			return (EIO);
14460 		}
14461 		/*
14462 		 * Device was not removed and re-inserted.
14463 		 * Try to online it.
14464 		 */
14465 		if (ndi_devi_online(tdip, 0) != NDI_SUCCESS) {
14466 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14467 			    "sata_hba_ioctl: configure: "
14468 			    "onlining device at SATA port "
14469 			    "%d:%d failed", cport, pmport));
14470 			return (EIO);
14471 		}
14472 
14473 		if (qual == SATA_ADDR_DPMPORT) {
14474 			mutex_enter(&pmportinfo->pmport_mutex);
14475 			pmportinfo->pmport_tgtnode_clean = B_TRUE;
14476 			mutex_exit(&pmportinfo->pmport_mutex);
14477 		} else {
14478 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14479 			    cport)->cport_mutex);
14480 			cportinfo-> cport_tgtnode_clean = B_TRUE;
14481 			mutex_exit(&SATA_CPORT_INFO(
14482 			    sata_hba_inst, cport)->cport_mutex);
14483 		}
14484 	} else {
14485 		/*
14486 		 * No target node - need to create a new target node.
14487 		 */
14488 		if (qual == SATA_ADDR_DPMPORT) {
14489 			mutex_enter(&pmportinfo->pmport_mutex);
14490 			pmportinfo->pmport_tgtnode_clean = B_TRUE;
14491 			mutex_exit(&pmportinfo->pmport_mutex);
14492 		} else {
14493 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
14494 			    cport_mutex);
14495 			cportinfo-> cport_tgtnode_clean = B_TRUE;
14496 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
14497 			    cport_mutex);
14498 		}
14499 
14500 		tdip = sata_create_target_node(SATA_DIP(sata_hba_inst),
14501 		    sata_hba_inst, &sata_device->satadev_addr);
14502 		if (tdip == NULL) {
14503 			/* Configure operation failed */
14504 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14505 			    "sata_hba_ioctl: configure: "
14506 			    "configuring SATA device at port %d:%d "
14507 			    "failed", cport, pmport));
14508 			return (EIO);
14509 		}
14510 	}
14511 	return (0);
14512 }
14513 
14514 
14515 /*
14516  * Process ioctl deactivate port request.
14517  * Arbitrarily unconfigure attached device, if any.
14518  * Even if the unconfigure fails, proceed with the
14519  * port deactivation.
14520  *
14521  * NOTE: Port Multiplier is supported now.
14522  */
14523 
14524 static int
14525 sata_ioctl_deactivate(sata_hba_inst_t *sata_hba_inst,
14526     sata_device_t *sata_device)
14527 {
14528 	int cport, pmport, qual;
14529 	int rval, rv = 0;
14530 	int npmport;
14531 	sata_cport_info_t *cportinfo;
14532 	sata_pmport_info_t *pmportinfo;
14533 	sata_pmult_info_t *pmultinfo;
14534 	dev_info_t *tdip;
14535 	sata_drive_info_t *sdinfo = NULL;
14536 	sata_device_t subsdevice;
14537 
14538 	/* Sanity check */
14539 	if (SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst) == NULL)
14540 		return (ENOTSUP);
14541 
14542 	cport = sata_device->satadev_addr.cport;
14543 	pmport = sata_device->satadev_addr.pmport;
14544 	qual = sata_device->satadev_addr.qual;
14545 
14546 	/* SCSI_TO_SATA_ADDR_QUAL() translate ap_id into a device qualifier */
14547 	ASSERT(qual == SATA_ADDR_DCPORT || qual == SATA_ADDR_DPMPORT);
14548 	if (qual == SATA_ADDR_DCPORT)
14549 		qual = SATA_ADDR_CPORT;
14550 	else
14551 		qual = SATA_ADDR_PMPORT;
14552 
14553 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
14554 	if (qual == SATA_ADDR_PMPORT)
14555 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
14556 
14557 	/*
14558 	 * Processing port multiplier
14559 	 */
14560 	if (qual == SATA_ADDR_CPORT &&
14561 	    SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) == SATA_DTYPE_PMULT) {
14562 		mutex_enter(&cportinfo->cport_mutex);
14563 
14564 		/* Deactivate all sub-deices */
14565 		pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
14566 		if (pmultinfo != NULL) {
14567 			for (npmport = 0; npmport < SATA_NUM_PMPORTS(
14568 			    sata_hba_inst, cport); npmport++) {
14569 
14570 				subsdevice.satadev_addr.cport = cport;
14571 				subsdevice.satadev_addr.pmport =
14572 				    (uint8_t)npmport;
14573 				subsdevice.satadev_addr.qual =
14574 				    SATA_ADDR_DPMPORT;
14575 
14576 				SATADBG2(SATA_DBG_PMULT, sata_hba_inst,
14577 				    "sata_hba_ioctl: deactivate: trying to "
14578 				    "deactivate SATA port %d:%d",
14579 				    cport, npmport);
14580 
14581 				mutex_exit(&cportinfo->cport_mutex);
14582 				if (sata_ioctl_deactivate(sata_hba_inst,
14583 				    &subsdevice) == SATA_SUCCESS) {
14584 					SATADBG2(SATA_DBG_PMULT, sata_hba_inst,
14585 					    "[Deactivate] device at port %d:%d "
14586 					    "successfully.", cport, npmport);
14587 				}
14588 				mutex_enter(&cportinfo->cport_mutex);
14589 			}
14590 		}
14591 
14592 		/* Deactivate the port multiplier now. */
14593 		cportinfo->cport_state &= ~SATA_STATE_READY;
14594 		mutex_exit(&cportinfo->cport_mutex);
14595 
14596 		sata_device->satadev_addr.qual = qual;
14597 		rval = (*SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst))
14598 		    (SATA_DIP(sata_hba_inst), sata_device);
14599 
14600 		sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
14601 		    SE_NO_HINT);
14602 
14603 		mutex_enter(&cportinfo->cport_mutex);
14604 		sata_update_port_info(sata_hba_inst, sata_device);
14605 		if (rval != SATA_SUCCESS) {
14606 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
14607 				cportinfo->cport_state = SATA_PSTATE_FAILED;
14608 			}
14609 			rv = EIO;
14610 		} else {
14611 			cportinfo->cport_state |= SATA_PSTATE_SHUTDOWN;
14612 		}
14613 		mutex_exit(&cportinfo->cport_mutex);
14614 
14615 		return (rv);
14616 	}
14617 
14618 	/*
14619 	 * Process non-port-multiplier device - it could be a drive connected
14620 	 * to a port multiplier port or a controller port.
14621 	 */
14622 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14623 	if (qual == SATA_ADDR_CPORT) {
14624 		sata_device->satadev_addr.qual = SATA_ADDR_DCPORT;
14625 		if (cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
14626 			/* deal only with valid devices */
14627 			if ((cportinfo->cport_dev_type &
14628 			    SATA_VALID_DEV_TYPE) != 0)
14629 				sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
14630 		}
14631 		cportinfo->cport_state &= ~SATA_STATE_READY;
14632 	} else {
14633 		/* Port multiplier device port */
14634 		mutex_enter(&pmportinfo->pmport_mutex);
14635 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
14636 		if (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE &&
14637 		    (pmportinfo->pmport_dev_type & SATA_VALID_DEV_TYPE) != 0)
14638 			sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
14639 		pmportinfo->pmport_state &= ~SATA_STATE_READY;
14640 		mutex_exit(&pmportinfo->pmport_mutex);
14641 	}
14642 
14643 	if (sdinfo != NULL) {
14644 		/*
14645 		 * If a target node exists, try to offline a device and
14646 		 * to remove a target node.
14647 		 */
14648 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
14649 		    cport_mutex);
14650 		tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
14651 		    &sata_device->satadev_addr);
14652 		if (tdip != NULL) {
14653 			/* target node exist */
14654 			SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
14655 			    "sata_hba_ioctl: port deactivate: "
14656 			    "target node exists.", NULL);
14657 
14658 			if (ndi_devi_offline(tdip, NDI_DEVI_REMOVE) !=
14659 			    NDI_SUCCESS) {
14660 				SATA_LOG_D((sata_hba_inst, CE_WARN,
14661 				    "sata_hba_ioctl: port deactivate: "
14662 				    "failed to unconfigure device at port "
14663 				    "%d:%d before deactivating the port",
14664 				    cport, pmport));
14665 				/*
14666 				 * Set DEVICE REMOVED state in the target
14667 				 * node. It will prevent an access to
14668 				 * the device even when a new device is
14669 				 * attached, until the old target node is
14670 				 * released, removed and recreated for a new
14671 				 * device.
14672 				 */
14673 				sata_set_device_removed(tdip);
14674 
14675 				/*
14676 				 * Instruct the event daemon to try the
14677 				 * target node cleanup later.
14678 				 */
14679 				sata_set_target_node_cleanup(sata_hba_inst,
14680 				    &sata_device->satadev_addr);
14681 			}
14682 		}
14683 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
14684 		    cport_mutex);
14685 		/*
14686 		 * In any case, remove and release sata_drive_info
14687 		 * structure.
14688 		 */
14689 		if (qual == SATA_ADDR_CPORT) {
14690 			SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
14691 			cportinfo->cport_dev_type = SATA_DTYPE_NONE;
14692 		} else { /* port multiplier device port */
14693 			mutex_enter(&pmportinfo->pmport_mutex);
14694 			SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
14695 			pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
14696 			mutex_exit(&pmportinfo->pmport_mutex);
14697 		}
14698 		(void) kmem_free((void *)sdinfo, sizeof (sata_drive_info_t));
14699 	}
14700 
14701 	if (qual == SATA_ADDR_CPORT) {
14702 		cportinfo->cport_state &= ~(SATA_STATE_PROBED |
14703 		    SATA_STATE_PROBING);
14704 	} else if (qual == SATA_ADDR_PMPORT) {
14705 		mutex_enter(&pmportinfo->pmport_mutex);
14706 		pmportinfo->pmport_state &= ~(SATA_STATE_PROBED |
14707 		    SATA_STATE_PROBING);
14708 		mutex_exit(&pmportinfo->pmport_mutex);
14709 	}
14710 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14711 
14712 	/* Just let HBA driver to deactivate port */
14713 	sata_device->satadev_addr.qual = qual;
14714 	rval = (*SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst))
14715 	    (SATA_DIP(sata_hba_inst), sata_device);
14716 
14717 	/*
14718 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
14719 	 * without the hint
14720 	 */
14721 	sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
14722 	    SE_NO_HINT);
14723 
14724 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14725 	sata_update_port_info(sata_hba_inst, sata_device);
14726 	if (qual == SATA_ADDR_CPORT) {
14727 		if (rval != SATA_SUCCESS) {
14728 			/*
14729 			 * Port deactivation failure - do not change port state
14730 			 * unless the state returned by HBA indicates a port
14731 			 * failure.
14732 			 */
14733 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
14734 				SATA_CPORT_STATE(sata_hba_inst, cport) =
14735 				    SATA_PSTATE_FAILED;
14736 			}
14737 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14738 			    "sata_hba_ioctl: port deactivate: "
14739 			    "cannot deactivate SATA port %d", cport));
14740 			rv = EIO;
14741 		} else {
14742 			cportinfo->cport_state |= SATA_PSTATE_SHUTDOWN;
14743 		}
14744 	} else {
14745 		mutex_enter(&pmportinfo->pmport_mutex);
14746 		if (rval != SATA_SUCCESS) {
14747 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
14748 				SATA_PMPORT_STATE(sata_hba_inst, cport,
14749 				    pmport) = SATA_PSTATE_FAILED;
14750 			}
14751 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14752 			    "sata_hba_ioctl: port deactivate: "
14753 			    "cannot deactivate SATA port %d:%d",
14754 			    cport, pmport));
14755 			rv = EIO;
14756 		} else {
14757 			pmportinfo->pmport_state |= SATA_PSTATE_SHUTDOWN;
14758 		}
14759 		mutex_exit(&pmportinfo->pmport_mutex);
14760 	}
14761 
14762 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14763 
14764 	return (rv);
14765 }
14766 
14767 /*
14768  * Process ioctl port activate request.
14769  *
14770  * NOTE: Port multiplier is supported now.
14771  */
14772 static int
14773 sata_ioctl_activate(sata_hba_inst_t *sata_hba_inst,
14774     sata_device_t *sata_device)
14775 {
14776 	int cport, pmport, qual;
14777 	sata_cport_info_t *cportinfo;
14778 	sata_pmport_info_t *pmportinfo = NULL;
14779 	boolean_t dev_existed = TRUE;
14780 
14781 	/* Sanity check */
14782 	if (SATA_PORT_ACTIVATE_FUNC(sata_hba_inst) == NULL)
14783 		return (ENOTSUP);
14784 
14785 	cport = sata_device->satadev_addr.cport;
14786 	pmport = sata_device->satadev_addr.pmport;
14787 	qual = sata_device->satadev_addr.qual;
14788 
14789 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
14790 
14791 	/*
14792 	 * The qual translate from ap_id (by SCSI_TO_SATA_ADDR_QUAL())
14793 	 * is a device. But what we are dealing with is port/pmport.
14794 	 */
14795 	ASSERT(qual == SATA_ADDR_DCPORT || qual == SATA_ADDR_DPMPORT);
14796 	if (qual == SATA_ADDR_DCPORT)
14797 		sata_device->satadev_addr.qual = qual = SATA_ADDR_CPORT;
14798 	else
14799 		sata_device->satadev_addr.qual = qual = SATA_ADDR_PMPORT;
14800 
14801 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14802 	if (qual == SATA_ADDR_PMPORT) {
14803 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
14804 		if (pmportinfo->pmport_state & SATA_PSTATE_SHUTDOWN ||
14805 		    pmportinfo->pmport_dev_type == SATA_DTYPE_NONE)
14806 			dev_existed = FALSE;
14807 	} else { /* cport */
14808 		if (cportinfo->cport_state & SATA_PSTATE_SHUTDOWN ||
14809 		    cportinfo->cport_dev_type == SATA_DTYPE_NONE)
14810 			dev_existed = FALSE;
14811 	}
14812 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14813 
14814 	/* Just let HBA driver to activate port, if necessary */
14815 	if ((*SATA_PORT_ACTIVATE_FUNC(sata_hba_inst))
14816 	    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
14817 		/*
14818 		 * Port activation failure - do not change port state unless
14819 		 * the state returned by HBA indicates a port failure.
14820 		 */
14821 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14822 		    cport)->cport_mutex);
14823 		sata_update_port_info(sata_hba_inst, sata_device);
14824 		if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
14825 			if (qual == SATA_ADDR_PMPORT) {
14826 				mutex_enter(&pmportinfo->pmport_mutex);
14827 				pmportinfo->pmport_state = SATA_PSTATE_FAILED;
14828 				mutex_exit(&pmportinfo->pmport_mutex);
14829 			} else
14830 				cportinfo->cport_state = SATA_PSTATE_FAILED;
14831 
14832 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14833 			    cport)->cport_mutex);
14834 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14835 			    "sata_hba_ioctl: port activate: cannot activate "
14836 			    "SATA port %d:%d", cport, pmport));
14837 			return (EIO);
14838 		}
14839 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14840 	}
14841 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14842 	if (qual == SATA_ADDR_PMPORT) {
14843 		mutex_enter(&pmportinfo->pmport_mutex);
14844 		pmportinfo->pmport_state &= ~SATA_PSTATE_SHUTDOWN;
14845 		mutex_exit(&pmportinfo->pmport_mutex);
14846 	} else
14847 		cportinfo->cport_state &= ~SATA_PSTATE_SHUTDOWN;
14848 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14849 
14850 	/*
14851 	 * Re-probe port to find its current state and possibly attached device.
14852 	 * Port re-probing may change the cportinfo device type if device is
14853 	 * found attached.
14854 	 * If port probing failed, the device type would be set to
14855 	 * SATA_DTYPE_NONE.
14856 	 */
14857 	(void) sata_reprobe_port(sata_hba_inst, sata_device,
14858 	    SATA_DEV_IDENTIFY_RETRY);
14859 
14860 	/*
14861 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
14862 	 * without the hint.
14863 	 */
14864 	sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
14865 	    SE_NO_HINT);
14866 
14867 	if (dev_existed == FALSE) {
14868 		if (qual == SATA_ADDR_PMPORT &&
14869 		    pmportinfo->pmport_dev_type != SATA_DTYPE_NONE) {
14870 			/*
14871 			 * That's the transition from the "inactive" port state
14872 			 * or the active port without a device attached to the
14873 			 * active port state with a device attached.
14874 			 */
14875 			sata_log(sata_hba_inst, CE_WARN,
14876 			    "SATA device detected at port %d:%d",
14877 			    cport, pmport);
14878 		} else if (qual == SATA_ADDR_CPORT &&
14879 		    cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
14880 			/*
14881 			 * That's the transition from the "inactive" port state
14882 			 * or the active port without a device attached to the
14883 			 * active port state with a device attached.
14884 			 */
14885 			if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
14886 				sata_log(sata_hba_inst, CE_WARN,
14887 				    "SATA device detected at port %d", cport);
14888 			} else {
14889 				sata_log(sata_hba_inst, CE_WARN,
14890 				    "SATA port multiplier detected at port %d",
14891 				    cport);
14892 			}
14893 		}
14894 	}
14895 	return (0);
14896 }
14897 
14898 
14899 
14900 /*
14901  * Process ioctl reset port request.
14902  *
14903  * NOTE: Port-Multiplier is supported.
14904  */
14905 static int
14906 sata_ioctl_reset_port(sata_hba_inst_t *sata_hba_inst,
14907     sata_device_t *sata_device)
14908 {
14909 	int cport, pmport, qual;
14910 	int rv = 0;
14911 
14912 	cport = sata_device->satadev_addr.cport;
14913 	pmport = sata_device->satadev_addr.pmport;
14914 	qual = sata_device->satadev_addr.qual;
14915 
14916 	/*
14917 	 * The qual translate from ap_id (by SCSI_TO_SATA_ADDR_QUAL())
14918 	 * is a device. But what we are dealing with is port/pmport.
14919 	 */
14920 	if (qual == SATA_ADDR_DCPORT)
14921 		sata_device->satadev_addr.qual = qual = SATA_ADDR_CPORT;
14922 	else
14923 		sata_device->satadev_addr.qual = qual = SATA_ADDR_PMPORT;
14924 	ASSERT(qual == SATA_ADDR_CPORT || qual == SATA_ADDR_PMPORT);
14925 
14926 	/* Sanity check */
14927 	if (SATA_RESET_DPORT_FUNC(sata_hba_inst) == NULL) {
14928 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14929 		    "sata_hba_ioctl: sata_hba_tran missing required "
14930 		    "function sata_tran_reset_dport"));
14931 		return (ENOTSUP);
14932 	}
14933 
14934 	/* Ask HBA to reset port */
14935 	if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst),
14936 	    sata_device) != SATA_SUCCESS) {
14937 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14938 		    "sata_hba_ioctl: reset port: failed %d:%d",
14939 		    cport, pmport));
14940 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
14941 		    cport_mutex);
14942 		sata_update_port_info(sata_hba_inst, sata_device);
14943 		if (qual == SATA_ADDR_CPORT)
14944 			SATA_CPORT_STATE(sata_hba_inst, cport) =
14945 			    SATA_PSTATE_FAILED;
14946 		else {
14947 			mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst, cport,
14948 			    pmport));
14949 			SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) =
14950 			    SATA_PSTATE_FAILED;
14951 			mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport,
14952 			    pmport));
14953 		}
14954 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
14955 		    cport_mutex);
14956 		rv = EIO;
14957 	}
14958 	/*
14959 	 * Beacuse the port was reset, it should be probed and
14960 	 * attached device reinitialized. At this point the
14961 	 * port state is unknown - it's state is HBA-specific.
14962 	 * Re-probe port to get its state.
14963 	 */
14964 	if (sata_reprobe_port(sata_hba_inst, sata_device,
14965 	    SATA_DEV_IDENTIFY_RETRY) != SATA_SUCCESS) {
14966 		rv = EIO;
14967 	}
14968 	return (rv);
14969 }
14970 
14971 /*
14972  * Process ioctl reset device request.
14973  *
14974  * NOTE: Port multiplier is supported.
14975  */
14976 static int
14977 sata_ioctl_reset_device(sata_hba_inst_t *sata_hba_inst,
14978     sata_device_t *sata_device)
14979 {
14980 	sata_drive_info_t *sdinfo = NULL;
14981 	sata_pmult_info_t *pmultinfo = NULL;
14982 	int cport, pmport;
14983 	int rv = 0;
14984 
14985 	/* Sanity check */
14986 	if (SATA_RESET_DPORT_FUNC(sata_hba_inst) == NULL) {
14987 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14988 		    "sata_hba_ioctl: sata_hba_tran missing required "
14989 		    "function sata_tran_reset_dport"));
14990 		return (ENOTSUP);
14991 	}
14992 
14993 	cport = sata_device->satadev_addr.cport;
14994 	pmport = sata_device->satadev_addr.pmport;
14995 
14996 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14997 	if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT) {
14998 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) ==
14999 		    SATA_DTYPE_PMULT)
15000 			pmultinfo = SATA_CPORT_INFO(sata_hba_inst, cport)->
15001 			    cport_devp.cport_sata_pmult;
15002 		else
15003 			sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
15004 			    sata_device->satadev_addr.cport);
15005 	} else { /* port multiplier */
15006 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
15007 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst,
15008 		    sata_device->satadev_addr.cport,
15009 		    sata_device->satadev_addr.pmport);
15010 	}
15011 	if (sdinfo == NULL && pmultinfo == NULL) {
15012 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
15013 		return (EINVAL);
15014 	}
15015 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
15016 
15017 	/* Ask HBA to reset device */
15018 	if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))
15019 	    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
15020 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15021 		    "sata_hba_ioctl: reset device: failed at port %d:%d",
15022 		    cport, pmport));
15023 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
15024 		    cport_mutex);
15025 		sata_update_port_info(sata_hba_inst, sata_device);
15026 		/*
15027 		 * Device info structure remains attached. Another device reset
15028 		 * or port disconnect/connect and re-probing is
15029 		 * needed to change it's state
15030 		 */
15031 		if (sdinfo != NULL) {
15032 			sdinfo->satadrv_state &= ~SATA_STATE_READY;
15033 			sdinfo->satadrv_state |= SATA_DSTATE_FAILED;
15034 		} else if (pmultinfo != NULL) {
15035 			pmultinfo->pmult_state &= ~SATA_STATE_READY;
15036 			pmultinfo->pmult_state |= SATA_DSTATE_FAILED;
15037 		}
15038 
15039 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
15040 		rv = EIO;
15041 	}
15042 	/*
15043 	 * If attached device was a port multiplier, some extra processing
15044 	 * may be needed to bring it back. SATA specification requies a
15045 	 * mandatory software reset on host port to reliably enumerate a port
15046 	 * multiplier, the HBA driver should handle that after reset
15047 	 * operation.
15048 	 */
15049 	return (rv);
15050 }
15051 
15052 
15053 /*
15054  * Process ioctl reset all request.
15055  */
15056 static int
15057 sata_ioctl_reset_all(sata_hba_inst_t *sata_hba_inst)
15058 {
15059 	sata_device_t sata_device;
15060 	int rv = 0;
15061 	int tcport;
15062 	int tpmport = 0;
15063 
15064 	sata_device.satadev_rev = SATA_DEVICE_REV;
15065 
15066 	/*
15067 	 * There is no protection here for configured devices.
15068 	 */
15069 	/* Sanity check */
15070 	if (SATA_RESET_DPORT_FUNC(sata_hba_inst) == NULL) {
15071 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15072 		    "sata_hba_ioctl: sata_hba_tran missing required "
15073 		    "function sata_tran_reset_dport"));
15074 		return (ENOTSUP);
15075 	}
15076 
15077 	/*
15078 	 * Need to lock all ports, not just one.
15079 	 * If any port is locked by event processing, fail the whole operation.
15080 	 * One port is already locked, but for simplicity lock it again.
15081 	 */
15082 	for (tcport = 0; tcport < SATA_NUM_CPORTS(sata_hba_inst); tcport++) {
15083 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
15084 		    cport_mutex);
15085 		if (((SATA_CPORT_INFO(sata_hba_inst, tcport)->
15086 		    cport_event_flags) & SATA_EVNT_LOCK_PORT_BUSY) != 0) {
15087 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
15088 			    cport_mutex);
15089 			rv = EBUSY;
15090 			break;
15091 		} else {
15092 			/*
15093 			 * It is enough to lock cport in command-based
15094 			 * switching mode.
15095 			 */
15096 			SATA_CPORT_INFO(sata_hba_inst, tcport)->
15097 			    cport_event_flags |= SATA_APCTL_LOCK_PORT_BUSY;
15098 		}
15099 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
15100 		    cport_mutex);
15101 	}
15102 
15103 	if (rv == 0) {
15104 		/*
15105 		 * All cports were successfully locked.
15106 		 * Reset main SATA controller.
15107 		 * Set the device address to port 0, to have a valid device
15108 		 * address.
15109 		 */
15110 		sata_device.satadev_addr.qual = SATA_ADDR_CNTRL;
15111 		sata_device.satadev_addr.cport = 0;
15112 		sata_device.satadev_addr.pmport = 0;
15113 
15114 		if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))
15115 		    (SATA_DIP(sata_hba_inst), &sata_device) != SATA_SUCCESS) {
15116 			SATA_LOG_D((sata_hba_inst, CE_WARN,
15117 			    "sata_hba_ioctl: reset controller failed"));
15118 			return (EIO);
15119 		}
15120 		/*
15121 		 * Because ports were reset, port states are unknown.
15122 		 * They should be re-probed to get their state and
15123 		 * attached devices should be reinitialized.
15124 		 */
15125 		for (tcport = 0; tcport < SATA_NUM_CPORTS(sata_hba_inst);
15126 		    tcport++) {
15127 			sata_device.satadev_addr.cport = tcport;
15128 			sata_device.satadev_addr.pmport = tpmport;
15129 			sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
15130 
15131 			/*
15132 			 * The sata_reprobe_port() will mark a
15133 			 * SATA_EVNT_DEVICE_RESET event on the port
15134 			 * multiplier, all its sub-ports will be probed by
15135 			 * sata daemon afterwards.
15136 			 */
15137 			if (sata_reprobe_port(sata_hba_inst, &sata_device,
15138 			    SATA_DEV_IDENTIFY_RETRY) != SATA_SUCCESS)
15139 				rv = EIO;
15140 		}
15141 	}
15142 	/*
15143 	 * Unlock all ports
15144 	 */
15145 	for (tcport = 0; tcport < SATA_NUM_CPORTS(sata_hba_inst); tcport++) {
15146 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
15147 		    cport_mutex);
15148 		SATA_CPORT_INFO(sata_hba_inst, tcport)->
15149 		    cport_event_flags &= ~SATA_APCTL_LOCK_PORT_BUSY;
15150 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
15151 		    cport_mutex);
15152 	}
15153 
15154 	/*
15155 	 * This operation returns EFAULT if either reset
15156 	 * controller failed or a re-probing of any port failed.
15157 	 */
15158 	return (rv);
15159 }
15160 
15161 
15162 /*
15163  * Process ioctl port self test request.
15164  *
15165  * NOTE: Port multiplier code is not completed nor tested.
15166  */
15167 static int
15168 sata_ioctl_port_self_test(sata_hba_inst_t *sata_hba_inst,
15169     sata_device_t *sata_device)
15170 {
15171 	int cport, pmport, qual;
15172 	int rv = 0;
15173 
15174 	/* Sanity check */
15175 	if (SATA_SELFTEST_FUNC(sata_hba_inst) == NULL)
15176 		return (ENOTSUP);
15177 
15178 	cport = sata_device->satadev_addr.cport;
15179 	pmport = sata_device->satadev_addr.pmport;
15180 	qual = sata_device->satadev_addr.qual;
15181 
15182 	/*
15183 	 * There is no protection here for a configured
15184 	 * device attached to this port.
15185 	 */
15186 
15187 	if ((*SATA_SELFTEST_FUNC(sata_hba_inst))
15188 	    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
15189 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15190 		    "sata_hba_ioctl: port selftest: "
15191 		    "failed port %d:%d", cport, pmport));
15192 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
15193 		    cport_mutex);
15194 		sata_update_port_info(sata_hba_inst, sata_device);
15195 		if (qual == SATA_ADDR_CPORT)
15196 			SATA_CPORT_STATE(sata_hba_inst, cport) =
15197 			    SATA_PSTATE_FAILED;
15198 		else { /* port multiplier device port */
15199 			mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst,
15200 			    cport, pmport));
15201 			SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) =
15202 			    SATA_PSTATE_FAILED;
15203 			mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst,
15204 			    cport, pmport));
15205 		}
15206 
15207 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
15208 		    cport_mutex);
15209 		return (EIO);
15210 	}
15211 	/*
15212 	 * Beacuse the port was reset in the course of testing, it should be
15213 	 * re-probed and attached device state should be restored. At this
15214 	 * point the port state is unknown - it's state is HBA-specific.
15215 	 * Force port re-probing to get it into a known state.
15216 	 */
15217 	if (sata_reprobe_port(sata_hba_inst, sata_device,
15218 	    SATA_DEV_IDENTIFY_RETRY) != SATA_SUCCESS)
15219 		rv = EIO;
15220 	return (rv);
15221 }
15222 
15223 
15224 /*
15225  * sata_cfgadm_state:
15226  * Use the sata port state and state of the target node to figure out
15227  * the cfgadm_state.
15228  *
15229  * The port argument is a value with encoded cport,
15230  * pmport and address qualifier, in the same manner as a scsi target number.
15231  * SCSI_TO_SATA_CPORT macro extracts cport number,
15232  * SCSI_TO_SATA_PMPORT extracts pmport number and
15233  * SCSI_TO_SATA_ADDR_QUAL extracts port mulitplier qualifier flag.
15234  *
15235  * Port multiplier is supported.
15236  */
15237 
15238 static void
15239 sata_cfgadm_state(sata_hba_inst_t *sata_hba_inst, int32_t port,
15240     devctl_ap_state_t *ap_state)
15241 {
15242 	uint8_t		cport, pmport, qual;
15243 	uint32_t	port_state, pmult_state;
15244 	uint32_t	dev_type;
15245 	sata_drive_info_t *sdinfo;
15246 
15247 	cport = SCSI_TO_SATA_CPORT(port);
15248 	pmport = SCSI_TO_SATA_PMPORT(port);
15249 	qual = SCSI_TO_SATA_ADDR_QUAL(port);
15250 
15251 	/* Check cport state */
15252 	port_state = SATA_CPORT_STATE(sata_hba_inst, cport);
15253 	if (port_state & SATA_PSTATE_SHUTDOWN ||
15254 	    port_state & SATA_PSTATE_FAILED) {
15255 		ap_state->ap_rstate = AP_RSTATE_DISCONNECTED;
15256 		ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
15257 		if (port_state & SATA_PSTATE_FAILED)
15258 			ap_state->ap_condition = AP_COND_FAILED;
15259 		else
15260 			ap_state->ap_condition = AP_COND_UNKNOWN;
15261 
15262 		return;
15263 	}
15264 
15265 	/* cport state is okay. Now check pmport state */
15266 	if (qual == SATA_ADDR_DPMPORT || qual == SATA_ADDR_PMPORT) {
15267 		/* Sanity check */
15268 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) !=
15269 		    SATA_DTYPE_PMULT || SATA_PMPORT_INFO(sata_hba_inst,
15270 		    cport, pmport) == NULL)
15271 			return;
15272 		port_state = SATA_PMPORT_STATE(sata_hba_inst, cport, pmport);
15273 		if (port_state & SATA_PSTATE_SHUTDOWN ||
15274 		    port_state & SATA_PSTATE_FAILED) {
15275 			ap_state->ap_rstate = AP_RSTATE_DISCONNECTED;
15276 			ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
15277 			if (port_state & SATA_PSTATE_FAILED)
15278 				ap_state->ap_condition = AP_COND_FAILED;
15279 			else
15280 				ap_state->ap_condition = AP_COND_UNKNOWN;
15281 
15282 			return;
15283 		}
15284 	}
15285 
15286 	/* Port is enabled and ready */
15287 	if (qual == SATA_ADDR_DCPORT || qual == SATA_ADDR_CPORT)
15288 		dev_type = SATA_CPORT_DEV_TYPE(sata_hba_inst, cport);
15289 	else
15290 		dev_type = SATA_PMPORT_DEV_TYPE(sata_hba_inst, cport, pmport);
15291 
15292 	switch (dev_type) {
15293 	case SATA_DTYPE_NONE:
15294 	{
15295 		ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
15296 		ap_state->ap_condition = AP_COND_OK;
15297 		/* No device attached */
15298 		ap_state->ap_rstate = AP_RSTATE_EMPTY;
15299 		break;
15300 	}
15301 	case SATA_DTYPE_PMULT:
15302 	{
15303 		/* Need to check port multiplier state */
15304 		ASSERT(qual == SATA_ADDR_DCPORT);
15305 		pmult_state = SATA_PMULT_INFO(sata_hba_inst, cport)->
15306 		    pmult_state;
15307 		if (pmult_state & (SATA_PSTATE_SHUTDOWN|SATA_PSTATE_FAILED)) {
15308 			ap_state->ap_rstate = AP_RSTATE_DISCONNECTED;
15309 			ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
15310 			if (pmult_state & SATA_PSTATE_FAILED)
15311 				ap_state->ap_condition = AP_COND_FAILED;
15312 			else
15313 				ap_state->ap_condition = AP_COND_UNKNOWN;
15314 
15315 			return;
15316 		}
15317 
15318 		/* Port multiplier is not configurable */
15319 		ap_state->ap_ostate = AP_OSTATE_CONFIGURED;
15320 		ap_state->ap_rstate = AP_RSTATE_CONNECTED;
15321 		ap_state->ap_condition = AP_COND_OK;
15322 		break;
15323 	}
15324 
15325 	case SATA_DTYPE_ATADISK:
15326 	case SATA_DTYPE_ATAPICD:
15327 	case SATA_DTYPE_ATAPITAPE:
15328 	case SATA_DTYPE_ATAPIDISK:
15329 	{
15330 		dev_info_t *tdip = NULL;
15331 		dev_info_t *dip = NULL;
15332 		int circ;
15333 
15334 		dip = SATA_DIP(sata_hba_inst);
15335 		tdip = sata_get_target_dip(dip, cport, pmport);
15336 		ap_state->ap_rstate = AP_RSTATE_CONNECTED;
15337 		if (tdip != NULL) {
15338 			ndi_devi_enter(dip, &circ);
15339 			mutex_enter(&(DEVI(tdip)->devi_lock));
15340 			if (DEVI_IS_DEVICE_REMOVED(tdip)) {
15341 				/*
15342 				 * There could be the case where previously
15343 				 * configured and opened device was removed
15344 				 * and unknown device was plugged.
15345 				 * In such case we want to show a device, and
15346 				 * its configured or unconfigured state but
15347 				 * indicate unusable condition untill the
15348 				 * old target node is released and removed.
15349 				 */
15350 				ap_state->ap_condition = AP_COND_UNUSABLE;
15351 			} else {
15352 				mutex_enter(&SATA_CPORT_MUTEX(sata_hba_inst,
15353 				    cport));
15354 				sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
15355 				    cport);
15356 				if (sdinfo != NULL) {
15357 					if ((sdinfo->satadrv_state &
15358 					    SATA_DSTATE_FAILED) != 0)
15359 						ap_state->ap_condition =
15360 						    AP_COND_FAILED;
15361 					else
15362 						ap_state->ap_condition =
15363 						    AP_COND_OK;
15364 				} else {
15365 					ap_state->ap_condition =
15366 					    AP_COND_UNKNOWN;
15367 				}
15368 				mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst,
15369 				    cport));
15370 			}
15371 			if ((DEVI_IS_DEVICE_OFFLINE(tdip)) ||
15372 			    (DEVI_IS_DEVICE_DOWN(tdip))) {
15373 				ap_state->ap_ostate =
15374 				    AP_OSTATE_UNCONFIGURED;
15375 			} else {
15376 				ap_state->ap_ostate =
15377 				    AP_OSTATE_CONFIGURED;
15378 			}
15379 			mutex_exit(&(DEVI(tdip)->devi_lock));
15380 			ndi_devi_exit(dip, circ);
15381 		} else {
15382 			ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
15383 			ap_state->ap_condition = AP_COND_UNKNOWN;
15384 		}
15385 		break;
15386 	}
15387 	default:
15388 		ap_state->ap_rstate = AP_RSTATE_CONNECTED;
15389 		ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
15390 		ap_state->ap_condition = AP_COND_UNKNOWN;
15391 		/*
15392 		 * This is actually internal error condition (non fatal),
15393 		 * because we have already checked all defined device types.
15394 		 */
15395 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15396 		    "sata_cfgadm_state: Internal error: "
15397 		    "unknown device type"));
15398 		break;
15399 	}
15400 }
15401 
15402 
15403 /*
15404  * Process ioctl get device path request.
15405  *
15406  * NOTE: Port multiplier has no target dip. Devices connected to port
15407  * multiplier have target node attached to the HBA node. The only difference
15408  * between them and the directly-attached device node is a target address.
15409  */
15410 static int
15411 sata_ioctl_get_device_path(sata_hba_inst_t *sata_hba_inst,
15412     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
15413 {
15414 	char path[MAXPATHLEN];
15415 	uint32_t size;
15416 	dev_info_t *tdip;
15417 
15418 	(void) strcpy(path, "/devices");
15419 	if ((tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
15420 	    &sata_device->satadev_addr)) == NULL) {
15421 		/*
15422 		 * No such device. If this is a request for a size, do not
15423 		 * return EINVAL for non-existing target, because cfgadm
15424 		 * will then indicate a meaningless ioctl failure.
15425 		 * If this is a request for a path, indicate invalid
15426 		 * argument.
15427 		 */
15428 		if (ioc->get_size == 0)
15429 			return (EINVAL);
15430 	} else {
15431 		(void) ddi_pathname(tdip, path + strlen(path));
15432 	}
15433 	size = strlen(path) + 1;
15434 
15435 	if (ioc->get_size != 0) {
15436 		if (ddi_copyout((void *)&size, ioc->buf, ioc->bufsiz,
15437 		    mode) != 0)
15438 			return (EFAULT);
15439 	} else {
15440 		if (ioc->bufsiz != size)
15441 			return (EINVAL);
15442 
15443 		else if (ddi_copyout((void *)&path, ioc->buf, ioc->bufsiz,
15444 		    mode) != 0)
15445 			return (EFAULT);
15446 	}
15447 	return (0);
15448 }
15449 
15450 /*
15451  * Process ioctl get attachment point type request.
15452  *
15453  * NOTE: Port multiplier is supported.
15454  */
15455 static	int
15456 sata_ioctl_get_ap_type(sata_hba_inst_t *sata_hba_inst,
15457     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
15458 {
15459 	uint32_t	type_len;
15460 	const char	*ap_type;
15461 	int		dev_type;
15462 
15463 	if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
15464 		dev_type = SATA_CPORT_DEV_TYPE(sata_hba_inst,
15465 		    sata_device->satadev_addr.cport);
15466 	else /* pmport */
15467 		dev_type = SATA_PMPORT_DEV_TYPE(sata_hba_inst,
15468 		    sata_device->satadev_addr.cport,
15469 		    sata_device->satadev_addr.pmport);
15470 
15471 	switch (dev_type) {
15472 	case SATA_DTYPE_NONE:
15473 		ap_type = "port";
15474 		break;
15475 
15476 	case SATA_DTYPE_ATADISK:
15477 	case SATA_DTYPE_ATAPIDISK:
15478 		ap_type = "disk";
15479 		break;
15480 
15481 	case SATA_DTYPE_ATAPICD:
15482 		ap_type = "cd/dvd";
15483 		break;
15484 
15485 	case SATA_DTYPE_ATAPITAPE:
15486 		ap_type = "tape";
15487 		break;
15488 
15489 	case SATA_DTYPE_PMULT:
15490 		ap_type = "sata-pmult";
15491 		break;
15492 
15493 	case SATA_DTYPE_UNKNOWN:
15494 		ap_type = "unknown";
15495 		break;
15496 
15497 	default:
15498 		ap_type = "unsupported";
15499 		break;
15500 
15501 	} /* end of dev_type switch */
15502 
15503 	type_len = strlen(ap_type) + 1;
15504 
15505 	if (ioc->get_size) {
15506 		if (ddi_copyout((void *)&type_len, ioc->buf, ioc->bufsiz,
15507 		    mode) != 0)
15508 			return (EFAULT);
15509 	} else {
15510 		if (ioc->bufsiz != type_len)
15511 			return (EINVAL);
15512 
15513 		if (ddi_copyout((void *)ap_type, ioc->buf,
15514 		    ioc->bufsiz, mode) != 0)
15515 			return (EFAULT);
15516 	}
15517 	return (0);
15518 
15519 }
15520 
15521 /*
15522  * Process ioctl get device model info request.
15523  * This operation should return to cfgadm the device model
15524  * information string
15525  *
15526  * NOTE: Port multiplier is supported.
15527  */
15528 static	int
15529 sata_ioctl_get_model_info(sata_hba_inst_t *sata_hba_inst,
15530     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
15531 {
15532 	sata_drive_info_t *sdinfo;
15533 	uint32_t info_len;
15534 	char ap_info[SATA_ID_MODEL_LEN + 1];
15535 
15536 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
15537 	    sata_device->satadev_addr.cport)->cport_mutex);
15538 	if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
15539 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
15540 		    sata_device->satadev_addr.cport);
15541 	else /* port multiplier */
15542 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst,
15543 		    sata_device->satadev_addr.cport,
15544 		    sata_device->satadev_addr.pmport);
15545 	if (sdinfo == NULL) {
15546 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15547 		    sata_device->satadev_addr.cport)->cport_mutex);
15548 		return (EINVAL);
15549 	}
15550 
15551 #ifdef	_LITTLE_ENDIAN
15552 	swab(sdinfo->satadrv_id.ai_model, ap_info, SATA_ID_MODEL_LEN);
15553 #else	/* _LITTLE_ENDIAN */
15554 	bcopy(sdinfo->satadrv_id.ai_model, ap_info, SATA_ID_MODEL_LEN);
15555 #endif	/* _LITTLE_ENDIAN */
15556 
15557 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15558 	    sata_device->satadev_addr.cport)->cport_mutex);
15559 
15560 	ap_info[SATA_ID_MODEL_LEN] = '\0';
15561 
15562 	info_len = strlen(ap_info) + 1;
15563 
15564 	if (ioc->get_size) {
15565 		if (ddi_copyout((void *)&info_len, ioc->buf, ioc->bufsiz,
15566 		    mode) != 0)
15567 			return (EFAULT);
15568 	} else {
15569 		if (ioc->bufsiz < info_len)
15570 			return (EINVAL);
15571 		if (ddi_copyout((void *)ap_info, ioc->buf, ioc->bufsiz,
15572 		    mode) != 0)
15573 			return (EFAULT);
15574 	}
15575 	return (0);
15576 }
15577 
15578 
15579 /*
15580  * Process ioctl get device firmware revision info request.
15581  * This operation should return to cfgadm the device firmware revision
15582  * information string
15583  *
15584  * Port multiplier is supported.
15585  */
15586 static	int
15587 sata_ioctl_get_revfirmware_info(sata_hba_inst_t *sata_hba_inst,
15588     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
15589 {
15590 	sata_drive_info_t *sdinfo;
15591 	uint32_t info_len;
15592 	char ap_info[SATA_ID_FW_LEN + 1];
15593 
15594 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
15595 	    sata_device->satadev_addr.cport)->cport_mutex);
15596 	if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
15597 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
15598 		    sata_device->satadev_addr.cport);
15599 	else /* port multiplier */
15600 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst,
15601 		    sata_device->satadev_addr.cport,
15602 		    sata_device->satadev_addr.pmport);
15603 	if (sdinfo == NULL) {
15604 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15605 		    sata_device->satadev_addr.cport)->cport_mutex);
15606 		return (EINVAL);
15607 	}
15608 
15609 #ifdef	_LITTLE_ENDIAN
15610 	swab(sdinfo->satadrv_id.ai_fw, ap_info, SATA_ID_FW_LEN);
15611 #else	/* _LITTLE_ENDIAN */
15612 	bcopy(sdinfo->satadrv_id.ai_fw, ap_info, SATA_ID_FW_LEN);
15613 #endif	/* _LITTLE_ENDIAN */
15614 
15615 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15616 	    sata_device->satadev_addr.cport)->cport_mutex);
15617 
15618 	ap_info[SATA_ID_FW_LEN] = '\0';
15619 
15620 	info_len = strlen(ap_info) + 1;
15621 
15622 	if (ioc->get_size) {
15623 		if (ddi_copyout((void *)&info_len, ioc->buf, ioc->bufsiz,
15624 		    mode) != 0)
15625 			return (EFAULT);
15626 	} else {
15627 		if (ioc->bufsiz < info_len)
15628 			return (EINVAL);
15629 		if (ddi_copyout((void *)ap_info, ioc->buf, ioc->bufsiz,
15630 		    mode) != 0)
15631 			return (EFAULT);
15632 	}
15633 	return (0);
15634 }
15635 
15636 
15637 /*
15638  * Process ioctl get device serial number info request.
15639  * This operation should return to cfgadm the device serial number string.
15640  *
15641  * NOTE: Port multiplier is supported.
15642  */
15643 static	int
15644 sata_ioctl_get_serialnumber_info(sata_hba_inst_t *sata_hba_inst,
15645     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
15646 {
15647 	sata_drive_info_t *sdinfo;
15648 	uint32_t info_len;
15649 	char ap_info[SATA_ID_SERIAL_LEN + 1];
15650 
15651 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
15652 	    sata_device->satadev_addr.cport)->cport_mutex);
15653 	if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
15654 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
15655 		    sata_device->satadev_addr.cport);
15656 	else /* port multiplier */
15657 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst,
15658 		    sata_device->satadev_addr.cport,
15659 		    sata_device->satadev_addr.pmport);
15660 	if (sdinfo == NULL) {
15661 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15662 		    sata_device->satadev_addr.cport)->cport_mutex);
15663 		return (EINVAL);
15664 	}
15665 
15666 #ifdef	_LITTLE_ENDIAN
15667 	swab(sdinfo->satadrv_id.ai_drvser, ap_info, SATA_ID_SERIAL_LEN);
15668 #else	/* _LITTLE_ENDIAN */
15669 	bcopy(sdinfo->satadrv_id.ai_drvser, ap_info, SATA_ID_SERIAL_LEN);
15670 #endif	/* _LITTLE_ENDIAN */
15671 
15672 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15673 	    sata_device->satadev_addr.cport)->cport_mutex);
15674 
15675 	ap_info[SATA_ID_SERIAL_LEN] = '\0';
15676 
15677 	info_len = strlen(ap_info) + 1;
15678 
15679 	if (ioc->get_size) {
15680 		if (ddi_copyout((void *)&info_len, ioc->buf, ioc->bufsiz,
15681 		    mode) != 0)
15682 			return (EFAULT);
15683 	} else {
15684 		if (ioc->bufsiz < info_len)
15685 			return (EINVAL);
15686 		if (ddi_copyout((void *)ap_info, ioc->buf, ioc->bufsiz,
15687 		    mode) != 0)
15688 			return (EFAULT);
15689 	}
15690 	return (0);
15691 }
15692 
15693 
15694 /*
15695  * Preset scsi extended sense data (to NO SENSE)
15696  * First 18 bytes of the sense data are preset to current valid sense
15697  * with a key NO SENSE data.
15698  *
15699  * Returns void
15700  */
15701 static void
15702 sata_fixed_sense_data_preset(struct scsi_extended_sense *sense)
15703 {
15704 	sense->es_valid = 1;		/* Valid sense */
15705 	sense->es_class = CLASS_EXTENDED_SENSE;	/* 0x70 - current err */
15706 	sense->es_key = KEY_NO_SENSE;
15707 	sense->es_info_1 = 0;
15708 	sense->es_info_2 = 0;
15709 	sense->es_info_3 = 0;
15710 	sense->es_info_4 = 0;
15711 	sense->es_add_len = 10;	/* Additional length - replace with a def */
15712 	sense->es_cmd_info[0] = 0;
15713 	sense->es_cmd_info[1] = 0;
15714 	sense->es_cmd_info[2] = 0;
15715 	sense->es_cmd_info[3] = 0;
15716 	sense->es_add_code = 0;
15717 	sense->es_qual_code = 0;
15718 }
15719 
15720 /*
15721  * Register a legacy cmdk-style devid for the target (disk) device.
15722  *
15723  * Note: This function is called only when the HBA devinfo node has the
15724  * property "use-cmdk-devid-format" set. This property indicates that
15725  * devid compatible with old cmdk (target) driver is to be generated
15726  * for any target device attached to this controller. This will take
15727  * precedence over the devid generated by sd (target) driver.
15728  * This function is derived from cmdk_devid_setup() function in cmdk.c.
15729  */
15730 static void
15731 sata_target_devid_register(dev_info_t *dip, sata_drive_info_t *sdinfo)
15732 {
15733 	char	*hwid;
15734 	int	modlen;
15735 	int	serlen;
15736 	int	rval;
15737 	ddi_devid_t	devid;
15738 
15739 	/*
15740 	 * device ID is a concatanation of model number, "=", serial number.
15741 	 */
15742 	hwid = kmem_zalloc(LEGACY_HWID_LEN, KM_SLEEP);
15743 	bcopy(&sdinfo->satadrv_id.ai_model, hwid,
15744 	    sizeof (sdinfo->satadrv_id.ai_model));
15745 	swab(hwid, hwid, sizeof (sdinfo->satadrv_id.ai_model));
15746 	modlen = sata_check_modser(hwid, sizeof (sdinfo->satadrv_id.ai_model));
15747 	if (modlen == 0)
15748 		goto err;
15749 	hwid[modlen++] = '=';
15750 	bcopy(&sdinfo->satadrv_id.ai_drvser, &hwid[modlen],
15751 	    sizeof (sdinfo->satadrv_id.ai_drvser));
15752 	swab(&hwid[modlen], &hwid[modlen],
15753 	    sizeof (sdinfo->satadrv_id.ai_drvser));
15754 	serlen = sata_check_modser(&hwid[modlen],
15755 	    sizeof (sdinfo->satadrv_id.ai_drvser));
15756 	if (serlen == 0)
15757 		goto err;
15758 	hwid[modlen + serlen] = 0; /* terminate the hwid string */
15759 
15760 	/* initialize/register devid */
15761 	if ((rval = ddi_devid_init(dip, DEVID_ATA_SERIAL,
15762 	    (ushort_t)(modlen + serlen), hwid, &devid)) == DDI_SUCCESS) {
15763 		rval = ddi_devid_register(dip, devid);
15764 		/*
15765 		 * Free up the allocated devid buffer.
15766 		 * NOTE: This doesn't mean unregistering devid.
15767 		 */
15768 		ddi_devid_free(devid);
15769 	}
15770 
15771 	if (rval != DDI_SUCCESS)
15772 		cmn_err(CE_WARN, "sata: failed to create devid for the disk"
15773 		    " on port %d", sdinfo->satadrv_addr.cport);
15774 err:
15775 	kmem_free(hwid, LEGACY_HWID_LEN);
15776 }
15777 
15778 /*
15779  * valid model/serial string must contain a non-zero non-space characters.
15780  * trim trailing spaces/NULLs.
15781  */
15782 static int
15783 sata_check_modser(char *buf, int buf_len)
15784 {
15785 	boolean_t ret;
15786 	char *s;
15787 	int i;
15788 	int tb;
15789 	char ch;
15790 
15791 	ret = B_FALSE;
15792 	s = buf;
15793 	for (i = 0; i < buf_len; i++) {
15794 		ch = *s++;
15795 		if (ch != ' ' && ch != '\0')
15796 			tb = i + 1;
15797 		if (ch != ' ' && ch != '\0' && ch != '0')
15798 			ret = B_TRUE;
15799 	}
15800 
15801 	if (ret == B_FALSE)
15802 		return (0); /* invalid string */
15803 
15804 	return (tb); /* return length */
15805 }
15806 
15807 /*
15808  * sata_set_drive_features function compares current device features setting
15809  * with the saved device features settings and, if there is a difference,
15810  * it restores device features setting to the previously saved state.
15811  * It also arbitrarily tries to select the highest supported DMA mode.
15812  * Device Identify or Identify Packet Device data has to be current.
15813  * At the moment read ahead and write cache are considered for all devices.
15814  * For atapi devices, Removable Media Status Notification is set in addition
15815  * to common features.
15816  *
15817  * This function cannot be called in the interrupt context (it may sleep).
15818  *
15819  * The input argument sdinfo should point to the drive info structure
15820  * to be updated after features are set. Note, that only
15821  * device (packet) identify data is updated, not the flags indicating the
15822  * supported features.
15823  *
15824  * Returns SATA_SUCCESS if successful or there was nothing to do.
15825  * Device Identify data in the drive info structure pointed to by the sdinfo
15826  * arguments is updated even when no features were set or changed.
15827  *
15828  * Returns SATA_FAILURE if device features could not be set or DMA mode
15829  * for a disk cannot be set and device identify data cannot be fetched.
15830  *
15831  * Returns SATA_RETRY if device features could not be set (other than disk
15832  * DMA mode) but the device identify data was fetched successfully.
15833  *
15834  * Note: This function may fail the port, making it inaccessible.
15835  * In such case the explicit port disconnect/connect or physical device
15836  * detach/attach is required to re-evaluate port state again.
15837  */
15838 
15839 static int
15840 sata_set_drive_features(sata_hba_inst_t *sata_hba_inst,
15841     sata_drive_info_t *sdinfo, int restore)
15842 {
15843 	int rval = SATA_SUCCESS;
15844 	int rval_set;
15845 	sata_drive_info_t new_sdinfo;
15846 	char *finfo = "sata_set_drive_features: cannot";
15847 	char *finfox;
15848 	int cache_op;
15849 
15850 	bzero(&new_sdinfo, sizeof (sata_drive_info_t));
15851 	new_sdinfo.satadrv_addr = sdinfo->satadrv_addr;
15852 	new_sdinfo.satadrv_type = sdinfo->satadrv_type;
15853 	if (sata_fetch_device_identify_data(sata_hba_inst, &new_sdinfo) != 0) {
15854 		/*
15855 		 * Cannot get device identification - caller may retry later
15856 		 */
15857 		SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
15858 		    "%s fetch device identify data\n", finfo);
15859 		return (SATA_FAILURE);
15860 	}
15861 	finfox = (restore != 0) ? " restore device features" :
15862 	    " initialize device features\n";
15863 
15864 	switch (sdinfo->satadrv_type) {
15865 	case SATA_DTYPE_ATADISK:
15866 		/* Arbitrarily set UDMA mode */
15867 		if (sata_set_dma_mode(sata_hba_inst, &new_sdinfo) !=
15868 		    SATA_SUCCESS) {
15869 			SATA_LOG_D((sata_hba_inst, CE_WARN,
15870 			    "%s set UDMA mode\n", finfo));
15871 			return (SATA_FAILURE);
15872 		}
15873 		break;
15874 	case SATA_DTYPE_ATAPICD:
15875 	case SATA_DTYPE_ATAPITAPE:
15876 	case SATA_DTYPE_ATAPIDISK:
15877 		/*  Set Removable Media Status Notification, if necessary */
15878 		if (SATA_RM_NOTIFIC_SUPPORTED(new_sdinfo.satadrv_id) &&
15879 		    restore != 0) {
15880 			if (((sdinfo->satadrv_settings & SATA_DEV_RMSN) &&
15881 			    (!SATA_RM_NOTIFIC_ENABLED(new_sdinfo.satadrv_id)))||
15882 			    ((!(sdinfo->satadrv_settings & SATA_DEV_RMSN)) &&
15883 			    SATA_RM_NOTIFIC_ENABLED(new_sdinfo.satadrv_id))) {
15884 				/* Current setting does not match saved one */
15885 				if (sata_set_rmsn(sata_hba_inst, sdinfo,
15886 				    sdinfo->satadrv_settings &
15887 				    SATA_DEV_RMSN) != SATA_SUCCESS)
15888 					rval = SATA_FAILURE;
15889 			}
15890 		}
15891 		/*
15892 		 * We have to set Multiword DMA or UDMA, if it is supported, as
15893 		 * we want to use DMA transfer mode whenever possible.
15894 		 * Some devices require explicit setting of the DMA mode.
15895 		 */
15896 		if (new_sdinfo.satadrv_id.ai_cap & SATA_DMA_SUPPORT) {
15897 			/* Set highest supported DMA mode */
15898 			if (sata_set_dma_mode(sata_hba_inst, &new_sdinfo) !=
15899 			    SATA_SUCCESS) {
15900 				SATA_LOG_D((sata_hba_inst, CE_WARN,
15901 				    "%s set UDMA mode\n", finfo));
15902 				rval = SATA_FAILURE;
15903 			}
15904 		}
15905 		break;
15906 	}
15907 
15908 	if (!SATA_READ_AHEAD_SUPPORTED(new_sdinfo.satadrv_id) &&
15909 	    !SATA_WRITE_CACHE_SUPPORTED(new_sdinfo.satadrv_id)) {
15910 		/*
15911 		 * neither READ AHEAD nor WRITE CACHE is supported
15912 		 * - do nothing
15913 		 */
15914 		SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
15915 		    "settable features not supported\n", NULL);
15916 		goto update_sdinfo;
15917 	}
15918 
15919 	if ((SATA_READ_AHEAD_ENABLED(new_sdinfo.satadrv_id) &&
15920 	    (sdinfo->satadrv_settings & SATA_DEV_READ_AHEAD)) &&
15921 	    (SATA_WRITE_CACHE_ENABLED(new_sdinfo.satadrv_id) &&
15922 	    (sdinfo->satadrv_settings & SATA_DEV_WRITE_CACHE))) {
15923 		/*
15924 		 * both READ AHEAD and WRITE CACHE are enabled
15925 		 * - Nothing to do
15926 		 */
15927 		SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
15928 		    "no device features to set\n", NULL);
15929 		goto update_sdinfo;
15930 	}
15931 
15932 	cache_op = 0;
15933 
15934 	if (SATA_READ_AHEAD_SUPPORTED(new_sdinfo.satadrv_id)) {
15935 		if ((sdinfo->satadrv_settings & SATA_DEV_READ_AHEAD) &&
15936 		    !SATA_READ_AHEAD_ENABLED(new_sdinfo.satadrv_id)) {
15937 			/* Enable read ahead / read cache */
15938 			cache_op = SATAC_SF_ENABLE_READ_AHEAD;
15939 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
15940 			    "enabling read cache\n", NULL);
15941 		} else if (!(sdinfo->satadrv_settings & SATA_DEV_READ_AHEAD) &&
15942 		    SATA_READ_AHEAD_ENABLED(new_sdinfo.satadrv_id)) {
15943 			/* Disable read ahead  / read cache */
15944 			cache_op = SATAC_SF_DISABLE_READ_AHEAD;
15945 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
15946 			    "disabling read cache\n", NULL);
15947 		}
15948 
15949 		if (cache_op != 0) {
15950 			/* Try to set read cache mode */
15951 			rval_set = sata_set_cache_mode(sata_hba_inst,
15952 			    &new_sdinfo, cache_op);
15953 			if (rval != SATA_FAILURE && rval_set != SATA_SUCCESS)
15954 				rval = rval_set;
15955 		}
15956 	}
15957 
15958 	cache_op = 0;
15959 
15960 	if (SATA_WRITE_CACHE_SUPPORTED(new_sdinfo.satadrv_id)) {
15961 		if ((sdinfo->satadrv_settings & SATA_DEV_WRITE_CACHE) &&
15962 		    !SATA_WRITE_CACHE_ENABLED(new_sdinfo.satadrv_id)) {
15963 			/* Enable write cache */
15964 			cache_op = SATAC_SF_ENABLE_WRITE_CACHE;
15965 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
15966 			    "enabling write cache\n", NULL);
15967 		} else if (!(sdinfo->satadrv_settings & SATA_DEV_WRITE_CACHE) &&
15968 		    SATA_WRITE_CACHE_ENABLED(new_sdinfo.satadrv_id)) {
15969 			/* Disable write cache */
15970 			cache_op = SATAC_SF_DISABLE_WRITE_CACHE;
15971 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
15972 			    "disabling write cache\n", NULL);
15973 		}
15974 
15975 		if (cache_op != 0) {
15976 			/* Try to set write cache mode */
15977 			rval_set = sata_set_cache_mode(sata_hba_inst,
15978 			    &new_sdinfo, cache_op);
15979 			if (rval != SATA_FAILURE && rval_set != SATA_SUCCESS)
15980 				rval = rval_set;
15981 		}
15982 	}
15983 	if (rval != SATA_SUCCESS)
15984 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15985 		    "%s %s", finfo, finfox));
15986 
15987 update_sdinfo:
15988 	/*
15989 	 * We need to fetch Device Identify data again
15990 	 */
15991 	if (sata_fetch_device_identify_data(sata_hba_inst, &new_sdinfo) != 0) {
15992 		/*
15993 		 * Cannot get device identification - retry later
15994 		 */
15995 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15996 		    "%s re-fetch device identify data\n", finfo));
15997 		rval = SATA_FAILURE;
15998 	}
15999 	/* Copy device sata info. */
16000 	sdinfo->satadrv_id = new_sdinfo.satadrv_id;
16001 
16002 	return (rval);
16003 }
16004 
16005 
16006 /*
16007  *
16008  * Returns 1 if threshold exceeded, 0 if threshold not exceeded, -1 if
16009  * unable to determine.
16010  *
16011  * Cannot be called in an interrupt context.
16012  *
16013  * Called by sata_build_lsense_page_2f()
16014  */
16015 
16016 static int
16017 sata_fetch_smart_return_status(sata_hba_inst_t *sata_hba_inst,
16018     sata_drive_info_t *sdinfo)
16019 {
16020 	sata_pkt_t *spkt;
16021 	sata_cmd_t *scmd;
16022 	sata_pkt_txlate_t *spx;
16023 	int rval;
16024 
16025 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
16026 	spx->txlt_sata_hba_inst = sata_hba_inst;
16027 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
16028 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
16029 	if (spkt == NULL) {
16030 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16031 		return (-1);
16032 	}
16033 	/* address is needed now */
16034 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16035 
16036 
16037 	/* Fill sata_pkt */
16038 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16039 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
16040 	/* Synchronous mode, no callback */
16041 	spkt->satapkt_comp = NULL;
16042 	/* Timeout 30s */
16043 	spkt->satapkt_time = sata_default_pkt_time;
16044 
16045 	scmd = &spkt->satapkt_cmd;
16046 	scmd->satacmd_flags.sata_special_regs = B_TRUE;
16047 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
16048 
16049 	/* Set up which registers need to be returned */
16050 	scmd->satacmd_flags.sata_copy_out_lba_mid_lsb = B_TRUE;
16051 	scmd->satacmd_flags.sata_copy_out_lba_high_lsb = B_TRUE;
16052 
16053 	/* Build SMART_RETURN_STATUS cmd in the sata_pkt */
16054 	scmd->satacmd_addr_type = 0;		/* N/A */
16055 	scmd->satacmd_sec_count_lsb = 0;	/* N/A */
16056 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
16057 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
16058 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
16059 	scmd->satacmd_features_reg = SATA_SMART_RETURN_STATUS;
16060 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
16061 	scmd->satacmd_cmd_reg = SATAC_SMART;
16062 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
16063 	    sdinfo->satadrv_addr.cport)));
16064 
16065 
16066 	/* Send pkt to SATA HBA driver */
16067 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
16068 	    SATA_TRAN_ACCEPTED ||
16069 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
16070 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16071 		    sdinfo->satadrv_addr.cport)));
16072 		/*
16073 		 * Whoops, no SMART RETURN STATUS
16074 		 */
16075 		rval = -1;
16076 	} else {
16077 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16078 		    sdinfo->satadrv_addr.cport)));
16079 		if (scmd->satacmd_error_reg & SATA_ERROR_ABORT) {
16080 			rval = -1;
16081 			goto fail;
16082 		}
16083 		if (scmd->satacmd_status_reg & SATA_STATUS_ERR) {
16084 			rval = -1;
16085 			goto fail;
16086 		}
16087 		if ((scmd->satacmd_lba_mid_lsb == SMART_MAGIC_VAL_1) &&
16088 		    (scmd->satacmd_lba_high_lsb == SMART_MAGIC_VAL_2))
16089 			rval = 0;
16090 		else if ((scmd->satacmd_lba_mid_lsb == SMART_MAGIC_VAL_3) &&
16091 		    (scmd->satacmd_lba_high_lsb == SMART_MAGIC_VAL_4))
16092 			rval = 1;
16093 		else {
16094 			rval = -1;
16095 			goto fail;
16096 		}
16097 	}
16098 fail:
16099 	/* Free allocated resources */
16100 	sata_pkt_free(spx);
16101 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
16102 
16103 	return (rval);
16104 }
16105 
16106 /*
16107  *
16108  * Returns 0 if succeeded, -1 otherwise
16109  *
16110  * Cannot be called in an interrupt context.
16111  *
16112  */
16113 static int
16114 sata_fetch_smart_data(
16115 	sata_hba_inst_t *sata_hba_inst,
16116 	sata_drive_info_t *sdinfo,
16117 	struct smart_data *smart_data)
16118 {
16119 	sata_pkt_t *spkt;
16120 	sata_cmd_t *scmd;
16121 	sata_pkt_txlate_t *spx;
16122 	int rval;
16123 
16124 #if ! defined(lint)
16125 	ASSERT(sizeof (struct smart_data) == 512);
16126 #endif
16127 
16128 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
16129 	spx->txlt_sata_hba_inst = sata_hba_inst;
16130 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
16131 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
16132 	if (spkt == NULL) {
16133 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16134 		return (-1);
16135 	}
16136 	/* address is needed now */
16137 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16138 
16139 
16140 	/* Fill sata_pkt */
16141 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16142 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
16143 	/* Synchronous mode, no callback */
16144 	spkt->satapkt_comp = NULL;
16145 	/* Timeout 30s */
16146 	spkt->satapkt_time = sata_default_pkt_time;
16147 
16148 	scmd = &spkt->satapkt_cmd;
16149 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
16150 
16151 	/*
16152 	 * Allocate buffer for SMART data
16153 	 */
16154 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
16155 	    sizeof (struct smart_data));
16156 	if (scmd->satacmd_bp == NULL) {
16157 		sata_pkt_free(spx);
16158 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16159 		SATA_LOG_D((sata_hba_inst, CE_WARN,
16160 		    "sata_fetch_smart_data: "
16161 		    "cannot allocate buffer"));
16162 		return (-1);
16163 	}
16164 
16165 
16166 	/* Build SMART_READ_DATA cmd in the sata_pkt */
16167 	scmd->satacmd_addr_type = 0;		/* N/A */
16168 	scmd->satacmd_sec_count_lsb = 0;	/* N/A */
16169 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
16170 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
16171 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
16172 	scmd->satacmd_features_reg = SATA_SMART_READ_DATA;
16173 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
16174 	scmd->satacmd_cmd_reg = SATAC_SMART;
16175 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
16176 	    sdinfo->satadrv_addr.cport)));
16177 
16178 	/* Send pkt to SATA HBA driver */
16179 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
16180 	    SATA_TRAN_ACCEPTED ||
16181 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
16182 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16183 		    sdinfo->satadrv_addr.cport)));
16184 		/*
16185 		 * Whoops, no SMART DATA available
16186 		 */
16187 		rval = -1;
16188 		goto fail;
16189 	} else {
16190 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16191 		    sdinfo->satadrv_addr.cport)));
16192 		if (spx->txlt_buf_dma_handle != NULL) {
16193 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
16194 			    DDI_DMA_SYNC_FORKERNEL);
16195 			ASSERT(rval == DDI_SUCCESS);
16196 		}
16197 		bcopy(scmd->satacmd_bp->b_un.b_addr, (uint8_t *)smart_data,
16198 		    sizeof (struct smart_data));
16199 	}
16200 
16201 fail:
16202 	/* Free allocated resources */
16203 	sata_free_local_buffer(spx);
16204 	sata_pkt_free(spx);
16205 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
16206 
16207 	return (rval);
16208 }
16209 
16210 /*
16211  * Used by LOG SENSE page 0x10
16212  * Reads (in synchronous mode) the self test log data using Read Log Ext cmd.
16213  * Note: cannot be called in the interrupt context.
16214  *
16215  * return 0 for success, -1 otherwise
16216  *
16217  */
16218 static int
16219 sata_ext_smart_selftest_read_log(
16220 	sata_hba_inst_t *sata_hba_inst,
16221 	sata_drive_info_t *sdinfo,
16222 	struct smart_ext_selftest_log *ext_selftest_log,
16223 	uint16_t block_num)
16224 {
16225 	sata_pkt_txlate_t *spx;
16226 	sata_pkt_t *spkt;
16227 	sata_cmd_t *scmd;
16228 	int rval;
16229 
16230 #if ! defined(lint)
16231 	ASSERT(sizeof (struct smart_ext_selftest_log) == 512);
16232 #endif
16233 
16234 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
16235 	spx->txlt_sata_hba_inst = sata_hba_inst;
16236 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
16237 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
16238 	if (spkt == NULL) {
16239 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16240 		return (-1);
16241 	}
16242 	/* address is needed now */
16243 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16244 
16245 
16246 	/* Fill sata_pkt */
16247 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16248 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
16249 	/* Synchronous mode, no callback */
16250 	spkt->satapkt_comp = NULL;
16251 	/* Timeout 30s */
16252 	spkt->satapkt_time = sata_default_pkt_time;
16253 
16254 	scmd = &spkt->satapkt_cmd;
16255 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
16256 
16257 	/*
16258 	 * Allocate buffer for SMART extended self-test log
16259 	 */
16260 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
16261 	    sizeof (struct smart_ext_selftest_log));
16262 	if (scmd->satacmd_bp == NULL) {
16263 		sata_pkt_free(spx);
16264 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16265 		SATA_LOG_D((sata_hba_inst, CE_WARN,
16266 		    "sata_ext_smart_selftest_log: "
16267 		    "cannot allocate buffer"));
16268 		return (-1);
16269 	}
16270 
16271 	/* Build READ LOG EXT w/ extended self-test log cmd in the sata_pkt */
16272 	scmd->satacmd_addr_type = ATA_ADDR_LBA48;
16273 	scmd->satacmd_sec_count_lsb = 1;	/* One sector of selftest log */
16274 	scmd->satacmd_sec_count_msb = 0;	/* One sector of selftest log */
16275 	scmd->satacmd_lba_low_lsb = EXT_SMART_SELFTEST_LOG_PAGE;
16276 	scmd->satacmd_lba_low_msb = 0;
16277 	scmd->satacmd_lba_mid_lsb = block_num & 0xff;
16278 	scmd->satacmd_lba_mid_msb = block_num >> 8;
16279 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
16280 	scmd->satacmd_cmd_reg = SATAC_READ_LOG_EXT;
16281 
16282 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
16283 	    sdinfo->satadrv_addr.cport)));
16284 
16285 	/* Send pkt to SATA HBA driver */
16286 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
16287 	    SATA_TRAN_ACCEPTED ||
16288 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
16289 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16290 		    sdinfo->satadrv_addr.cport)));
16291 
16292 		/*
16293 		 * Whoops, no SMART selftest log info available
16294 		 */
16295 		rval = -1;
16296 		goto fail;
16297 	} else {
16298 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16299 		    sdinfo->satadrv_addr.cport)));
16300 
16301 		if (spx->txlt_buf_dma_handle != NULL) {
16302 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
16303 			    DDI_DMA_SYNC_FORKERNEL);
16304 			ASSERT(rval == DDI_SUCCESS);
16305 		}
16306 		bcopy(scmd->satacmd_bp->b_un.b_addr,
16307 		    (uint8_t *)ext_selftest_log,
16308 		    sizeof (struct smart_ext_selftest_log));
16309 		rval = 0;
16310 	}
16311 
16312 fail:
16313 	/* Free allocated resources */
16314 	sata_free_local_buffer(spx);
16315 	sata_pkt_free(spx);
16316 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
16317 
16318 	return (rval);
16319 }
16320 
16321 /*
16322  * Returns 0 for success, -1 otherwise
16323  *
16324  * SMART self-test log data is returned in buffer pointed to by selftest_log
16325  */
16326 static int
16327 sata_smart_selftest_log(
16328 	sata_hba_inst_t *sata_hba_inst,
16329 	sata_drive_info_t *sdinfo,
16330 	struct smart_selftest_log *selftest_log)
16331 {
16332 	sata_pkt_t *spkt;
16333 	sata_cmd_t *scmd;
16334 	sata_pkt_txlate_t *spx;
16335 	int rval;
16336 
16337 #if ! defined(lint)
16338 	ASSERT(sizeof (struct smart_selftest_log) == 512);
16339 #endif
16340 
16341 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
16342 	spx->txlt_sata_hba_inst = sata_hba_inst;
16343 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
16344 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
16345 	if (spkt == NULL) {
16346 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16347 		return (-1);
16348 	}
16349 	/* address is needed now */
16350 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16351 
16352 
16353 	/* Fill sata_pkt */
16354 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16355 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
16356 	/* Synchronous mode, no callback */
16357 	spkt->satapkt_comp = NULL;
16358 	/* Timeout 30s */
16359 	spkt->satapkt_time = sata_default_pkt_time;
16360 
16361 	scmd = &spkt->satapkt_cmd;
16362 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
16363 
16364 	/*
16365 	 * Allocate buffer for SMART SELFTEST LOG
16366 	 */
16367 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
16368 	    sizeof (struct smart_selftest_log));
16369 	if (scmd->satacmd_bp == NULL) {
16370 		sata_pkt_free(spx);
16371 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16372 		SATA_LOG_D((sata_hba_inst, CE_WARN,
16373 		    "sata_smart_selftest_log: "
16374 		    "cannot allocate buffer"));
16375 		return (-1);
16376 	}
16377 
16378 	/* Build SMART_READ_LOG cmd in the sata_pkt */
16379 	scmd->satacmd_addr_type = 0;		/* N/A */
16380 	scmd->satacmd_sec_count_lsb = 1;	/* One sector of SMART log */
16381 	scmd->satacmd_lba_low_lsb = SMART_SELFTEST_LOG_PAGE;
16382 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
16383 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
16384 	scmd->satacmd_features_reg = SATA_SMART_READ_LOG;
16385 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
16386 	scmd->satacmd_cmd_reg = SATAC_SMART;
16387 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
16388 	    sdinfo->satadrv_addr.cport)));
16389 
16390 	/* Send pkt to SATA HBA driver */
16391 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
16392 	    SATA_TRAN_ACCEPTED ||
16393 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
16394 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16395 		    sdinfo->satadrv_addr.cport)));
16396 		/*
16397 		 * Whoops, no SMART DATA available
16398 		 */
16399 		rval = -1;
16400 		goto fail;
16401 	} else {
16402 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16403 		    sdinfo->satadrv_addr.cport)));
16404 		if (spx->txlt_buf_dma_handle != NULL) {
16405 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
16406 			    DDI_DMA_SYNC_FORKERNEL);
16407 			ASSERT(rval == DDI_SUCCESS);
16408 		}
16409 		bcopy(scmd->satacmd_bp->b_un.b_addr, (uint8_t *)selftest_log,
16410 		    sizeof (struct smart_selftest_log));
16411 		rval = 0;
16412 	}
16413 
16414 fail:
16415 	/* Free allocated resources */
16416 	sata_free_local_buffer(spx);
16417 	sata_pkt_free(spx);
16418 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
16419 
16420 	return (rval);
16421 }
16422 
16423 
16424 /*
16425  * Returns 0 for success, -1 otherwise
16426  *
16427  * SMART READ LOG data is returned in buffer pointed to by smart_log
16428  */
16429 static int
16430 sata_smart_read_log(
16431 	sata_hba_inst_t *sata_hba_inst,
16432 	sata_drive_info_t *sdinfo,
16433 	uint8_t *smart_log,		/* where the data should be returned */
16434 	uint8_t which_log,		/* which log should be returned */
16435 	uint8_t log_size)		/* # of 512 bytes in log */
16436 {
16437 	sata_pkt_t *spkt;
16438 	sata_cmd_t *scmd;
16439 	sata_pkt_txlate_t *spx;
16440 	int rval;
16441 
16442 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
16443 	spx->txlt_sata_hba_inst = sata_hba_inst;
16444 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
16445 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
16446 	if (spkt == NULL) {
16447 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16448 		return (-1);
16449 	}
16450 	/* address is needed now */
16451 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16452 
16453 
16454 	/* Fill sata_pkt */
16455 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16456 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
16457 	/* Synchronous mode, no callback */
16458 	spkt->satapkt_comp = NULL;
16459 	/* Timeout 30s */
16460 	spkt->satapkt_time = sata_default_pkt_time;
16461 
16462 	scmd = &spkt->satapkt_cmd;
16463 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
16464 
16465 	/*
16466 	 * Allocate buffer for SMART READ LOG
16467 	 */
16468 	scmd->satacmd_bp = sata_alloc_local_buffer(spx, log_size * 512);
16469 	if (scmd->satacmd_bp == NULL) {
16470 		sata_pkt_free(spx);
16471 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16472 		SATA_LOG_D((sata_hba_inst, CE_WARN,
16473 		    "sata_smart_read_log: " "cannot allocate buffer"));
16474 		return (-1);
16475 	}
16476 
16477 	/* Build SMART_READ_LOG cmd in the sata_pkt */
16478 	scmd->satacmd_addr_type = 0;		/* N/A */
16479 	scmd->satacmd_sec_count_lsb = log_size;	/* what the caller asked for */
16480 	scmd->satacmd_lba_low_lsb = which_log;	/* which log page */
16481 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
16482 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
16483 	scmd->satacmd_features_reg = SATA_SMART_READ_LOG;
16484 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
16485 	scmd->satacmd_cmd_reg = SATAC_SMART;
16486 
16487 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
16488 	    sdinfo->satadrv_addr.cport)));
16489 
16490 	/* Send pkt to SATA HBA driver */
16491 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
16492 	    SATA_TRAN_ACCEPTED ||
16493 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
16494 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16495 		    sdinfo->satadrv_addr.cport)));
16496 
16497 		/*
16498 		 * Whoops, no SMART DATA available
16499 		 */
16500 		rval = -1;
16501 		goto fail;
16502 	} else {
16503 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16504 		    sdinfo->satadrv_addr.cport)));
16505 
16506 		if (spx->txlt_buf_dma_handle != NULL) {
16507 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
16508 			    DDI_DMA_SYNC_FORKERNEL);
16509 			ASSERT(rval == DDI_SUCCESS);
16510 		}
16511 		bcopy(scmd->satacmd_bp->b_un.b_addr, smart_log, log_size * 512);
16512 		rval = 0;
16513 	}
16514 
16515 fail:
16516 	/* Free allocated resources */
16517 	sata_free_local_buffer(spx);
16518 	sata_pkt_free(spx);
16519 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
16520 
16521 	return (rval);
16522 }
16523 
16524 /*
16525  * Used by LOG SENSE page 0x10
16526  *
16527  * return 0 for success, -1 otherwise
16528  *
16529  */
16530 static int
16531 sata_read_log_ext_directory(
16532 	sata_hba_inst_t *sata_hba_inst,
16533 	sata_drive_info_t *sdinfo,
16534 	struct read_log_ext_directory *logdir)
16535 {
16536 	sata_pkt_txlate_t *spx;
16537 	sata_pkt_t *spkt;
16538 	sata_cmd_t *scmd;
16539 	int rval;
16540 
16541 #if ! defined(lint)
16542 	ASSERT(sizeof (struct read_log_ext_directory) == 512);
16543 #endif
16544 
16545 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
16546 	spx->txlt_sata_hba_inst = sata_hba_inst;
16547 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
16548 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
16549 	if (spkt == NULL) {
16550 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16551 		return (-1);
16552 	}
16553 
16554 	/* Fill sata_pkt */
16555 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16556 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
16557 	/* Synchronous mode, no callback */
16558 	spkt->satapkt_comp = NULL;
16559 	/* Timeout 30s */
16560 	spkt->satapkt_time = sata_default_pkt_time;
16561 
16562 	scmd = &spkt->satapkt_cmd;
16563 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
16564 
16565 	/*
16566 	 * Allocate buffer for SMART READ LOG EXTENDED command
16567 	 */
16568 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
16569 	    sizeof (struct read_log_ext_directory));
16570 	if (scmd->satacmd_bp == NULL) {
16571 		sata_pkt_free(spx);
16572 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16573 		SATA_LOG_D((sata_hba_inst, CE_WARN,
16574 		    "sata_read_log_ext_directory: "
16575 		    "cannot allocate buffer"));
16576 		return (-1);
16577 	}
16578 
16579 	/* Build READ LOG EXT w/ log directory cmd in the  sata_pkt */
16580 	scmd->satacmd_addr_type = ATA_ADDR_LBA48;
16581 	scmd->satacmd_sec_count_lsb = 1;	/* One sector of directory */
16582 	scmd->satacmd_sec_count_msb = 0;	/* One sector of directory */
16583 	scmd->satacmd_lba_low_lsb = READ_LOG_EXT_LOG_DIRECTORY;
16584 	scmd->satacmd_lba_low_msb = 0;
16585 	scmd->satacmd_lba_mid_lsb = 0;
16586 	scmd->satacmd_lba_mid_msb = 0;
16587 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
16588 	scmd->satacmd_cmd_reg = SATAC_READ_LOG_EXT;
16589 
16590 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
16591 	    sdinfo->satadrv_addr.cport)));
16592 
16593 	/* Send pkt to SATA HBA driver */
16594 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
16595 	    SATA_TRAN_ACCEPTED ||
16596 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
16597 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16598 		    sdinfo->satadrv_addr.cport)));
16599 		/*
16600 		 * Whoops, no SMART selftest log info available
16601 		 */
16602 		rval = -1;
16603 		goto fail;
16604 	} else {
16605 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16606 		    sdinfo->satadrv_addr.cport)));
16607 		if (spx->txlt_buf_dma_handle != NULL) {
16608 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
16609 			    DDI_DMA_SYNC_FORKERNEL);
16610 			ASSERT(rval == DDI_SUCCESS);
16611 		}
16612 		bcopy(scmd->satacmd_bp->b_un.b_addr, (uint8_t *)logdir,
16613 		    sizeof (struct read_log_ext_directory));
16614 		rval = 0;
16615 	}
16616 
16617 fail:
16618 	/* Free allocated resources */
16619 	sata_free_local_buffer(spx);
16620 	sata_pkt_free(spx);
16621 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
16622 
16623 	return (rval);
16624 }
16625 
16626 /*
16627  * Set up error retrieval sata command for NCQ command error data
16628  * recovery.
16629  *
16630  * Returns SATA_SUCCESS when data buffer is allocated and packet set-up,
16631  * returns SATA_FAILURE otherwise.
16632  */
16633 static int
16634 sata_ncq_err_ret_cmd_setup(sata_pkt_txlate_t *spx, sata_drive_info_t *sdinfo)
16635 {
16636 #ifndef __lock_lint
16637 	_NOTE(ARGUNUSED(sdinfo))
16638 #endif
16639 
16640 	sata_pkt_t *spkt = spx->txlt_sata_pkt;
16641 	sata_cmd_t *scmd;
16642 	struct buf *bp;
16643 
16644 	/* Operation modes are up to the caller */
16645 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
16646 
16647 	/* Synchronous mode, no callback - may be changed by the caller */
16648 	spkt->satapkt_comp = NULL;
16649 	spkt->satapkt_time = sata_default_pkt_time;
16650 
16651 	scmd = &spkt->satapkt_cmd;
16652 	bcopy(&sata_rle_cmd, scmd, sizeof (sata_cmd_t));
16653 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
16654 
16655 	/*
16656 	 * Allocate dma_able buffer error data.
16657 	 * Buffer allocation will take care of buffer alignment and other DMA
16658 	 * attributes.
16659 	 */
16660 	bp = sata_alloc_local_buffer(spx,
16661 	    sizeof (struct sata_ncq_error_recovery_page));
16662 	if (bp == NULL)
16663 		return (SATA_FAILURE);
16664 
16665 	bp_mapin(bp); /* make data buffer accessible */
16666 	scmd->satacmd_bp = bp;
16667 
16668 	/*
16669 	 * Set-up pointer to the buffer handle, so HBA can sync buffer
16670 	 * before accessing it. Handle is in usual place in translate struct.
16671 	 */
16672 	scmd->satacmd_err_ret_buf_handle = &spx->txlt_buf_dma_handle;
16673 
16674 	ASSERT(scmd->satacmd_num_dma_cookies != 0);
16675 	ASSERT(scmd->satacmd_dma_cookie_list != NULL);
16676 
16677 	return (SATA_SUCCESS);
16678 }
16679 
16680 /*
16681  * sata_xlate_errors() is used to translate (S)ATA error
16682  * information to SCSI information returned in the SCSI
16683  * packet.
16684  */
16685 static void
16686 sata_xlate_errors(sata_pkt_txlate_t *spx)
16687 {
16688 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
16689 	struct scsi_extended_sense *sense;
16690 
16691 	scsipkt->pkt_reason = CMD_INCOMPLETE;
16692 	*scsipkt->pkt_scbp = STATUS_CHECK;
16693 	sense = sata_arq_sense(spx);
16694 
16695 	switch (spx->txlt_sata_pkt->satapkt_reason) {
16696 	case SATA_PKT_PORT_ERROR:
16697 		/*
16698 		 * We have no device data. Assume no data transfered.
16699 		 */
16700 		sense->es_key = KEY_HARDWARE_ERROR;
16701 		break;
16702 
16703 	case SATA_PKT_DEV_ERROR:
16704 		if (spx->txlt_sata_pkt->satapkt_cmd.satacmd_status_reg &
16705 		    SATA_STATUS_ERR) {
16706 			/*
16707 			 * determine dev error reason from error
16708 			 * reg content
16709 			 */
16710 			sata_decode_device_error(spx, sense);
16711 			break;
16712 		}
16713 		/* No extended sense key - no info available */
16714 		break;
16715 
16716 	case SATA_PKT_TIMEOUT:
16717 		scsipkt->pkt_reason = CMD_TIMEOUT;
16718 		scsipkt->pkt_statistics |= STAT_TIMEOUT | STAT_DEV_RESET;
16719 		/* No extended sense key */
16720 		break;
16721 
16722 	case SATA_PKT_ABORTED:
16723 		scsipkt->pkt_reason = CMD_ABORTED;
16724 		scsipkt->pkt_statistics |= STAT_ABORTED;
16725 		/* No extended sense key */
16726 		break;
16727 
16728 	case SATA_PKT_RESET:
16729 		/*
16730 		 * pkt aborted either by an explicit reset request from
16731 		 * a host, or due to error recovery
16732 		 */
16733 		scsipkt->pkt_reason = CMD_RESET;
16734 		scsipkt->pkt_statistics |= STAT_DEV_RESET;
16735 		break;
16736 
16737 	default:
16738 		scsipkt->pkt_reason = CMD_TRAN_ERR;
16739 		break;
16740 	}
16741 }
16742 
16743 
16744 
16745 
16746 /*
16747  * Log sata message
16748  * dev pathname msg line preceeds the logged message.
16749  */
16750 
16751 static	void
16752 sata_log(sata_hba_inst_t *sata_hba_inst, uint_t level, char *fmt, ...)
16753 {
16754 	char pathname[128];
16755 	dev_info_t *dip = NULL;
16756 	va_list ap;
16757 
16758 	mutex_enter(&sata_log_mutex);
16759 
16760 	va_start(ap, fmt);
16761 	(void) vsprintf(sata_log_buf, fmt, ap);
16762 	va_end(ap);
16763 
16764 	if (sata_hba_inst != NULL) {
16765 		dip = SATA_DIP(sata_hba_inst);
16766 		(void) ddi_pathname(dip, pathname);
16767 	} else {
16768 		pathname[0] = 0;
16769 	}
16770 	if (level == CE_CONT) {
16771 		if (sata_debug_flags == 0)
16772 			cmn_err(level, "?%s:\n %s\n", pathname, sata_log_buf);
16773 		else
16774 			cmn_err(level, "%s:\n %s\n", pathname, sata_log_buf);
16775 	} else {
16776 		if (level != CE_NOTE) {
16777 			cmn_err(level, "%s:\n %s", pathname, sata_log_buf);
16778 		} else if (sata_msg) {
16779 			cmn_err(level, "%s:\n %s", pathname,
16780 			    sata_log_buf);
16781 		}
16782 	}
16783 
16784 	/* sata trace debug */
16785 	sata_trace_debug(dip, sata_log_buf);
16786 
16787 	mutex_exit(&sata_log_mutex);
16788 }
16789 
16790 
16791 /* ******** Asynchronous HBA events handling & hotplugging support ******** */
16792 
16793 /*
16794  * Start or terminate the thread, depending on flag arg and current state
16795  */
16796 static void
16797 sata_event_thread_control(int startstop)
16798 {
16799 	static 	int sata_event_thread_terminating = 0;
16800 	static 	int sata_event_thread_starting = 0;
16801 	int i;
16802 
16803 	mutex_enter(&sata_event_mutex);
16804 
16805 	if (startstop == 0 && (sata_event_thread_starting == 1 ||
16806 	    sata_event_thread_terminating == 1)) {
16807 		mutex_exit(&sata_event_mutex);
16808 		return;
16809 	}
16810 	if (startstop == 1 && sata_event_thread_starting == 1) {
16811 		mutex_exit(&sata_event_mutex);
16812 		return;
16813 	}
16814 	if (startstop == 1 && sata_event_thread_terminating == 1) {
16815 		sata_event_thread_starting = 1;
16816 		/* wait til terminate operation completes */
16817 		i = SATA_EVNT_DAEMON_TERM_WAIT/SATA_EVNT_DAEMON_TERM_TIMEOUT;
16818 		while (sata_event_thread_terminating == 1) {
16819 			if (i-- <= 0) {
16820 				sata_event_thread_starting = 0;
16821 				mutex_exit(&sata_event_mutex);
16822 #ifdef SATA_DEBUG
16823 				cmn_err(CE_WARN, "sata_event_thread_control: "
16824 				    "timeout waiting for thread to terminate");
16825 #endif
16826 				return;
16827 			}
16828 			mutex_exit(&sata_event_mutex);
16829 			delay(drv_usectohz(SATA_EVNT_DAEMON_TERM_TIMEOUT));
16830 			mutex_enter(&sata_event_mutex);
16831 		}
16832 	}
16833 	if (startstop == 1) {
16834 		if (sata_event_thread == NULL) {
16835 			sata_event_thread = thread_create(NULL, 0,
16836 			    (void (*)())sata_event_daemon,
16837 			    &sata_hba_list, 0, &p0, TS_RUN, minclsyspri);
16838 		}
16839 		sata_event_thread_starting = 0;
16840 		mutex_exit(&sata_event_mutex);
16841 		return;
16842 	}
16843 
16844 	/*
16845 	 * If we got here, thread may need to be terminated
16846 	 */
16847 	if (sata_event_thread != NULL) {
16848 		int i;
16849 		/* Signal event thread to go away */
16850 		sata_event_thread_terminating = 1;
16851 		sata_event_thread_terminate = 1;
16852 		cv_signal(&sata_event_cv);
16853 		/*
16854 		 * Wait til daemon terminates.
16855 		 */
16856 		i = SATA_EVNT_DAEMON_TERM_WAIT/SATA_EVNT_DAEMON_TERM_TIMEOUT;
16857 		while (sata_event_thread_terminate == 1) {
16858 			mutex_exit(&sata_event_mutex);
16859 			if (i-- <= 0) {
16860 				/* Daemon did not go away !!! */
16861 #ifdef SATA_DEBUG
16862 				cmn_err(CE_WARN, "sata_event_thread_control: "
16863 				    "cannot terminate event daemon thread");
16864 #endif
16865 				mutex_enter(&sata_event_mutex);
16866 				break;
16867 			}
16868 			delay(drv_usectohz(SATA_EVNT_DAEMON_TERM_TIMEOUT));
16869 			mutex_enter(&sata_event_mutex);
16870 		}
16871 		sata_event_thread_terminating = 0;
16872 	}
16873 	ASSERT(sata_event_thread_terminating == 0);
16874 	ASSERT(sata_event_thread_starting == 0);
16875 	mutex_exit(&sata_event_mutex);
16876 }
16877 
16878 
16879 /*
16880  * SATA HBA event notification function.
16881  * Events reported by SATA HBA drivers per HBA instance relate to a change in
16882  * a port and/or device state or a controller itself.
16883  * Events for different addresses/addr types cannot be combined.
16884  * A warning message is generated for each event type.
16885  * Events are not processed by this function, so only the
16886  * event flag(s)is set for an affected entity and the event thread is
16887  * waken up. Event daemon thread processes all events.
16888  *
16889  * NOTE: Since more than one event may be reported at the same time, one
16890  * cannot determine a sequence of events when opposite event are reported, eg.
16891  * LINK_LOST and LINK_ESTABLISHED. Actual port status during event processing
16892  * is taking precedence over reported events, i.e. may cause ignoring some
16893  * events.
16894  */
16895 #define	SATA_EVENT_MAX_MSG_LENGTH	79
16896 
16897 void
16898 sata_hba_event_notify(dev_info_t *dip, sata_device_t *sata_device, int event)
16899 {
16900 	sata_hba_inst_t *sata_hba_inst = NULL;
16901 	sata_address_t *saddr;
16902 	sata_pmult_info_t *pmultinfo;
16903 	sata_drive_info_t *sdinfo;
16904 	sata_port_stats_t *pstats;
16905 	sata_cport_info_t *cportinfo;
16906 	sata_pmport_info_t *pmportinfo;
16907 	int cport, pmport;
16908 	char buf1[SATA_EVENT_MAX_MSG_LENGTH + 1];
16909 	char buf2[SATA_EVENT_MAX_MSG_LENGTH + 1];
16910 	char *lcp;
16911 	static char *err_msg_evnt_1 =
16912 	    "sata_hba_event_notify: invalid port event 0x%x ";
16913 	static char *err_msg_evnt_2 =
16914 	    "sata_hba_event_notify: invalid device event 0x%x ";
16915 	int linkevent;
16916 
16917 	/*
16918 	 * There is a possibility that an event will be generated on HBA
16919 	 * that has not completed attachment or is detaching. We still want
16920 	 * to process events until HBA is detached.
16921 	 */
16922 	mutex_enter(&sata_mutex);
16923 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
16924 	    sata_hba_inst = sata_hba_inst->satahba_next) {
16925 		if (SATA_DIP(sata_hba_inst) == dip)
16926 			if (sata_hba_inst->satahba_attached == 1)
16927 				break;
16928 	}
16929 	mutex_exit(&sata_mutex);
16930 	if (sata_hba_inst == NULL)
16931 		/* HBA not attached */
16932 		return;
16933 
16934 	ASSERT(sata_device != NULL);
16935 
16936 	/*
16937 	 * Validate address before - do not proceed with invalid address.
16938 	 */
16939 	saddr = &sata_device->satadev_addr;
16940 	if (saddr->cport >= SATA_NUM_CPORTS(sata_hba_inst))
16941 		return;
16942 
16943 	cport = saddr->cport;
16944 	pmport = saddr->pmport;
16945 
16946 	buf1[0] = buf2[0] = '\0';
16947 
16948 	/*
16949 	 * If event relates to port or device, check port state.
16950 	 * Port has to be initialized, or we cannot accept an event.
16951 	 */
16952 	if ((saddr->qual & (SATA_ADDR_CPORT | SATA_ADDR_PMPORT |
16953 	    SATA_ADDR_DCPORT | SATA_ADDR_DPMPORT | SATA_ADDR_PMULT)) != 0) {
16954 		mutex_enter(&sata_hba_inst->satahba_mutex);
16955 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
16956 		mutex_exit(&sata_hba_inst->satahba_mutex);
16957 		if (cportinfo == NULL || cportinfo->cport_state == 0)
16958 			return;
16959 	}
16960 
16961 	if ((saddr->qual & (SATA_ADDR_PMULT | SATA_ADDR_PMPORT |
16962 	    SATA_ADDR_DPMPORT)) != 0) {
16963 		if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
16964 			SATA_LOG_D((sata_hba_inst, CE_WARN,
16965 			    "sata_hba_event_notify: Non-pmult device (0x%x)"
16966 			    "is attached to port %d, ignore pmult/pmport "
16967 			    "event 0x%x", cportinfo->cport_dev_type,
16968 			    cport, event));
16969 			return;
16970 		}
16971 
16972 		mutex_enter(&cportinfo->cport_mutex);
16973 		pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
16974 		mutex_exit(&cportinfo->cport_mutex);
16975 
16976 		/*
16977 		 * The daemon might be processing attachment of port
16978 		 * multiplier, in that case we should ignore events on its
16979 		 * sub-devices.
16980 		 *
16981 		 * NOTE: Only pmult_state is checked in sata_hba_event_notify.
16982 		 * The pmport_state is checked by sata daemon.
16983 		 */
16984 		if (pmultinfo == NULL ||
16985 		    pmultinfo->pmult_state == SATA_STATE_UNKNOWN) {
16986 			SATA_LOG_D((sata_hba_inst, CE_WARN,
16987 			    "sata_hba_event_notify: pmult is not"
16988 			    "available at port %d:%d, ignore event 0x%x",
16989 			    cport, pmport, event));
16990 			return;
16991 		}
16992 	}
16993 
16994 	if ((saddr->qual &
16995 	    (SATA_ADDR_PMPORT | SATA_ADDR_DPMPORT)) != 0) {
16996 
16997 		mutex_enter(&cportinfo->cport_mutex);
16998 		if (pmport > SATA_NUM_PMPORTS(sata_hba_inst, cport)) {
16999 			SATA_LOG_D((sata_hba_inst, CE_WARN,
17000 			    "sata_hba_event_notify: invalid/"
17001 			    "un-implemented port %d:%d (%d ports), "
17002 			    "ignore event 0x%x", cport, pmport,
17003 			    SATA_NUM_PMPORTS(sata_hba_inst, cport), event));
17004 			mutex_exit(&cportinfo->cport_mutex);
17005 			return;
17006 		}
17007 		mutex_exit(&cportinfo->cport_mutex);
17008 
17009 		mutex_enter(&sata_hba_inst->satahba_mutex);
17010 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
17011 		    cport, pmport);
17012 		mutex_exit(&sata_hba_inst->satahba_mutex);
17013 
17014 		/* pmport is implemented/valid? */
17015 		if (pmportinfo == NULL) {
17016 			SATA_LOG_D((sata_hba_inst, CE_WARN,
17017 			    "sata_hba_event_notify: invalid/"
17018 			    "un-implemented port %d:%d, ignore "
17019 			    "event 0x%x", cport, pmport, event));
17020 			return;
17021 		}
17022 	}
17023 
17024 	/*
17025 	 * Events refer to devices, ports and controllers - each has
17026 	 * unique address. Events for different addresses cannot be combined.
17027 	 */
17028 	if (saddr->qual & (SATA_ADDR_CPORT | SATA_ADDR_PMPORT)) {
17029 
17030 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17031 
17032 		/* qualify this event(s) */
17033 		if ((event & SATA_EVNT_PORT_EVENTS) == 0) {
17034 			/* Invalid event for the device port */
17035 			(void) sprintf(buf2, err_msg_evnt_1,
17036 			    event & SATA_EVNT_PORT_EVENTS);
17037 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17038 			goto event_info;
17039 		}
17040 		if (saddr->qual == SATA_ADDR_CPORT) {
17041 			/* Controller's device port event */
17042 
17043 			(SATA_CPORT_INFO(sata_hba_inst, cport))->
17044 			    cport_event_flags |=
17045 			    event & SATA_EVNT_PORT_EVENTS;
17046 			pstats =
17047 			    &(SATA_CPORT_INFO(sata_hba_inst, cport))->
17048 			    cport_stats;
17049 		} else {
17050 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17051 			mutex_enter(&pmportinfo->pmport_mutex);
17052 			/* Port multiplier's device port event */
17053 			(SATA_PMPORT_INFO(sata_hba_inst, cport, pmport))->
17054 			    pmport_event_flags |=
17055 			    event & SATA_EVNT_PORT_EVENTS;
17056 			pstats =
17057 			    &(SATA_PMPORT_INFO(sata_hba_inst, cport, pmport))->
17058 			    pmport_stats;
17059 			mutex_exit(&pmportinfo->pmport_mutex);
17060 			mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17061 		}
17062 
17063 		/*
17064 		 * Add to statistics and log the message. We have to do it
17065 		 * here rather than in the event daemon, because there may be
17066 		 * multiple events occuring before they are processed.
17067 		 */
17068 		linkevent = event &
17069 		    (SATA_EVNT_LINK_LOST | SATA_EVNT_LINK_ESTABLISHED);
17070 		if (linkevent) {
17071 			if (linkevent == (SATA_EVNT_LINK_LOST |
17072 			    SATA_EVNT_LINK_ESTABLISHED)) {
17073 				/* This is likely event combination */
17074 				(void) strlcat(buf1, "link lost/established, ",
17075 				    SATA_EVENT_MAX_MSG_LENGTH);
17076 
17077 				if (pstats->link_lost < 0xffffffffffffffffULL)
17078 					pstats->link_lost++;
17079 				if (pstats->link_established <
17080 				    0xffffffffffffffffULL)
17081 					pstats->link_established++;
17082 				linkevent = 0;
17083 			} else if (linkevent & SATA_EVNT_LINK_LOST) {
17084 				(void) strlcat(buf1, "link lost, ",
17085 				    SATA_EVENT_MAX_MSG_LENGTH);
17086 
17087 				if (pstats->link_lost < 0xffffffffffffffffULL)
17088 					pstats->link_lost++;
17089 			} else {
17090 				(void) strlcat(buf1, "link established, ",
17091 				    SATA_EVENT_MAX_MSG_LENGTH);
17092 				if (pstats->link_established <
17093 				    0xffffffffffffffffULL)
17094 					pstats->link_established++;
17095 			}
17096 		}
17097 		if (event & SATA_EVNT_DEVICE_ATTACHED) {
17098 			(void) strlcat(buf1, "device attached, ",
17099 			    SATA_EVENT_MAX_MSG_LENGTH);
17100 			if (pstats->device_attached < 0xffffffffffffffffULL)
17101 				pstats->device_attached++;
17102 		}
17103 		if (event & SATA_EVNT_DEVICE_DETACHED) {
17104 			(void) strlcat(buf1, "device detached, ",
17105 			    SATA_EVENT_MAX_MSG_LENGTH);
17106 			if (pstats->device_detached < 0xffffffffffffffffULL)
17107 				pstats->device_detached++;
17108 		}
17109 		if (event & SATA_EVNT_PWR_LEVEL_CHANGED) {
17110 			SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
17111 			    "port %d power level changed", cport);
17112 			if (pstats->port_pwr_changed < 0xffffffffffffffffULL)
17113 				pstats->port_pwr_changed++;
17114 		}
17115 
17116 		if ((event & ~SATA_EVNT_PORT_EVENTS) != 0) {
17117 			/* There should be no other events for this address */
17118 			(void) sprintf(buf2, err_msg_evnt_1,
17119 			    event & ~SATA_EVNT_PORT_EVENTS);
17120 		}
17121 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17122 
17123 	} else if (saddr->qual & (SATA_ADDR_DCPORT | SATA_ADDR_DPMPORT)) {
17124 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17125 
17126 		/* qualify this event */
17127 		if ((event & SATA_EVNT_DEVICE_RESET) == 0) {
17128 			/* Invalid event for a device */
17129 			(void) sprintf(buf2, err_msg_evnt_2,
17130 			    event & SATA_EVNT_DEVICE_RESET);
17131 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17132 			goto event_info;
17133 		}
17134 		/* drive event */
17135 		sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
17136 		if (sdinfo != NULL) {
17137 			if (event & SATA_EVNT_DEVICE_RESET) {
17138 				(void) strlcat(buf1, "device reset, ",
17139 				    SATA_EVENT_MAX_MSG_LENGTH);
17140 				if (sdinfo->satadrv_stats.drive_reset <
17141 				    0xffffffffffffffffULL)
17142 					sdinfo->satadrv_stats.drive_reset++;
17143 				sdinfo->satadrv_event_flags |=
17144 				    SATA_EVNT_DEVICE_RESET;
17145 			}
17146 		}
17147 		if ((event & ~SATA_EVNT_DEVICE_RESET) != 0) {
17148 			/* Invalid event for a device */
17149 			(void) sprintf(buf2, err_msg_evnt_2,
17150 			    event & ~SATA_EVNT_DRIVE_EVENTS);
17151 		}
17152 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17153 	} else if (saddr->qual == SATA_ADDR_PMULT) {
17154 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17155 
17156 		/* qualify this event */
17157 		if ((event & (SATA_EVNT_DEVICE_RESET |
17158 		    SATA_EVNT_PMULT_LINK_CHANGED)) == 0) {
17159 			/* Invalid event for a port multiplier */
17160 			(void) sprintf(buf2, err_msg_evnt_2,
17161 			    event & SATA_EVNT_DEVICE_RESET);
17162 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17163 			goto event_info;
17164 		}
17165 
17166 		pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
17167 
17168 		if (event & SATA_EVNT_DEVICE_RESET) {
17169 
17170 			SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
17171 			    "[Reset] port-mult on cport %d", cport);
17172 			pmultinfo->pmult_event_flags |=
17173 			    SATA_EVNT_DEVICE_RESET;
17174 			(void) strlcat(buf1, "pmult reset, ",
17175 			    SATA_EVENT_MAX_MSG_LENGTH);
17176 		}
17177 
17178 		if (event & SATA_EVNT_PMULT_LINK_CHANGED) {
17179 
17180 			SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
17181 			    "pmult link changed on cport %d", cport);
17182 			pmultinfo->pmult_event_flags |=
17183 			    SATA_EVNT_PMULT_LINK_CHANGED;
17184 			(void) strlcat(buf1, "pmult link changed, ",
17185 			    SATA_EVENT_MAX_MSG_LENGTH);
17186 		}
17187 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17188 
17189 	} else {
17190 		if (saddr->qual != SATA_ADDR_NULL) {
17191 			/* Wrong address qualifier */
17192 			SATA_LOG_D((sata_hba_inst, CE_WARN,
17193 			    "sata_hba_event_notify: invalid address 0x%x",
17194 			    *(uint32_t *)saddr));
17195 			return;
17196 		}
17197 		if ((event & SATA_EVNT_CONTROLLER_EVENTS) == 0 ||
17198 		    (event & ~SATA_EVNT_CONTROLLER_EVENTS) != 0) {
17199 			/* Invalid event for the controller */
17200 			SATA_LOG_D((sata_hba_inst, CE_WARN,
17201 			    "sata_hba_event_notify: invalid event 0x%x for "
17202 			    "controller",
17203 			    event & SATA_EVNT_CONTROLLER_EVENTS));
17204 			return;
17205 		}
17206 		buf1[0] = '\0';
17207 		/* This may be a frequent and not interesting event */
17208 		SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
17209 		    "controller power level changed\n", NULL);
17210 
17211 		mutex_enter(&sata_hba_inst->satahba_mutex);
17212 		if (sata_hba_inst->satahba_stats.ctrl_pwr_change <
17213 		    0xffffffffffffffffULL)
17214 			sata_hba_inst->satahba_stats.ctrl_pwr_change++;
17215 
17216 		sata_hba_inst->satahba_event_flags |=
17217 		    SATA_EVNT_PWR_LEVEL_CHANGED;
17218 		mutex_exit(&sata_hba_inst->satahba_mutex);
17219 	}
17220 	/*
17221 	 * If we got here, there is something to do with this HBA
17222 	 * instance.
17223 	 */
17224 	mutex_enter(&sata_hba_inst->satahba_mutex);
17225 	sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
17226 	mutex_exit(&sata_hba_inst->satahba_mutex);
17227 	mutex_enter(&sata_mutex);
17228 	sata_event_pending |= SATA_EVNT_MAIN;	/* global event indicator */
17229 	mutex_exit(&sata_mutex);
17230 
17231 	/* Tickle event thread */
17232 	mutex_enter(&sata_event_mutex);
17233 	if (sata_event_thread_active == 0)
17234 		cv_signal(&sata_event_cv);
17235 	mutex_exit(&sata_event_mutex);
17236 
17237 event_info:
17238 	if (buf1[0] != '\0') {
17239 		lcp = strrchr(buf1, ',');
17240 		if (lcp != NULL)
17241 			*lcp = '\0';
17242 	}
17243 	if (saddr->qual == SATA_ADDR_CPORT ||
17244 	    saddr->qual == SATA_ADDR_DCPORT) {
17245 		if (buf1[0] != '\0') {
17246 			sata_log(sata_hba_inst, CE_NOTE, "port %d: %s\n",
17247 			    cport, buf1);
17248 		}
17249 		if (buf2[0] != '\0') {
17250 			sata_log(sata_hba_inst, CE_NOTE, "port %d: %s\n",
17251 			    cport, buf2);
17252 		}
17253 	} else if (saddr->qual == SATA_ADDR_PMPORT ||
17254 	    saddr->qual == SATA_ADDR_DPMPORT) {
17255 		if (buf1[0] != '\0') {
17256 			sata_log(sata_hba_inst, CE_NOTE,
17257 			    "port %d pmport %d: %s\n", cport, pmport, buf1);
17258 		}
17259 		if (buf2[0] != '\0') {
17260 			sata_log(sata_hba_inst, CE_NOTE,
17261 			    "port %d pmport %d: %s\n", cport, pmport, buf2);
17262 		}
17263 	}
17264 }
17265 
17266 
17267 /*
17268  * Event processing thread.
17269  * Arg is a pointer to the sata_hba_list pointer.
17270  * It is not really needed, because sata_hba_list is global and static
17271  */
17272 static void
17273 sata_event_daemon(void *arg)
17274 {
17275 #ifndef __lock_lint
17276 	_NOTE(ARGUNUSED(arg))
17277 #endif
17278 	sata_hba_inst_t *sata_hba_inst;
17279 	clock_t delta;
17280 
17281 	SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
17282 	    "SATA event daemon started\n", NULL);
17283 loop:
17284 	/*
17285 	 * Process events here. Walk through all registered HBAs
17286 	 */
17287 	mutex_enter(&sata_mutex);
17288 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
17289 	    sata_hba_inst = sata_hba_inst->satahba_next) {
17290 		ASSERT(sata_hba_inst != NULL);
17291 		mutex_enter(&sata_hba_inst->satahba_mutex);
17292 		if (sata_hba_inst->satahba_attached == 0 ||
17293 		    (sata_hba_inst->satahba_event_flags &
17294 		    SATA_EVNT_SKIP) != 0) {
17295 			mutex_exit(&sata_hba_inst->satahba_mutex);
17296 			continue;
17297 		}
17298 		if (sata_hba_inst->satahba_event_flags & SATA_EVNT_MAIN) {
17299 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_SKIP;
17300 			mutex_exit(&sata_hba_inst->satahba_mutex);
17301 			mutex_exit(&sata_mutex);
17302 			/* Got the controller with pending event */
17303 			sata_process_controller_events(sata_hba_inst);
17304 			/*
17305 			 * Since global mutex was released, there is a
17306 			 * possibility that HBA list has changed, so start
17307 			 * over from the top. Just processed controller
17308 			 * will be passed-over because of the SKIP flag.
17309 			 */
17310 			goto loop;
17311 		}
17312 		mutex_exit(&sata_hba_inst->satahba_mutex);
17313 	}
17314 	/* Clear SKIP flag in all controllers */
17315 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
17316 	    sata_hba_inst = sata_hba_inst->satahba_next) {
17317 		mutex_enter(&sata_hba_inst->satahba_mutex);
17318 		sata_hba_inst->satahba_event_flags &= ~SATA_EVNT_SKIP;
17319 		mutex_exit(&sata_hba_inst->satahba_mutex);
17320 	}
17321 	mutex_exit(&sata_mutex);
17322 
17323 	SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
17324 	    "SATA EVENT DAEMON suspending itself", NULL);
17325 
17326 #ifdef SATA_DEBUG
17327 	if ((sata_func_enable & SATA_ENABLE_PROCESS_EVENTS) == 0) {
17328 		sata_log(sata_hba_inst, CE_WARN,
17329 		    "SATA EVENTS PROCESSING DISABLED\n");
17330 		thread_exit(); /* Daemon will not run again */
17331 	}
17332 #endif
17333 	mutex_enter(&sata_event_mutex);
17334 	sata_event_thread_active = 0;
17335 	mutex_exit(&sata_event_mutex);
17336 	/*
17337 	 * Go to sleep/suspend itself and wake up either because new event or
17338 	 * wait timeout. Exit if there is a termination request (driver
17339 	 * unload).
17340 	 */
17341 	delta = drv_usectohz(SATA_EVNT_DAEMON_SLEEP_TIME);
17342 	do {
17343 		mutex_enter(&sata_event_mutex);
17344 		(void) cv_reltimedwait(&sata_event_cv, &sata_event_mutex,
17345 		    delta, TR_CLOCK_TICK);
17346 
17347 		if (sata_event_thread_active != 0) {
17348 			mutex_exit(&sata_event_mutex);
17349 			continue;
17350 		}
17351 
17352 		/* Check if it is time to go away */
17353 		if (sata_event_thread_terminate == 1) {
17354 			/*
17355 			 * It is up to the thread setting above flag to make
17356 			 * sure that this thread is not killed prematurely.
17357 			 */
17358 			sata_event_thread_terminate = 0;
17359 			sata_event_thread = NULL;
17360 			mutex_exit(&sata_event_mutex);
17361 			SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
17362 			    "SATA_EVENT_DAEMON_TERMINATING", NULL);
17363 			thread_exit();  { _NOTE(NOT_REACHED) }
17364 		}
17365 		mutex_exit(&sata_event_mutex);
17366 	} while (!(sata_event_pending & SATA_EVNT_MAIN));
17367 
17368 	mutex_enter(&sata_event_mutex);
17369 	sata_event_thread_active = 1;
17370 	mutex_exit(&sata_event_mutex);
17371 
17372 	mutex_enter(&sata_mutex);
17373 	sata_event_pending &= ~SATA_EVNT_MAIN;
17374 	mutex_exit(&sata_mutex);
17375 
17376 	SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
17377 	    "SATA EVENT DAEMON READY TO PROCESS EVENT", NULL);
17378 
17379 	goto loop;
17380 }
17381 
17382 /*
17383  * Specific HBA instance event processing.
17384  *
17385  * NOTE: At the moment, device event processing is limited to hard disks
17386  * only.
17387  * Port multiplier is supported now.
17388  */
17389 static void
17390 sata_process_controller_events(sata_hba_inst_t *sata_hba_inst)
17391 {
17392 	int ncport;
17393 	uint32_t event_flags;
17394 	sata_address_t *saddr;
17395 	sata_cport_info_t *cportinfo;
17396 	sata_pmult_info_t *pmultinfo;
17397 
17398 	SATADBG1(SATA_DBG_EVENTS_CNTRL, sata_hba_inst,
17399 	    "Processing controller %d event(s)",
17400 	    ddi_get_instance(SATA_DIP(sata_hba_inst)));
17401 
17402 	mutex_enter(&sata_hba_inst->satahba_mutex);
17403 	sata_hba_inst->satahba_event_flags &= ~SATA_EVNT_MAIN;
17404 	event_flags = sata_hba_inst->satahba_event_flags;
17405 	mutex_exit(&sata_hba_inst->satahba_mutex);
17406 	/*
17407 	 * Process controller power change first
17408 	 * HERE
17409 	 */
17410 	if (event_flags & SATA_EVNT_PWR_LEVEL_CHANGED)
17411 		sata_process_cntrl_pwr_level_change(sata_hba_inst);
17412 
17413 	/*
17414 	 * Search through ports/devices to identify affected port/device.
17415 	 * We may have to process events for more than one port/device.
17416 	 */
17417 	for (ncport = 0; ncport < SATA_NUM_CPORTS(sata_hba_inst); ncport++) {
17418 		/*
17419 		 * Not all ports may be processed in attach by the time we
17420 		 * get an event. Check if port info is initialized.
17421 		 */
17422 		mutex_enter(&sata_hba_inst->satahba_mutex);
17423 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, ncport);
17424 		mutex_exit(&sata_hba_inst->satahba_mutex);
17425 		if (cportinfo == NULL || cportinfo->cport_state == NULL)
17426 			continue;
17427 
17428 		/* We have initialized controller port info */
17429 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
17430 		event_flags = (SATA_CPORT_INFO(sata_hba_inst, ncport))->
17431 		    cport_event_flags;
17432 		/* Check if port was locked by IOCTL processing */
17433 		if (event_flags & SATA_APCTL_LOCK_PORT_BUSY) {
17434 			/*
17435 			 * We ignore port events because port is busy
17436 			 * with AP control processing. Set again
17437 			 * controller and main event flag, so that
17438 			 * events may be processed by the next daemon
17439 			 * run.
17440 			 */
17441 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
17442 			mutex_enter(&sata_hba_inst->satahba_mutex);
17443 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
17444 			mutex_exit(&sata_hba_inst->satahba_mutex);
17445 			mutex_enter(&sata_mutex);
17446 			sata_event_pending |= SATA_EVNT_MAIN;
17447 			mutex_exit(&sata_mutex);
17448 			SATADBG1(SATA_DBG_EVENTS_PROCPST, sata_hba_inst,
17449 			    "Event processing postponed until "
17450 			    "AP control processing completes",
17451 			    NULL);
17452 			/* Check other ports */
17453 			continue;
17454 		} else {
17455 			/*
17456 			 * Set BSY flag so that AP control would not
17457 			 * interfere with events processing for
17458 			 * this port.
17459 			 */
17460 			(SATA_CPORT_INFO(sata_hba_inst, ncport))->
17461 			    cport_event_flags |= SATA_EVNT_LOCK_PORT_BUSY;
17462 		}
17463 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
17464 
17465 		saddr = &(SATA_CPORT_INFO(sata_hba_inst, ncport))->cport_addr;
17466 
17467 		if ((event_flags &
17468 		    (SATA_EVNT_PORT_EVENTS | SATA_EVNT_DRIVE_EVENTS)) != 0) {
17469 			/*
17470 			 * Got port event.
17471 			 * We need some hierarchy of event processing as they
17472 			 * are affecting each other:
17473 			 * 1. port failed
17474 			 * 2. device detached/attached
17475 			 * 3. link events - link events may trigger device
17476 			 *    detached or device attached events in some
17477 			 *    circumstances.
17478 			 * 4. port power level changed
17479 			 */
17480 			if (event_flags & SATA_EVNT_PORT_FAILED) {
17481 				sata_process_port_failed_event(sata_hba_inst,
17482 				    saddr);
17483 			}
17484 			if (event_flags & SATA_EVNT_DEVICE_DETACHED) {
17485 				sata_process_device_detached(sata_hba_inst,
17486 				    saddr);
17487 			}
17488 			if (event_flags & SATA_EVNT_DEVICE_ATTACHED) {
17489 				sata_process_device_attached(sata_hba_inst,
17490 				    saddr);
17491 			}
17492 			if (event_flags &
17493 			    (SATA_EVNT_LINK_ESTABLISHED |
17494 			    SATA_EVNT_LINK_LOST)) {
17495 				sata_process_port_link_events(sata_hba_inst,
17496 				    saddr);
17497 			}
17498 			if (event_flags & SATA_EVNT_PWR_LEVEL_CHANGED) {
17499 				sata_process_port_pwr_change(sata_hba_inst,
17500 				    saddr);
17501 			}
17502 			if (event_flags & SATA_EVNT_TARGET_NODE_CLEANUP) {
17503 				sata_process_target_node_cleanup(
17504 				    sata_hba_inst, saddr);
17505 			}
17506 			if (event_flags & SATA_EVNT_AUTOONLINE_DEVICE) {
17507 				sata_process_device_autoonline(
17508 				    sata_hba_inst, saddr);
17509 			}
17510 		}
17511 
17512 
17513 		/*
17514 		 * Scan port multiplier and all its sub-ports event flags.
17515 		 * The events are marked by
17516 		 * (1) sata_pmult_info.pmult_event_flags
17517 		 * (2) sata_pmport_info.pmport_event_flags
17518 		 */
17519 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
17520 		if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT) {
17521 			/*
17522 			 * There should be another extra check: this
17523 			 * port multiplier still exists?
17524 			 */
17525 			pmultinfo = SATA_PMULT_INFO(sata_hba_inst,
17526 			    ncport);
17527 
17528 			if (pmultinfo != NULL) {
17529 				mutex_exit(&(SATA_CPORT_MUTEX(
17530 				    sata_hba_inst, ncport)));
17531 				sata_process_pmult_events(
17532 				    sata_hba_inst, ncport);
17533 				mutex_enter(&(SATA_CPORT_MUTEX(
17534 				    sata_hba_inst, ncport)));
17535 			} else {
17536 				SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
17537 				    "Port-multiplier is gone. "
17538 				    "Ignore all sub-device events "
17539 				    "at port %d.", ncport);
17540 			}
17541 		}
17542 
17543 		if ((SATA_CPORT_DEV_TYPE(sata_hba_inst, ncport) !=
17544 		    SATA_DTYPE_NONE) &&
17545 		    (SATA_CPORT_DRV_INFO(sata_hba_inst, ncport) != NULL)) {
17546 			if (SATA_CPORT_DRV_INFO(sata_hba_inst, ncport)->
17547 			    satadrv_event_flags &
17548 			    (SATA_EVNT_DEVICE_RESET |
17549 			    SATA_EVNT_INPROC_DEVICE_RESET)) {
17550 				/* Have device event */
17551 				sata_process_device_reset(sata_hba_inst,
17552 				    saddr);
17553 			}
17554 		}
17555 		/* Release PORT_BUSY flag */
17556 		(SATA_CPORT_INFO(sata_hba_inst, ncport))->
17557 		    cport_event_flags &= ~SATA_EVNT_LOCK_PORT_BUSY;
17558 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
17559 
17560 	} /* End of loop through the controller SATA ports */
17561 }
17562 
17563 /*
17564  * Specific port multiplier instance event processing. At the moment, device
17565  * event processing is limited to link/attach event only.
17566  *
17567  * NOTE: power management event is not supported yet.
17568  */
17569 static void
17570 sata_process_pmult_events(sata_hba_inst_t *sata_hba_inst, uint8_t cport)
17571 {
17572 	sata_cport_info_t *cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
17573 	sata_pmult_info_t *pmultinfo;
17574 	sata_pmport_info_t *pmportinfo;
17575 	sata_address_t *saddr;
17576 	sata_device_t sata_device;
17577 	uint32_t event_flags;
17578 	int npmport;
17579 	int rval;
17580 
17581 	SATADBG2(SATA_DBG_EVENTS_CNTRL|SATA_DBG_PMULT, sata_hba_inst,
17582 	    "Processing pmult event(s) on cport %d of controller %d",
17583 	    cport, ddi_get_instance(SATA_DIP(sata_hba_inst)));
17584 
17585 	/* First process events on port multiplier */
17586 	mutex_enter(&cportinfo->cport_mutex);
17587 	pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
17588 	event_flags = pmultinfo->pmult_event_flags;
17589 
17590 	/*
17591 	 * Reset event (of port multiplier) has higher priority because the
17592 	 * port multiplier itself might be failed or removed after reset.
17593 	 */
17594 	if (event_flags & SATA_EVNT_DEVICE_RESET) {
17595 		/*
17596 		 * The status of the sub-links are uncertain,
17597 		 * so mark all sub-ports as RESET
17598 		 */
17599 		for (npmport = 0; npmport < SATA_NUM_PMPORTS(
17600 		    sata_hba_inst, cport); npmport ++) {
17601 			pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
17602 			    cport, npmport);
17603 			if (pmportinfo == NULL) {
17604 				/* That's weird. */
17605 				SATA_LOG_D((sata_hba_inst, CE_WARN,
17606 				    "sata_hba_event_notify: "
17607 				    "invalid/un-implemented "
17608 				    "port %d:%d (%d ports), ",
17609 				    cport, npmport, SATA_NUM_PMPORTS(
17610 				    sata_hba_inst, cport)));
17611 				continue;
17612 			}
17613 
17614 			mutex_enter(&pmportinfo->pmport_mutex);
17615 
17616 			/* Mark all pmport to unknow state. */
17617 			pmportinfo->pmport_state = SATA_STATE_UNKNOWN;
17618 			/* Mark all pmports with link events. */
17619 			pmportinfo->pmport_event_flags =
17620 			    (SATA_EVNT_LINK_ESTABLISHED|SATA_EVNT_LINK_LOST);
17621 			mutex_exit(&pmportinfo->pmport_mutex);
17622 		}
17623 
17624 	} else if (event_flags & SATA_EVNT_PMULT_LINK_CHANGED) {
17625 		/*
17626 		 * We need probe the port multiplier to know what has
17627 		 * happened.
17628 		 */
17629 		bzero(&sata_device, sizeof (sata_device_t));
17630 		sata_device.satadev_rev = SATA_DEVICE_REV;
17631 		sata_device.satadev_addr.cport = cport;
17632 		sata_device.satadev_addr.pmport = SATA_PMULT_HOSTPORT;
17633 		sata_device.satadev_addr.qual = SATA_ADDR_PMULT;
17634 
17635 		mutex_exit(&cportinfo->cport_mutex);
17636 		rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
17637 		    (SATA_DIP(sata_hba_inst), &sata_device);
17638 		mutex_enter(&cportinfo->cport_mutex);
17639 		if (rval != SATA_SUCCESS) {
17640 			/* Something went wrong? Fail the port */
17641 			cportinfo->cport_state = SATA_PSTATE_FAILED;
17642 			mutex_exit(&cportinfo->cport_mutex);
17643 			SATA_LOG_D((sata_hba_inst, CE_WARN,
17644 			    "SATA port %d probing failed", cport));
17645 
17646 			/* PMult structure must be released.  */
17647 			sata_free_pmult(sata_hba_inst, &sata_device);
17648 			return;
17649 		}
17650 
17651 		sata_update_port_info(sata_hba_inst, &sata_device);
17652 
17653 		/*
17654 		 * Sanity check - Port is active? Is the link active?
17655 		 * The device is still a port multiplier?
17656 		 */
17657 		if ((cportinfo->cport_state &
17658 		    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
17659 		    ((cportinfo->cport_scr.sstatus &
17660 		    SATA_PORT_DEVLINK_UP_MASK) != SATA_PORT_DEVLINK_UP) ||
17661 		    (cportinfo->cport_dev_type != SATA_DTYPE_PMULT)) {
17662 			mutex_exit(&cportinfo->cport_mutex);
17663 
17664 			/* PMult structure must be released.  */
17665 			sata_free_pmult(sata_hba_inst, &sata_device);
17666 			return;
17667 		}
17668 
17669 		/* Probed succeed, set port ready. */
17670 		cportinfo->cport_state |=
17671 		    SATA_STATE_PROBED | SATA_STATE_READY;
17672 	}
17673 
17674 	/* Release port multiplier event flags. */
17675 	pmultinfo->pmult_event_flags &=
17676 	    ~(SATA_EVNT_DEVICE_RESET|SATA_EVNT_PMULT_LINK_CHANGED);
17677 	mutex_exit(&cportinfo->cport_mutex);
17678 
17679 	/*
17680 	 * Check all sub-links.
17681 	 */
17682 	for (npmport = 0; npmport < SATA_NUM_PMPORTS(sata_hba_inst, cport);
17683 	    npmport ++) {
17684 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, npmport);
17685 		mutex_enter(&pmportinfo->pmport_mutex);
17686 		event_flags = pmportinfo->pmport_event_flags;
17687 		mutex_exit(&pmportinfo->pmport_mutex);
17688 		saddr = &pmportinfo->pmport_addr;
17689 
17690 		if ((event_flags &
17691 		    (SATA_EVNT_PORT_EVENTS | SATA_EVNT_DRIVE_EVENTS)) != 0) {
17692 			/*
17693 			 * Got port multiplier port event.
17694 			 * We need some hierarchy of event processing as they
17695 			 * are affecting each other:
17696 			 * 1. device detached/attached
17697 			 * 2. link events - link events may trigger device
17698 			 *    detached or device attached events in some
17699 			 *    circumstances.
17700 			 */
17701 			if (event_flags & SATA_EVNT_DEVICE_DETACHED) {
17702 				sata_process_pmdevice_detached(sata_hba_inst,
17703 				    saddr);
17704 			}
17705 			if (event_flags & SATA_EVNT_DEVICE_ATTACHED) {
17706 				sata_process_pmdevice_attached(sata_hba_inst,
17707 				    saddr);
17708 			}
17709 			if (event_flags & SATA_EVNT_LINK_ESTABLISHED ||
17710 			    event_flags & SATA_EVNT_LINK_LOST) {
17711 				sata_process_pmport_link_events(sata_hba_inst,
17712 				    saddr);
17713 			}
17714 			if (event_flags & SATA_EVNT_TARGET_NODE_CLEANUP) {
17715 				sata_process_target_node_cleanup(
17716 				    sata_hba_inst, saddr);
17717 			}
17718 		}
17719 
17720 		/* Checking drive event(s). */
17721 		mutex_enter(&pmportinfo->pmport_mutex);
17722 		if (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE &&
17723 		    pmportinfo->pmport_sata_drive != NULL) {
17724 			event_flags = pmportinfo->pmport_sata_drive->
17725 			    satadrv_event_flags;
17726 			if (event_flags & (SATA_EVNT_DEVICE_RESET |
17727 			    SATA_EVNT_INPROC_DEVICE_RESET)) {
17728 
17729 				/* Have device event */
17730 				sata_process_pmdevice_reset(sata_hba_inst,
17731 				    saddr);
17732 			}
17733 		}
17734 		mutex_exit(&pmportinfo->pmport_mutex);
17735 
17736 		/* Release PORT_BUSY flag */
17737 		mutex_enter(&cportinfo->cport_mutex);
17738 		cportinfo->cport_event_flags &= ~SATA_EVNT_LOCK_PORT_BUSY;
17739 		mutex_exit(&cportinfo->cport_mutex);
17740 	}
17741 
17742 	SATADBG2(SATA_DBG_EVENTS_CNTRL|SATA_DBG_PMULT, sata_hba_inst,
17743 	    "[DONE] pmult event(s) on cport %d of controller %d",
17744 	    cport, ddi_get_instance(SATA_DIP(sata_hba_inst)));
17745 }
17746 
17747 /*
17748  * Process HBA power level change reported by HBA driver.
17749  * Not implemented at this time - event is ignored.
17750  */
17751 static void
17752 sata_process_cntrl_pwr_level_change(sata_hba_inst_t *sata_hba_inst)
17753 {
17754 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17755 	    "Processing controller power level change", NULL);
17756 
17757 	/* Ignoring it for now */
17758 	mutex_enter(&sata_hba_inst->satahba_mutex);
17759 	sata_hba_inst->satahba_event_flags &= ~SATA_EVNT_PWR_LEVEL_CHANGED;
17760 	mutex_exit(&sata_hba_inst->satahba_mutex);
17761 }
17762 
17763 /*
17764  * Process port power level change reported by HBA driver.
17765  * Not implemented at this time - event is ignored.
17766  */
17767 static void
17768 sata_process_port_pwr_change(sata_hba_inst_t *sata_hba_inst,
17769     sata_address_t *saddr)
17770 {
17771 	sata_cport_info_t *cportinfo;
17772 
17773 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17774 	    "Processing port power level change", NULL);
17775 
17776 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
17777 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17778 	/* Reset event flag */
17779 	cportinfo->cport_event_flags &= ~SATA_EVNT_PWR_LEVEL_CHANGED;
17780 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17781 }
17782 
17783 /*
17784  * Process port failure reported by HBA driver.
17785  * cports support only - no pmports.
17786  */
17787 static void
17788 sata_process_port_failed_event(sata_hba_inst_t *sata_hba_inst,
17789     sata_address_t *saddr)
17790 {
17791 	sata_cport_info_t *cportinfo;
17792 
17793 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
17794 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17795 	/* Reset event flag first */
17796 	cportinfo->cport_event_flags &= ~SATA_EVNT_PORT_FAILED;
17797 	/* If the port is in SHUTDOWN or FAILED state, ignore this event. */
17798 	if ((cportinfo->cport_state &
17799 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) == 0) {
17800 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
17801 		    cport_mutex);
17802 		return;
17803 	}
17804 	/* Fail the port */
17805 	cportinfo->cport_state = SATA_PSTATE_FAILED;
17806 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17807 	sata_log(sata_hba_inst, CE_WARN, "SATA port %d failed", saddr->cport);
17808 }
17809 
17810 /*
17811  * Device Reset Event processing.
17812  * The seqeunce is managed by 3 stage flags:
17813  * - reset event reported,
17814  * - reset event being processed,
17815  * - request to clear device reset state.
17816  *
17817  * NOTE: This function has to be entered with cport mutex held. It exits with
17818  * mutex held as well, but can release mutex during the processing.
17819  */
17820 static void
17821 sata_process_device_reset(sata_hba_inst_t *sata_hba_inst,
17822     sata_address_t *saddr)
17823 {
17824 	sata_drive_info_t old_sdinfo; /* local copy of the drive info */
17825 	sata_drive_info_t *sdinfo;
17826 	sata_cport_info_t *cportinfo;
17827 	sata_device_t sata_device;
17828 	int rval_probe, rval_set;
17829 
17830 	/* We only care about host sata cport for now */
17831 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
17832 	sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst, saddr->cport);
17833 	/*
17834 	 * If the port is in SHUTDOWN or FAILED state, or device is in FAILED
17835 	 * state, ignore reset event.
17836 	 */
17837 	if (((cportinfo->cport_state &
17838 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) ||
17839 	    (sdinfo->satadrv_state & SATA_DSTATE_FAILED) != 0) {
17840 		sdinfo->satadrv_event_flags &=
17841 		    ~(SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET);
17842 		return;
17843 	}
17844 
17845 	if ((SATA_CPORT_DEV_TYPE(sata_hba_inst, saddr->cport) ==
17846 	    SATA_DTYPE_PMULT)) {
17847 		/*
17848 		 * Should not happened: this is already handled in
17849 		 * sata_hba_event_notify()
17850 		 */
17851 		mutex_exit(&cportinfo->cport_mutex);
17852 		goto done;
17853 	}
17854 
17855 	if ((SATA_CPORT_DEV_TYPE(sata_hba_inst, saddr->cport) &
17856 	    SATA_VALID_DEV_TYPE) == 0) {
17857 		/*
17858 		 * This should not happen - coding error.
17859 		 * But we can recover, so do not panic, just clean up
17860 		 * and if in debug mode, log the message.
17861 		 */
17862 #ifdef SATA_DEBUG
17863 		sata_log(sata_hba_inst, CE_WARN,
17864 		    "sata_process_device_reset: "
17865 		    "Invalid device type with sdinfo!", NULL);
17866 #endif
17867 		sdinfo->satadrv_event_flags = 0;
17868 		return;
17869 	}
17870 
17871 #ifdef SATA_DEBUG
17872 	if ((sdinfo->satadrv_event_flags &
17873 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) == 0) {
17874 		/* Nothing to do */
17875 		/* Something is weird - why we are processing dev reset? */
17876 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17877 		    "No device reset event!!!!", NULL);
17878 
17879 		return;
17880 	}
17881 	if ((sdinfo->satadrv_event_flags &
17882 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) ==
17883 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) {
17884 		/* Something is weird - new device reset event */
17885 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17886 		    "Overlapping device reset events!", NULL);
17887 	}
17888 #endif
17889 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17890 	    "Processing port %d device reset", saddr->cport);
17891 
17892 	/* Clear event flag */
17893 	sdinfo->satadrv_event_flags &= ~SATA_EVNT_DEVICE_RESET;
17894 
17895 	/* It seems that we always need to check the port state first */
17896 	sata_device.satadev_rev = SATA_DEVICE_REV;
17897 	sata_device.satadev_addr = *saddr;
17898 	/*
17899 	 * We have to exit mutex, because the HBA probe port function may
17900 	 * block on its own mutex.
17901 	 */
17902 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17903 	rval_probe = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
17904 	    (SATA_DIP(sata_hba_inst), &sata_device);
17905 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17906 	sata_update_port_info(sata_hba_inst, &sata_device);
17907 	if (rval_probe != SATA_SUCCESS) {
17908 		/* Something went wrong? Fail the port */
17909 		cportinfo->cport_state = SATA_PSTATE_FAILED;
17910 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst, saddr->cport);
17911 		if (sdinfo != NULL)
17912 			sdinfo->satadrv_event_flags = 0;
17913 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
17914 		    cport_mutex);
17915 		SATA_LOG_D((sata_hba_inst, CE_WARN,
17916 		    "SATA port %d probing failed",
17917 		    saddr->cport));
17918 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
17919 		    saddr->cport)->cport_mutex);
17920 		return;
17921 	}
17922 	if ((sata_device.satadev_scr.sstatus  &
17923 	    SATA_PORT_DEVLINK_UP_MASK) !=
17924 	    SATA_PORT_DEVLINK_UP ||
17925 	    sata_device.satadev_type == SATA_DTYPE_NONE) {
17926 		/*
17927 		 * No device to process, anymore. Some other event processing
17928 		 * would or have already performed port info cleanup.
17929 		 * To be safe (HBA may need it), request clearing device
17930 		 * reset condition.
17931 		 */
17932 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst, saddr->cport);
17933 		if (sdinfo != NULL) {
17934 			sdinfo->satadrv_event_flags &=
17935 			    ~SATA_EVNT_INPROC_DEVICE_RESET;
17936 			sdinfo->satadrv_event_flags |=
17937 			    SATA_EVNT_CLEAR_DEVICE_RESET;
17938 		}
17939 		return;
17940 	}
17941 
17942 	sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst, saddr->cport);
17943 	if (sdinfo == NULL) {
17944 		return;
17945 	}
17946 	if ((sdinfo->satadrv_event_flags &
17947 	    SATA_EVNT_INPROC_DEVICE_RESET) == 0) {
17948 		/*
17949 		 * Start tracking time for device feature restoration and
17950 		 * identification. Save current time (lbolt value).
17951 		 */
17952 		sdinfo->satadrv_reset_time = ddi_get_lbolt();
17953 	}
17954 	/* Mark device reset processing as active */
17955 	sdinfo->satadrv_event_flags |= SATA_EVNT_INPROC_DEVICE_RESET;
17956 
17957 	old_sdinfo = *sdinfo;	/* local copy of the drive info */
17958 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17959 
17960 	rval_set = sata_set_drive_features(sata_hba_inst, &old_sdinfo, 1);
17961 
17962 	if (rval_set  != SATA_SUCCESS) {
17963 		/*
17964 		 * Restoring drive setting failed.
17965 		 * Probe the port first, to check if the port state has changed
17966 		 */
17967 		sata_device.satadev_rev = SATA_DEVICE_REV;
17968 		sata_device.satadev_addr = *saddr;
17969 		sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
17970 		/* probe port */
17971 		rval_probe = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
17972 		    (SATA_DIP(sata_hba_inst), &sata_device);
17973 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
17974 		    cport_mutex);
17975 		if (rval_probe == SATA_SUCCESS &&
17976 		    (sata_device.satadev_state &
17977 		    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) == 0 &&
17978 		    (sata_device.satadev_scr.sstatus  &
17979 		    SATA_PORT_DEVLINK_UP_MASK) == SATA_PORT_DEVLINK_UP &&
17980 		    sata_device.satadev_type != SATA_DTYPE_NONE) {
17981 			/*
17982 			 * We may retry this a bit later - in-process reset
17983 			 * condition should be already set.
17984 			 * Track retry time for device identification.
17985 			 */
17986 			if ((cportinfo->cport_dev_type &
17987 			    SATA_VALID_DEV_TYPE) != 0 &&
17988 			    SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL &&
17989 			    sdinfo->satadrv_reset_time != 0) {
17990 				clock_t cur_time = ddi_get_lbolt();
17991 				/*
17992 				 * If the retry time limit was not
17993 				 * exceeded, retry.
17994 				 */
17995 				if ((cur_time - sdinfo->satadrv_reset_time) <
17996 				    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
17997 					mutex_enter(
17998 					    &sata_hba_inst->satahba_mutex);
17999 					sata_hba_inst->satahba_event_flags |=
18000 					    SATA_EVNT_MAIN;
18001 					mutex_exit(
18002 					    &sata_hba_inst->satahba_mutex);
18003 					mutex_enter(&sata_mutex);
18004 					sata_event_pending |= SATA_EVNT_MAIN;
18005 					mutex_exit(&sata_mutex);
18006 					return;
18007 				}
18008 				if (rval_set == SATA_RETRY) {
18009 					/*
18010 					 * Setting drive features failed, but
18011 					 * the drive is still accessible,
18012 					 * so emit a warning message before
18013 					 * return.
18014 					 */
18015 					mutex_exit(&SATA_CPORT_INFO(
18016 					    sata_hba_inst,
18017 					    saddr->cport)->cport_mutex);
18018 					goto done;
18019 				}
18020 			}
18021 			/* Fail the drive */
18022 			sdinfo->satadrv_state = SATA_DSTATE_FAILED;
18023 
18024 			sata_log(sata_hba_inst, CE_WARN,
18025 			    "SATA device at port %d - device failed",
18026 			    saddr->cport);
18027 		}
18028 		/*
18029 		 * No point of retrying - device failed or some other event
18030 		 * processing or already did or will do port info cleanup.
18031 		 * To be safe (HBA may need it),
18032 		 * request clearing device reset condition.
18033 		 */
18034 		sdinfo->satadrv_event_flags |= SATA_EVNT_CLEAR_DEVICE_RESET;
18035 		sdinfo->satadrv_event_flags &= ~SATA_EVNT_INPROC_DEVICE_RESET;
18036 		sdinfo->satadrv_reset_time = 0;
18037 		return;
18038 	}
18039 done:
18040 	/*
18041 	 * If setting of drive features failed, but the drive is still
18042 	 * accessible, emit a warning message.
18043 	 */
18044 	if (rval_set == SATA_RETRY) {
18045 		sata_log(sata_hba_inst, CE_WARN,
18046 		    "SATA device at port %d - desired setting could not be "
18047 		    "restored after reset. Device may not operate as expected.",
18048 		    saddr->cport);
18049 	}
18050 	/*
18051 	 * Raise the flag indicating that the next sata command could
18052 	 * be sent with SATA_CLEAR_DEV_RESET_STATE flag, if no new device
18053 	 * reset is reported.
18054 	 */
18055 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18056 	if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
18057 		sdinfo->satadrv_reset_time = 0;
18058 		if ((cportinfo->cport_dev_type & SATA_VALID_DEV_TYPE) != 0) {
18059 			sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
18060 			sdinfo->satadrv_event_flags &=
18061 			    ~SATA_EVNT_INPROC_DEVICE_RESET;
18062 			sdinfo->satadrv_event_flags |=
18063 			    SATA_EVNT_CLEAR_DEVICE_RESET;
18064 		}
18065 	}
18066 }
18067 
18068 
18069 /*
18070  * Port Multiplier Port Device Reset Event processing.
18071  *
18072  * NOTE: This function has to be entered with pmport mutex held. It exits with
18073  * mutex held as well, but can release mutex during the processing.
18074  */
18075 static void
18076 sata_process_pmdevice_reset(sata_hba_inst_t *sata_hba_inst,
18077     sata_address_t *saddr)
18078 {
18079 	sata_drive_info_t old_sdinfo; /* local copy of the drive info */
18080 	sata_drive_info_t *sdinfo = NULL;
18081 	sata_cport_info_t *cportinfo = NULL;
18082 	sata_pmport_info_t *pmportinfo = NULL;
18083 	sata_pmult_info_t *pminfo = NULL;
18084 	sata_device_t sata_device;
18085 	uint8_t cport = saddr->cport;
18086 	uint8_t pmport = saddr->pmport;
18087 	int rval;
18088 
18089 	SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18090 	    "Processing drive reset at port %d:%d", cport, pmport);
18091 
18092 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
18093 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
18094 	sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, cport, pmport);
18095 
18096 	/*
18097 	 * If the port is in SHUTDOWN or FAILED state, or device is in FAILED
18098 	 * state, ignore reset event.
18099 	 */
18100 	if (((cportinfo->cport_state &
18101 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) ||
18102 	    (sdinfo->satadrv_state & SATA_DSTATE_FAILED) != 0) {
18103 		sdinfo->satadrv_event_flags &=
18104 		    ~(SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET);
18105 		return;
18106 	}
18107 
18108 	if ((pmportinfo->pmport_dev_type & SATA_VALID_DEV_TYPE) == 0) {
18109 		/*
18110 		 * This should not happen - coding error.
18111 		 * But we can recover, so do not panic, just clean up
18112 		 * and if in debug mode, log the message.
18113 		 */
18114 #ifdef SATA_DEBUG
18115 		sata_log(sata_hba_inst, CE_WARN,
18116 		    "sata_process_pmdevice_reset: "
18117 		    "Invalid device type with sdinfo!", NULL);
18118 #endif
18119 		sdinfo->satadrv_event_flags = 0;
18120 		return;
18121 	}
18122 
18123 #ifdef SATA_DEBUG
18124 	if ((sdinfo->satadrv_event_flags &
18125 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) == 0) {
18126 		/* Nothing to do */
18127 		/* Something is weird - why we are processing dev reset? */
18128 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18129 		    "No device reset event!!!!", NULL);
18130 
18131 		return;
18132 	}
18133 	if ((sdinfo->satadrv_event_flags &
18134 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) ==
18135 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) {
18136 		/* Something is weird - new device reset event */
18137 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18138 		    "Overlapping device reset events!", NULL);
18139 	}
18140 #endif
18141 	SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18142 	    "Processing port %d:%d device reset", cport, pmport);
18143 
18144 	/* Clear event flag */
18145 	sdinfo->satadrv_event_flags &= ~SATA_EVNT_DEVICE_RESET;
18146 
18147 	/* It seems that we always need to check the port state first */
18148 	sata_device.satadev_rev = SATA_DEVICE_REV;
18149 	sata_device.satadev_addr = *saddr;
18150 	/*
18151 	 * We have to exit mutex, because the HBA probe port function may
18152 	 * block on its own mutex.
18153 	 */
18154 	mutex_exit(&pmportinfo->pmport_mutex);
18155 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18156 	    (SATA_DIP(sata_hba_inst), &sata_device);
18157 	mutex_enter(&pmportinfo->pmport_mutex);
18158 
18159 	sata_update_pmport_info(sata_hba_inst, &sata_device);
18160 	if (rval != SATA_SUCCESS) {
18161 		/* Something went wrong? Fail the port */
18162 		pmportinfo->pmport_state = SATA_PSTATE_FAILED;
18163 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, saddr->cport,
18164 		    saddr->pmport);
18165 		if (sdinfo != NULL)
18166 			sdinfo->satadrv_event_flags = 0;
18167 		mutex_exit(&pmportinfo->pmport_mutex);
18168 		SATA_LOG_D((sata_hba_inst, CE_WARN,
18169 		    "SATA port %d:%d probing failed",
18170 		    saddr->cport, saddr->pmport));
18171 		mutex_enter(&pmportinfo->pmport_mutex);
18172 		return;
18173 	}
18174 	if ((sata_device.satadev_scr.sstatus  &
18175 	    SATA_PORT_DEVLINK_UP_MASK) !=
18176 	    SATA_PORT_DEVLINK_UP ||
18177 	    sata_device.satadev_type == SATA_DTYPE_NONE) {
18178 		/*
18179 		 * No device to process, anymore. Some other event processing
18180 		 * would or have already performed port info cleanup.
18181 		 * To be safe (HBA may need it), request clearing device
18182 		 * reset condition.
18183 		 */
18184 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, saddr->cport,
18185 		    saddr->pmport);
18186 		if (sdinfo != NULL) {
18187 			sdinfo->satadrv_event_flags &=
18188 			    ~SATA_EVNT_INPROC_DEVICE_RESET;
18189 			/* must clear flags on cport */
18190 			pminfo = SATA_PMULT_INFO(sata_hba_inst,
18191 			    saddr->cport);
18192 			pminfo->pmult_event_flags |=
18193 			    SATA_EVNT_CLEAR_DEVICE_RESET;
18194 		}
18195 		return;
18196 	}
18197 
18198 	sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, saddr->cport,
18199 	    saddr->pmport);
18200 	if (sdinfo == NULL) {
18201 		return;
18202 	}
18203 	if ((sdinfo->satadrv_event_flags &
18204 	    SATA_EVNT_INPROC_DEVICE_RESET) == 0) {
18205 		/*
18206 		 * Start tracking time for device feature restoration and
18207 		 * identification. Save current time (lbolt value).
18208 		 */
18209 		sdinfo->satadrv_reset_time = ddi_get_lbolt();
18210 	}
18211 	/* Mark device reset processing as active */
18212 	sdinfo->satadrv_event_flags |= SATA_EVNT_INPROC_DEVICE_RESET;
18213 
18214 	old_sdinfo = *sdinfo;	/* local copy of the drive info */
18215 	mutex_exit(&pmportinfo->pmport_mutex);
18216 
18217 	if (sata_set_drive_features(sata_hba_inst, &old_sdinfo, 1) ==
18218 	    SATA_FAILURE) {
18219 		/*
18220 		 * Restoring drive setting failed.
18221 		 * Probe the port first, to check if the port state has changed
18222 		 */
18223 		sata_device.satadev_rev = SATA_DEVICE_REV;
18224 		sata_device.satadev_addr = *saddr;
18225 		sata_device.satadev_addr.qual = SATA_ADDR_PMPORT;
18226 
18227 		/* probe port */
18228 		rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18229 		    (SATA_DIP(sata_hba_inst), &sata_device);
18230 		mutex_enter(&pmportinfo->pmport_mutex);
18231 		if (rval == SATA_SUCCESS &&
18232 		    (sata_device.satadev_state &
18233 		    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) == 0 &&
18234 		    (sata_device.satadev_scr.sstatus  &
18235 		    SATA_PORT_DEVLINK_UP_MASK) == SATA_PORT_DEVLINK_UP &&
18236 		    sata_device.satadev_type != SATA_DTYPE_NONE) {
18237 			/*
18238 			 * We may retry this a bit later - in-process reset
18239 			 * condition should be already set.
18240 			 * Track retry time for device identification.
18241 			 */
18242 			if ((pmportinfo->pmport_dev_type &
18243 			    SATA_VALID_DEV_TYPE) != 0 &&
18244 			    SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL &&
18245 			    sdinfo->satadrv_reset_time != 0) {
18246 				clock_t cur_time = ddi_get_lbolt();
18247 				/*
18248 				 * If the retry time limit was not
18249 				 * exceeded, retry.
18250 				 */
18251 				if ((cur_time - sdinfo->satadrv_reset_time) <
18252 				    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
18253 					mutex_enter(
18254 					    &sata_hba_inst->satahba_mutex);
18255 					sata_hba_inst->satahba_event_flags |=
18256 					    SATA_EVNT_MAIN;
18257 					mutex_exit(
18258 					    &sata_hba_inst->satahba_mutex);
18259 					mutex_enter(&sata_mutex);
18260 					sata_event_pending |= SATA_EVNT_MAIN;
18261 					mutex_exit(&sata_mutex);
18262 					return;
18263 				}
18264 			}
18265 			/* Fail the drive */
18266 			sdinfo->satadrv_state = SATA_DSTATE_FAILED;
18267 
18268 			sata_log(sata_hba_inst, CE_WARN,
18269 			    "SATA device at port %d:%d - device failed",
18270 			    saddr->cport, saddr->pmport);
18271 		} else {
18272 			/*
18273 			 * No point of retrying - some other event processing
18274 			 * would or already did port info cleanup.
18275 			 * To be safe (HBA may need it),
18276 			 * request clearing device reset condition.
18277 			 */
18278 			sdinfo->satadrv_event_flags |=
18279 			    SATA_EVNT_CLEAR_DEVICE_RESET;
18280 		}
18281 		sdinfo->satadrv_event_flags &= ~SATA_EVNT_INPROC_DEVICE_RESET;
18282 		sdinfo->satadrv_reset_time = 0;
18283 		return;
18284 	}
18285 	/*
18286 	 * Raise the flag indicating that the next sata command could
18287 	 * be sent with SATA_CLEAR_DEV_RESET_STATE flag, if no new device
18288 	 * reset is reported.
18289 	 */
18290 	mutex_enter(&pmportinfo->pmport_mutex);
18291 	if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL) {
18292 		sdinfo->satadrv_reset_time = 0;
18293 		if (pmportinfo->pmport_dev_type & SATA_VALID_DEV_TYPE) {
18294 			sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
18295 			sdinfo->satadrv_event_flags &=
18296 			    ~SATA_EVNT_INPROC_DEVICE_RESET;
18297 			/* must clear flags on cport */
18298 			pminfo = SATA_PMULT_INFO(sata_hba_inst,
18299 			    saddr->cport);
18300 			pminfo->pmult_event_flags |=
18301 			    SATA_EVNT_CLEAR_DEVICE_RESET;
18302 		}
18303 	}
18304 }
18305 
18306 /*
18307  * Port Link Events processing.
18308  * Every link established event may involve device reset (due to
18309  * COMRESET signal, equivalent of the hard reset) so arbitrarily
18310  * set device reset event for an attached device (if any).
18311  * If the port is in SHUTDOWN or FAILED state, ignore link events.
18312  *
18313  * The link established event processing varies, depending on the state
18314  * of the target node, HBA hotplugging capabilities, state of the port.
18315  * If the link is not active, the link established event is ignored.
18316  * If HBA cannot detect device attachment and there is no target node,
18317  * the link established event triggers device attach event processing.
18318  * Else, link established event triggers device reset event processing.
18319  *
18320  * The link lost event processing varies, depending on a HBA hotplugging
18321  * capability and the state of the port (link active or not active).
18322  * If the link is active, the lost link event is ignored.
18323  * If HBA cannot detect device removal, the lost link event triggers
18324  * device detached event processing after link lost timeout.
18325  * Else, the event is ignored.
18326  *
18327  * NOTE: Port multiplier ports events are handled by
18328  * sata_process_pmport_link_events();
18329  */
18330 static void
18331 sata_process_port_link_events(sata_hba_inst_t *sata_hba_inst,
18332     sata_address_t *saddr)
18333 {
18334 	sata_device_t sata_device;
18335 	sata_cport_info_t *cportinfo;
18336 	sata_drive_info_t *sdinfo;
18337 	uint32_t event_flags;
18338 	int rval;
18339 
18340 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18341 	    "Processing port %d link event(s)", saddr->cport);
18342 
18343 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
18344 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18345 	event_flags = cportinfo->cport_event_flags;
18346 
18347 	/* Reset event flags first */
18348 	cportinfo->cport_event_flags &=
18349 	    ~(SATA_EVNT_LINK_ESTABLISHED | SATA_EVNT_LINK_LOST);
18350 
18351 	/* If the port is in SHUTDOWN or FAILED state, ignore link events. */
18352 	if ((cportinfo->cport_state &
18353 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
18354 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18355 		    cport_mutex);
18356 		return;
18357 	}
18358 
18359 	/*
18360 	 * For the sanity sake get current port state.
18361 	 * Set device address only. Other sata_device fields should be
18362 	 * set by HBA driver.
18363 	 */
18364 	sata_device.satadev_rev = SATA_DEVICE_REV;
18365 	sata_device.satadev_addr = *saddr;
18366 	/*
18367 	 * We have to exit mutex, because the HBA probe port function may
18368 	 * block on its own mutex.
18369 	 */
18370 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18371 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18372 	    (SATA_DIP(sata_hba_inst), &sata_device);
18373 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18374 	sata_update_port_info(sata_hba_inst, &sata_device);
18375 	if (rval != SATA_SUCCESS) {
18376 		/* Something went wrong? Fail the port */
18377 		cportinfo->cport_state = SATA_PSTATE_FAILED;
18378 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18379 		    cport_mutex);
18380 		SATA_LOG_D((sata_hba_inst, CE_WARN,
18381 		    "SATA port %d probing failed",
18382 		    saddr->cport));
18383 		/*
18384 		 * We may want to release device info structure, but
18385 		 * it is not necessary.
18386 		 */
18387 		return;
18388 	} else {
18389 		/* port probed successfully */
18390 		cportinfo->cport_state |= SATA_STATE_PROBED | SATA_STATE_READY;
18391 	}
18392 	if (event_flags & SATA_EVNT_LINK_ESTABLISHED) {
18393 
18394 		if ((sata_device.satadev_scr.sstatus &
18395 		    SATA_PORT_DEVLINK_UP_MASK) != SATA_PORT_DEVLINK_UP) {
18396 			/* Ignore event */
18397 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18398 			    "Ignoring port %d link established event - "
18399 			    "link down",
18400 			    saddr->cport);
18401 			goto linklost;
18402 		}
18403 
18404 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18405 		    "Processing port %d link established event",
18406 		    saddr->cport);
18407 
18408 		/*
18409 		 * For the sanity sake check if a device is attached - check
18410 		 * return state of a port probing.
18411 		 */
18412 		if (sata_device.satadev_type != SATA_DTYPE_NONE) {
18413 			/*
18414 			 * HBA port probe indicated that there is a device
18415 			 * attached. Check if the framework had device info
18416 			 * structure attached for this device.
18417 			 */
18418 			if (cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
18419 				ASSERT(SATA_CPORTINFO_DRV_INFO(cportinfo) !=
18420 				    NULL);
18421 
18422 				sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
18423 				if ((sdinfo->satadrv_type &
18424 				    SATA_VALID_DEV_TYPE) != 0) {
18425 					/*
18426 					 * Dev info structure is present.
18427 					 * If dev_type is set to known type in
18428 					 * the framework's drive info struct
18429 					 * then the device existed before and
18430 					 * the link was probably lost
18431 					 * momentarily - in such case
18432 					 * we may want to check device
18433 					 * identity.
18434 					 * Identity check is not supported now.
18435 					 *
18436 					 * Link established event
18437 					 * triggers device reset event.
18438 					 */
18439 					(SATA_CPORTINFO_DRV_INFO(cportinfo))->
18440 					    satadrv_event_flags |=
18441 					    SATA_EVNT_DEVICE_RESET;
18442 				}
18443 			} else if (cportinfo->cport_dev_type ==
18444 			    SATA_DTYPE_NONE) {
18445 				/*
18446 				 * We got new device attached! If HBA does not
18447 				 * generate device attached events, trigger it
18448 				 * here.
18449 				 */
18450 				if (!(SATA_FEATURES(sata_hba_inst) &
18451 				    SATA_CTLF_HOTPLUG)) {
18452 					cportinfo->cport_event_flags |=
18453 					    SATA_EVNT_DEVICE_ATTACHED;
18454 				}
18455 			}
18456 			/* Reset link lost timeout */
18457 			cportinfo->cport_link_lost_time = 0;
18458 		}
18459 	}
18460 linklost:
18461 	if (event_flags & SATA_EVNT_LINK_LOST) {
18462 		if ((sata_device.satadev_scr.sstatus &
18463 		    SATA_PORT_DEVLINK_UP_MASK) == SATA_PORT_DEVLINK_UP) {
18464 			/* Ignore event */
18465 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18466 			    "Ignoring port %d link lost event - link is up",
18467 			    saddr->cport);
18468 			goto done;
18469 		}
18470 #ifdef SATA_DEBUG
18471 		if (cportinfo->cport_link_lost_time == 0) {
18472 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18473 			    "Processing port %d link lost event",
18474 			    saddr->cport);
18475 		}
18476 #endif
18477 		/*
18478 		 * When HBA cannot generate device attached/detached events,
18479 		 * we need to track link lost time and eventually generate
18480 		 * device detach event.
18481 		 */
18482 		if (!(SATA_FEATURES(sata_hba_inst) & SATA_CTLF_HOTPLUG)) {
18483 			/* We are tracking link lost time */
18484 			if (cportinfo->cport_link_lost_time == 0) {
18485 				/* save current time (lbolt value) */
18486 				cportinfo->cport_link_lost_time =
18487 				    ddi_get_lbolt();
18488 				/* just keep link lost event */
18489 				cportinfo->cport_event_flags |=
18490 				    SATA_EVNT_LINK_LOST;
18491 			} else {
18492 				clock_t cur_time = ddi_get_lbolt();
18493 				if ((cur_time -
18494 				    cportinfo->cport_link_lost_time) >=
18495 				    drv_usectohz(
18496 				    SATA_EVNT_LINK_LOST_TIMEOUT)) {
18497 					/* trigger device detach event */
18498 					cportinfo->cport_event_flags |=
18499 					    SATA_EVNT_DEVICE_DETACHED;
18500 					cportinfo->cport_link_lost_time = 0;
18501 					SATADBG1(SATA_DBG_EVENTS,
18502 					    sata_hba_inst,
18503 					    "Triggering port %d "
18504 					    "device detached event",
18505 					    saddr->cport);
18506 				} else {
18507 					/* keep link lost event */
18508 					cportinfo->cport_event_flags |=
18509 					    SATA_EVNT_LINK_LOST;
18510 				}
18511 			}
18512 		}
18513 		/*
18514 		 * We could change port state to disable/delay access to
18515 		 * the attached device until the link is recovered.
18516 		 */
18517 	}
18518 done:
18519 	event_flags = cportinfo->cport_event_flags;
18520 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18521 	if (event_flags != 0) {
18522 		mutex_enter(&sata_hba_inst->satahba_mutex);
18523 		sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
18524 		mutex_exit(&sata_hba_inst->satahba_mutex);
18525 		mutex_enter(&sata_mutex);
18526 		sata_event_pending |= SATA_EVNT_MAIN;
18527 		mutex_exit(&sata_mutex);
18528 	}
18529 }
18530 
18531 /*
18532  * Port Multiplier Port Link Events processing.
18533  */
18534 static void
18535 sata_process_pmport_link_events(sata_hba_inst_t *sata_hba_inst,
18536     sata_address_t *saddr)
18537 {
18538 	sata_device_t sata_device;
18539 	sata_pmport_info_t *pmportinfo = NULL;
18540 	sata_drive_info_t *sdinfo = NULL;
18541 	uint32_t event_flags;
18542 	uint8_t cport = saddr->cport;
18543 	uint8_t pmport = saddr->pmport;
18544 	int rval;
18545 
18546 	SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18547 	    "Processing port %d:%d link event(s)",
18548 	    cport, pmport);
18549 
18550 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
18551 	mutex_enter(&pmportinfo->pmport_mutex);
18552 	event_flags = pmportinfo->pmport_event_flags;
18553 
18554 	/* Reset event flags first */
18555 	pmportinfo->pmport_event_flags &=
18556 	    ~(SATA_EVNT_LINK_ESTABLISHED | SATA_EVNT_LINK_LOST);
18557 
18558 	/* If the port is in SHUTDOWN or FAILED state, ignore link events. */
18559 	if ((pmportinfo->pmport_state &
18560 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
18561 		mutex_exit(&pmportinfo->pmport_mutex);
18562 		return;
18563 	}
18564 
18565 	/*
18566 	 * For the sanity sake get current port state.
18567 	 * Set device address only. Other sata_device fields should be
18568 	 * set by HBA driver.
18569 	 */
18570 	sata_device.satadev_rev = SATA_DEVICE_REV;
18571 	sata_device.satadev_addr = *saddr;
18572 	/*
18573 	 * We have to exit mutex, because the HBA probe port function may
18574 	 * block on its own mutex.
18575 	 */
18576 	mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, saddr->cport,
18577 	    saddr->pmport));
18578 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18579 	    (SATA_DIP(sata_hba_inst), &sata_device);
18580 	mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst, saddr->cport,
18581 	    saddr->pmport));
18582 	sata_update_pmport_info(sata_hba_inst, &sata_device);
18583 	if (rval != SATA_SUCCESS) {
18584 		/* Something went wrong? Fail the port */
18585 		pmportinfo->pmport_state = SATA_PSTATE_FAILED;
18586 		mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, saddr->cport,
18587 		    saddr->pmport));
18588 		SATA_LOG_D((sata_hba_inst, CE_WARN,
18589 		    "SATA port %d:%d probing failed",
18590 		    saddr->cport, saddr->pmport));
18591 		/*
18592 		 * We may want to release device info structure, but
18593 		 * it is not necessary.
18594 		 */
18595 		return;
18596 	} else {
18597 		/* port probed successfully */
18598 		pmportinfo->pmport_state |=
18599 		    SATA_STATE_PROBED | SATA_STATE_READY;
18600 	}
18601 	mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst,
18602 	    saddr->cport, saddr->pmport));
18603 	mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst,
18604 	    saddr->cport, saddr->pmport));
18605 	if (event_flags & SATA_EVNT_LINK_ESTABLISHED) {
18606 
18607 		if ((sata_device.satadev_scr.sstatus &
18608 		    SATA_PORT_DEVLINK_UP_MASK) != SATA_PORT_DEVLINK_UP) {
18609 			/* Ignore event */
18610 			SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18611 			    "Ignoring port %d:%d link established event - "
18612 			    "link down",
18613 			    saddr->cport, saddr->pmport);
18614 			goto linklost;
18615 		}
18616 
18617 		SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18618 		    "Processing port %d:%d link established event",
18619 		    cport, pmport);
18620 
18621 		/*
18622 		 * For the sanity sake check if a device is attached - check
18623 		 * return state of a port probing.
18624 		 */
18625 		if (sata_device.satadev_type != SATA_DTYPE_NONE &&
18626 		    sata_device.satadev_type != SATA_DTYPE_PMULT) {
18627 			/*
18628 			 * HBA port probe indicated that there is a device
18629 			 * attached. Check if the framework had device info
18630 			 * structure attached for this device.
18631 			 */
18632 			if (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE) {
18633 				ASSERT(SATA_PMPORTINFO_DRV_INFO(pmportinfo) !=
18634 				    NULL);
18635 
18636 				sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
18637 				if ((sdinfo->satadrv_type &
18638 				    SATA_VALID_DEV_TYPE) != 0) {
18639 					/*
18640 					 * Dev info structure is present.
18641 					 * If dev_type is set to known type in
18642 					 * the framework's drive info struct
18643 					 * then the device existed before and
18644 					 * the link was probably lost
18645 					 * momentarily - in such case
18646 					 * we may want to check device
18647 					 * identity.
18648 					 * Identity check is not supported now.
18649 					 *
18650 					 * Link established event
18651 					 * triggers device reset event.
18652 					 */
18653 					(SATA_PMPORTINFO_DRV_INFO(pmportinfo))->
18654 					    satadrv_event_flags |=
18655 					    SATA_EVNT_DEVICE_RESET;
18656 				}
18657 			} else if (pmportinfo->pmport_dev_type ==
18658 			    SATA_DTYPE_NONE) {
18659 				/*
18660 				 * We got new device attached! If HBA does not
18661 				 * generate device attached events, trigger it
18662 				 * here.
18663 				 */
18664 				if (!(SATA_FEATURES(sata_hba_inst) &
18665 				    SATA_CTLF_HOTPLUG)) {
18666 					pmportinfo->pmport_event_flags |=
18667 					    SATA_EVNT_DEVICE_ATTACHED;
18668 				}
18669 			}
18670 			/* Reset link lost timeout */
18671 			pmportinfo->pmport_link_lost_time = 0;
18672 		}
18673 	}
18674 linklost:
18675 	if (event_flags & SATA_EVNT_LINK_LOST) {
18676 #ifdef SATA_DEBUG
18677 		if (pmportinfo->pmport_link_lost_time == 0) {
18678 			SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18679 			    "Processing port %d:%d link lost event",
18680 			    saddr->cport, saddr->pmport);
18681 		}
18682 #endif
18683 		if ((sata_device.satadev_scr.sstatus &
18684 		    SATA_PORT_DEVLINK_UP_MASK) == SATA_PORT_DEVLINK_UP) {
18685 			/* Ignore event */
18686 			SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18687 			    "Ignoring port %d:%d link lost event - link is up",
18688 			    saddr->cport, saddr->pmport);
18689 			goto done;
18690 		}
18691 		/*
18692 		 * When HBA cannot generate device attached/detached events,
18693 		 * we need to track link lost time and eventually generate
18694 		 * device detach event.
18695 		 */
18696 		if (!(SATA_FEATURES(sata_hba_inst) & SATA_CTLF_HOTPLUG)) {
18697 			/* We are tracking link lost time */
18698 			if (pmportinfo->pmport_link_lost_time == 0) {
18699 				/* save current time (lbolt value) */
18700 				pmportinfo->pmport_link_lost_time =
18701 				    ddi_get_lbolt();
18702 				/* just keep link lost event */
18703 				pmportinfo->pmport_event_flags |=
18704 				    SATA_EVNT_LINK_LOST;
18705 			} else {
18706 				clock_t cur_time = ddi_get_lbolt();
18707 				if ((cur_time -
18708 				    pmportinfo->pmport_link_lost_time) >=
18709 				    drv_usectohz(
18710 				    SATA_EVNT_LINK_LOST_TIMEOUT)) {
18711 					/* trigger device detach event */
18712 					pmportinfo->pmport_event_flags |=
18713 					    SATA_EVNT_DEVICE_DETACHED;
18714 					pmportinfo->pmport_link_lost_time = 0;
18715 					SATADBG2(SATA_DBG_EVENTS,
18716 					    sata_hba_inst,
18717 					    "Triggering port %d:%d "
18718 					    "device detached event",
18719 					    saddr->cport, saddr->pmport);
18720 				} else {
18721 					/* keep link lost event */
18722 					pmportinfo->pmport_event_flags |=
18723 					    SATA_EVNT_LINK_LOST;
18724 				}
18725 			}
18726 		}
18727 		/*
18728 		 * We could change port state to disable/delay access to
18729 		 * the attached device until the link is recovered.
18730 		 */
18731 	}
18732 done:
18733 	event_flags = pmportinfo->pmport_event_flags;
18734 	mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, saddr->cport,
18735 	    saddr->pmport));
18736 	if (event_flags != 0) {
18737 		mutex_enter(&sata_hba_inst->satahba_mutex);
18738 		sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
18739 		mutex_exit(&sata_hba_inst->satahba_mutex);
18740 		mutex_enter(&sata_mutex);
18741 		sata_event_pending |= SATA_EVNT_MAIN;
18742 		mutex_exit(&sata_mutex);
18743 	}
18744 }
18745 
18746 /*
18747  * Device Detached Event processing.
18748  * Port is probed to find if a device is really gone. If so,
18749  * the device info structure is detached from the SATA port info structure
18750  * and released.
18751  * Port status is updated.
18752  *
18753  * NOTE: Port multiplier ports events are handled by
18754  * sata_process_pmdevice_detached()
18755  */
18756 static void
18757 sata_process_device_detached(sata_hba_inst_t *sata_hba_inst,
18758     sata_address_t *saddr)
18759 {
18760 	sata_cport_info_t *cportinfo;
18761 	sata_pmport_info_t *pmportinfo;
18762 	sata_drive_info_t *sdevinfo;
18763 	sata_device_t sata_device;
18764 	sata_address_t pmport_addr;
18765 	char name[16];
18766 	uint8_t cport = saddr->cport;
18767 	int npmport;
18768 	int rval;
18769 
18770 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18771 	    "Processing port %d device detached", saddr->cport);
18772 
18773 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
18774 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18775 	/* Clear event flag */
18776 	cportinfo->cport_event_flags &= ~SATA_EVNT_DEVICE_DETACHED;
18777 
18778 	/* If the port is in SHUTDOWN or FAILED state, ignore detach event. */
18779 	if ((cportinfo->cport_state &
18780 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
18781 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18782 		    cport_mutex);
18783 		return;
18784 	}
18785 	/* For sanity, re-probe the port */
18786 	sata_device.satadev_rev = SATA_DEVICE_REV;
18787 	sata_device.satadev_addr = *saddr;
18788 
18789 	/*
18790 	 * We have to exit mutex, because the HBA probe port function may
18791 	 * block on its own mutex.
18792 	 */
18793 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18794 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18795 	    (SATA_DIP(sata_hba_inst), &sata_device);
18796 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18797 	sata_update_port_info(sata_hba_inst, &sata_device);
18798 	if (rval != SATA_SUCCESS) {
18799 		/* Something went wrong? Fail the port */
18800 		cportinfo->cport_state = SATA_PSTATE_FAILED;
18801 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18802 		    cport_mutex);
18803 		SATA_LOG_D((sata_hba_inst, CE_WARN,
18804 		    "SATA port %d probing failed",
18805 		    saddr->cport));
18806 		/*
18807 		 * We may want to release device info structure, but
18808 		 * it is not necessary.
18809 		 */
18810 		return;
18811 	} else {
18812 		/* port probed successfully */
18813 		cportinfo->cport_state |= SATA_STATE_PROBED | SATA_STATE_READY;
18814 	}
18815 	/*
18816 	 * Check if a device is still attached. For sanity, check also
18817 	 * link status - if no link, there is no device.
18818 	 */
18819 	if ((sata_device.satadev_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) ==
18820 	    SATA_PORT_DEVLINK_UP && sata_device.satadev_type !=
18821 	    SATA_DTYPE_NONE) {
18822 		/*
18823 		 * Device is still attached - ignore detach event.
18824 		 */
18825 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18826 		    cport_mutex);
18827 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18828 		    "Ignoring detach - device still attached to port %d",
18829 		    sata_device.satadev_addr.cport);
18830 		return;
18831 	}
18832 	/*
18833 	 * We need to detach and release device info structure here
18834 	 */
18835 	if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT) {
18836 		/*
18837 		 * A port-multiplier is removed.
18838 		 *
18839 		 * Calling sata_process_pmdevice_detached() does not work
18840 		 * here. The port multiplier is gone, so we cannot probe
18841 		 * sub-port any more and all pmult-related data structure must
18842 		 * be de-allocated immediately. Following structure of every
18843 		 * implemented sub-port behind the pmult are required to
18844 		 * released.
18845 		 *
18846 		 *   - attachment point
18847 		 *   - target node
18848 		 *   - sata_drive_info
18849 		 *   - sata_pmport_info
18850 		 */
18851 		for (npmport = 0; npmport < SATA_NUM_PMPORTS(sata_hba_inst,
18852 		    cport); npmport ++) {
18853 			SATADBG2(SATA_DBG_PMULT|SATA_DBG_EVENTS_PROC,
18854 			    sata_hba_inst,
18855 			    "Detaching target node at port %d:%d",
18856 			    cport, npmport);
18857 
18858 			mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
18859 
18860 			/* Remove attachment point. */
18861 			name[0] = '\0';
18862 			(void) sprintf(name, "%d.%d", cport, npmport);
18863 			ddi_remove_minor_node(SATA_DIP(sata_hba_inst), name);
18864 			sata_log(sata_hba_inst, CE_NOTE,
18865 			    "Remove attachment point of port %d:%d",
18866 			    cport, npmport);
18867 
18868 			/* Remove target node */
18869 			pmport_addr.cport = cport;
18870 			pmport_addr.pmport = (uint8_t)npmport;
18871 			pmport_addr.qual = SATA_ADDR_PMPORT;
18872 			sata_remove_target_node(sata_hba_inst, &pmport_addr);
18873 
18874 			mutex_enter(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
18875 
18876 			/* Release sata_pmport_info & sata_drive_info. */
18877 			pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
18878 			    cport, npmport);
18879 			ASSERT(pmportinfo != NULL);
18880 
18881 			sdevinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
18882 			if (sdevinfo != NULL) {
18883 				(void) kmem_free((void *) sdevinfo,
18884 				    sizeof (sata_drive_info_t));
18885 			}
18886 
18887 			/* Release sata_pmport_info at last */
18888 			(void) kmem_free((void *) pmportinfo,
18889 			    sizeof (sata_pmport_info_t));
18890 		}
18891 
18892 		/* Finally, release sata_pmult_info */
18893 		(void) kmem_free((void *)
18894 		    SATA_CPORTINFO_PMULT_INFO(cportinfo),
18895 		    sizeof (sata_pmult_info_t));
18896 		SATA_CPORTINFO_PMULT_INFO(cportinfo) = NULL;
18897 
18898 		sata_log(sata_hba_inst, CE_WARN,
18899 		    "SATA port-multiplier detached at port %d", cport);
18900 
18901 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
18902 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
18903 		    saddr->cport)->cport_mutex);
18904 	} else {
18905 		if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
18906 			sdevinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
18907 			SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
18908 			(void) kmem_free((void *)sdevinfo,
18909 			    sizeof (sata_drive_info_t));
18910 		}
18911 		sata_log(sata_hba_inst, CE_WARN,
18912 		    "SATA device detached at port %d", cport);
18913 
18914 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
18915 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
18916 		    saddr->cport)->cport_mutex);
18917 
18918 		/*
18919 		 * Try to offline a device and remove target node
18920 		 * if it still exists
18921 		 */
18922 		sata_remove_target_node(sata_hba_inst, saddr);
18923 	}
18924 
18925 
18926 	/*
18927 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
18928 	 * with the hint: SE_HINT_REMOVE
18929 	 */
18930 	sata_gen_sysevent(sata_hba_inst, saddr, SE_HINT_REMOVE);
18931 }
18932 
18933 /*
18934  * Port Multiplier Port Device Deattached Event processing.
18935  *
18936  * NOTE: No Mutex should be hold.
18937  */
18938 static void
18939 sata_process_pmdevice_detached(sata_hba_inst_t *sata_hba_inst,
18940     sata_address_t *saddr)
18941 {
18942 	sata_pmport_info_t *pmportinfo;
18943 	sata_drive_info_t *sdevinfo;
18944 	sata_device_t sata_device;
18945 	int rval;
18946 	uint8_t cport, pmport;
18947 
18948 	cport = saddr->cport;
18949 	pmport = saddr->pmport;
18950 
18951 	SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18952 	    "Processing port %d:%d device detached",
18953 	    cport, pmport);
18954 
18955 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
18956 	mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
18957 
18958 	/* Clear event flag */
18959 	pmportinfo->pmport_event_flags &= ~SATA_EVNT_DEVICE_DETACHED;
18960 
18961 	/* If the port is in SHUTDOWN or FAILED state, ignore detach event. */
18962 	if ((pmportinfo->pmport_state &
18963 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
18964 		mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
18965 		return;
18966 	}
18967 	/* For sanity, re-probe the port */
18968 	sata_device.satadev_rev = SATA_DEVICE_REV;
18969 	sata_device.satadev_addr = *saddr;
18970 
18971 	/*
18972 	 * We have to exit mutex, because the HBA probe port function may
18973 	 * block on its own mutex.
18974 	 */
18975 	mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
18976 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18977 	    (SATA_DIP(sata_hba_inst), &sata_device);
18978 	mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
18979 	sata_update_pmport_info(sata_hba_inst, &sata_device);
18980 	if (rval != SATA_SUCCESS) {
18981 		/* Something went wrong? Fail the port */
18982 		pmportinfo->pmport_state = SATA_PSTATE_FAILED;
18983 		mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
18984 		SATA_LOG_D((sata_hba_inst, CE_WARN,
18985 		    "SATA port %d:%d probing failed",
18986 		    saddr->pmport));
18987 		/*
18988 		 * We may want to release device info structure, but
18989 		 * it is not necessary.
18990 		 */
18991 		return;
18992 	} else {
18993 		/* port probed successfully */
18994 		pmportinfo->pmport_state |=
18995 		    SATA_STATE_PROBED | SATA_STATE_READY;
18996 	}
18997 	/*
18998 	 * Check if a device is still attached. For sanity, check also
18999 	 * link status - if no link, there is no device.
19000 	 */
19001 	if ((sata_device.satadev_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) ==
19002 	    SATA_PORT_DEVLINK_UP && sata_device.satadev_type !=
19003 	    SATA_DTYPE_NONE) {
19004 		/*
19005 		 * Device is still attached - ignore detach event.
19006 		 */
19007 		mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
19008 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19009 		    "Ignoring detach - device still attached to port %d",
19010 		    sata_device.satadev_addr.pmport);
19011 		return;
19012 	}
19013 	/*
19014 	 * We need to detach and release device info structure here
19015 	 */
19016 	if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL) {
19017 		sdevinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
19018 		SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
19019 		(void) kmem_free((void *)sdevinfo,
19020 		    sizeof (sata_drive_info_t));
19021 	}
19022 	pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
19023 	/*
19024 	 * Device cannot be reached anymore, even if the target node may be
19025 	 * still present.
19026 	 */
19027 	mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
19028 
19029 	/*
19030 	 * Try to offline a device and remove target node if it still exists
19031 	 */
19032 	sata_remove_target_node(sata_hba_inst, saddr);
19033 
19034 	/*
19035 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
19036 	 * with the hint: SE_HINT_REMOVE
19037 	 */
19038 	sata_gen_sysevent(sata_hba_inst, saddr, SE_HINT_REMOVE);
19039 }
19040 
19041 
19042 /*
19043  * Device Attached Event processing.
19044  * Port state is checked to verify that a device is really attached. If so,
19045  * the device info structure is created and attached to the SATA port info
19046  * structure.
19047  *
19048  * If attached device cannot be identified or set-up, the retry for the
19049  * attach processing is set-up. Subsequent daemon run would try again to
19050  * identify the device, until the time limit is reached
19051  * (SATA_DEV_IDENTIFY_TIMEOUT).
19052  *
19053  * This function cannot be called in interrupt context (it may sleep).
19054  *
19055  * NOTE: Port multiplier ports events are handled by
19056  * sata_process_pmdevice_attached()
19057  */
19058 static void
19059 sata_process_device_attached(sata_hba_inst_t *sata_hba_inst,
19060     sata_address_t *saddr)
19061 {
19062 	sata_cport_info_t *cportinfo = NULL;
19063 	sata_drive_info_t *sdevinfo = NULL;
19064 	sata_pmult_info_t *pmultinfo = NULL;
19065 	sata_pmport_info_t *pmportinfo = NULL;
19066 	sata_device_t sata_device;
19067 	dev_info_t *tdip;
19068 	uint32_t event_flags = 0, pmult_event_flags = 0;
19069 	int rval;
19070 	int npmport;
19071 
19072 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19073 	    "Processing port %d device attached", saddr->cport);
19074 
19075 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
19076 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19077 
19078 	/* Clear attach event flag first */
19079 	cportinfo->cport_event_flags &= ~SATA_EVNT_DEVICE_ATTACHED;
19080 
19081 	/* If the port is in SHUTDOWN or FAILED state, ignore event. */
19082 	if ((cportinfo->cport_state &
19083 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
19084 		cportinfo->cport_dev_attach_time = 0;
19085 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
19086 		    cport_mutex);
19087 		return;
19088 	}
19089 
19090 	/*
19091 	 * If the sata_drive_info structure is found attached to the port info,
19092 	 * despite the fact the device was removed and now it is re-attached,
19093 	 * the old drive info structure was not removed.
19094 	 * Arbitrarily release device info structure.
19095 	 */
19096 	if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
19097 		sdevinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
19098 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
19099 		(void) kmem_free((void *)sdevinfo,
19100 		    sizeof (sata_drive_info_t));
19101 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19102 		    "Arbitrarily detaching old device info.", NULL);
19103 	}
19104 	cportinfo->cport_dev_type = SATA_DTYPE_NONE;
19105 
19106 	/* For sanity, re-probe the port */
19107 	sata_device.satadev_rev = SATA_DEVICE_REV;
19108 	sata_device.satadev_addr = *saddr;
19109 
19110 	/*
19111 	 * We have to exit mutex, because the HBA probe port function may
19112 	 * block on its own mutex.
19113 	 */
19114 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19115 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
19116 	    (SATA_DIP(sata_hba_inst), &sata_device);
19117 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19118 	sata_update_port_info(sata_hba_inst, &sata_device);
19119 	if (rval != SATA_SUCCESS) {
19120 		/* Something went wrong? Fail the port */
19121 		cportinfo->cport_state = SATA_PSTATE_FAILED;
19122 		cportinfo->cport_dev_attach_time = 0;
19123 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
19124 		    cport_mutex);
19125 		SATA_LOG_D((sata_hba_inst, CE_WARN,
19126 		    "SATA port %d probing failed",
19127 		    saddr->cport));
19128 		return;
19129 	} else {
19130 		/* port probed successfully */
19131 		cportinfo->cport_state |= SATA_STATE_PROBED | SATA_STATE_READY;
19132 	}
19133 	/*
19134 	 * Check if a device is still attached. For sanity, check also
19135 	 * link status - if no link, there is no device.
19136 	 */
19137 	if ((sata_device.satadev_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
19138 	    SATA_PORT_DEVLINK_UP || sata_device.satadev_type ==
19139 	    SATA_DTYPE_NONE) {
19140 		/*
19141 		 * No device - ignore attach event.
19142 		 */
19143 		cportinfo->cport_dev_attach_time = 0;
19144 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
19145 		    cport_mutex);
19146 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19147 		    "Ignoring attach - no device connected to port %d",
19148 		    sata_device.satadev_addr.cport);
19149 		return;
19150 	}
19151 
19152 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19153 	/*
19154 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
19155 	 * with the hint: SE_HINT_INSERT
19156 	 */
19157 	sata_gen_sysevent(sata_hba_inst, saddr, SE_HINT_INSERT);
19158 
19159 	/*
19160 	 * Port reprobing will take care of the creation of the device
19161 	 * info structure and determination of the device type.
19162 	 */
19163 	sata_device.satadev_addr = *saddr;
19164 	(void) sata_reprobe_port(sata_hba_inst, &sata_device,
19165 	    SATA_DEV_IDENTIFY_NORETRY);
19166 
19167 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
19168 	    cport_mutex);
19169 	if ((cportinfo->cport_state & SATA_STATE_READY) &&
19170 	    (cportinfo->cport_dev_type != SATA_DTYPE_NONE)) {
19171 		/* Some device is attached to the port */
19172 		if (cportinfo->cport_dev_type == SATA_DTYPE_UNKNOWN) {
19173 			/*
19174 			 * A device was not successfully attached.
19175 			 * Track retry time for device identification.
19176 			 */
19177 			if (cportinfo->cport_dev_attach_time != 0) {
19178 				clock_t cur_time = ddi_get_lbolt();
19179 				/*
19180 				 * If the retry time limit was not exceeded,
19181 				 * reinstate attach event.
19182 				 */
19183 				if ((cur_time -
19184 				    cportinfo->cport_dev_attach_time) <
19185 				    drv_usectohz(
19186 				    SATA_DEV_IDENTIFY_TIMEOUT)) {
19187 					/* OK, restore attach event */
19188 					cportinfo->cport_event_flags |=
19189 					    SATA_EVNT_DEVICE_ATTACHED;
19190 				} else {
19191 					/* Timeout - cannot identify device */
19192 					cportinfo->cport_dev_attach_time = 0;
19193 					sata_log(sata_hba_inst,
19194 					    CE_WARN,
19195 					    "Could not identify SATA device "
19196 					    "at port %d",
19197 					    saddr->cport);
19198 				}
19199 			} else {
19200 				/*
19201 				 * Start tracking time for device
19202 				 * identification.
19203 				 * Save current time (lbolt value).
19204 				 */
19205 				cportinfo->cport_dev_attach_time =
19206 				    ddi_get_lbolt();
19207 				/* Restore attach event */
19208 				cportinfo->cport_event_flags |=
19209 				    SATA_EVNT_DEVICE_ATTACHED;
19210 			}
19211 		} else if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT) {
19212 			cportinfo->cport_dev_attach_time = 0;
19213 			sata_log(sata_hba_inst, CE_NOTE,
19214 			    "SATA port-multiplier detected at port %d",
19215 			    saddr->cport);
19216 
19217 			if (SATA_CPORTINFO_PMULT_INFO(cportinfo) != NULL) {
19218 				/* Log the info of new port multiplier */
19219 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19220 				    saddr->cport)->cport_mutex);
19221 				sata_show_pmult_info(sata_hba_inst,
19222 				    &sata_device);
19223 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19224 				    saddr->cport)->cport_mutex);
19225 			}
19226 
19227 			ASSERT(SATA_CPORTINFO_PMULT_INFO(cportinfo) != NULL);
19228 			pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
19229 			for (npmport = 0; npmport <
19230 			    pmultinfo->pmult_num_dev_ports; npmport++) {
19231 				pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
19232 				    saddr->cport, npmport);
19233 				ASSERT(pmportinfo != NULL);
19234 
19235 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19236 				    saddr->cport)->cport_mutex);
19237 				mutex_enter(&pmportinfo->pmport_mutex);
19238 				/* Marked all pmports with link events. */
19239 				pmportinfo->pmport_event_flags =
19240 				    SATA_EVNT_LINK_ESTABLISHED;
19241 				pmult_event_flags |=
19242 				    pmportinfo->pmport_event_flags;
19243 				mutex_exit(&pmportinfo->pmport_mutex);
19244 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19245 				    saddr->cport)->cport_mutex);
19246 			}
19247 			/* Auto-online is not available for PMult now. */
19248 
19249 		} else {
19250 			/*
19251 			 * If device was successfully attached, the subsequent
19252 			 * action depends on a state of the
19253 			 * sata_auto_online variable. If it is set to zero.
19254 			 * an explicit 'configure' command will be needed to
19255 			 * configure it. If its value is non-zero, we will
19256 			 * attempt to online (configure) the device.
19257 			 * First, log the message indicating that a device
19258 			 * was attached.
19259 			 */
19260 			cportinfo->cport_dev_attach_time = 0;
19261 			sata_log(sata_hba_inst, CE_WARN,
19262 			    "SATA device detected at port %d", saddr->cport);
19263 
19264 			if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
19265 				sata_drive_info_t new_sdinfo;
19266 
19267 				/* Log device info data */
19268 				new_sdinfo = *(SATA_CPORTINFO_DRV_INFO(
19269 				    cportinfo));
19270 				sata_show_drive_info(sata_hba_inst,
19271 				    &new_sdinfo);
19272 			}
19273 
19274 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19275 			    saddr->cport)->cport_mutex);
19276 
19277 			/*
19278 			 * Make sure that there is no target node for that
19279 			 * device. If so, release it. It should not happen,
19280 			 * unless we had problem removing the node when
19281 			 * device was detached.
19282 			 */
19283 			tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst),
19284 			    saddr->cport, saddr->pmport);
19285 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19286 			    saddr->cport)->cport_mutex);
19287 			if (tdip != NULL) {
19288 
19289 #ifdef SATA_DEBUG
19290 				if ((cportinfo->cport_event_flags &
19291 				    SATA_EVNT_TARGET_NODE_CLEANUP) == 0)
19292 					sata_log(sata_hba_inst, CE_WARN,
19293 					    "sata_process_device_attached: "
19294 					    "old device target node exists!");
19295 #endif
19296 				/*
19297 				 * target node exists - try to unconfigure
19298 				 * device and remove the node.
19299 				 */
19300 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19301 				    saddr->cport)->cport_mutex);
19302 				rval = ndi_devi_offline(tdip,
19303 				    NDI_DEVI_REMOVE);
19304 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19305 				    saddr->cport)->cport_mutex);
19306 
19307 				if (rval == NDI_SUCCESS) {
19308 					cportinfo->cport_event_flags &=
19309 					    ~SATA_EVNT_TARGET_NODE_CLEANUP;
19310 					cportinfo->cport_tgtnode_clean = B_TRUE;
19311 				} else {
19312 					/*
19313 					 * PROBLEM - the target node remained
19314 					 * and it belongs to a previously
19315 					 * attached device.
19316 					 * This happens when the file was open
19317 					 * or the node was waiting for
19318 					 * resources at the time the
19319 					 * associated device was removed.
19320 					 * Instruct event daemon to retry the
19321 					 * cleanup later.
19322 					 */
19323 					sata_log(sata_hba_inst,
19324 					    CE_WARN,
19325 					    "Application(s) accessing "
19326 					    "previously attached SATA "
19327 					    "device have to release "
19328 					    "it before newly inserted "
19329 					    "device can be made accessible.",
19330 					    saddr->cport);
19331 					cportinfo->cport_event_flags |=
19332 					    SATA_EVNT_TARGET_NODE_CLEANUP;
19333 					cportinfo->cport_tgtnode_clean =
19334 					    B_FALSE;
19335 				}
19336 			}
19337 			if (sata_auto_online != 0) {
19338 				cportinfo->cport_event_flags |=
19339 				    SATA_EVNT_AUTOONLINE_DEVICE;
19340 			}
19341 
19342 		}
19343 	} else {
19344 		cportinfo->cport_dev_attach_time = 0;
19345 	}
19346 
19347 	event_flags = cportinfo->cport_event_flags;
19348 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19349 	if (event_flags != 0 || pmult_event_flags != 0) {
19350 		mutex_enter(&sata_hba_inst->satahba_mutex);
19351 		sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
19352 		mutex_exit(&sata_hba_inst->satahba_mutex);
19353 		mutex_enter(&sata_mutex);
19354 		sata_event_pending |= SATA_EVNT_MAIN;
19355 		mutex_exit(&sata_mutex);
19356 	}
19357 }
19358 
19359 /*
19360  * Port Multiplier Port Device Attached Event processing.
19361  *
19362  * NOTE: No Mutex should be hold.
19363  */
19364 static void
19365 sata_process_pmdevice_attached(sata_hba_inst_t *sata_hba_inst,
19366     sata_address_t *saddr)
19367 {
19368 	sata_pmport_info_t *pmportinfo;
19369 	sata_drive_info_t *sdinfo;
19370 	sata_device_t sata_device;
19371 	dev_info_t *tdip;
19372 	uint32_t event_flags;
19373 	uint8_t cport = saddr->cport;
19374 	uint8_t pmport = saddr->pmport;
19375 	int rval;
19376 
19377 	SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19378 	    "Processing port %d:%d device attached", cport, pmport);
19379 
19380 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
19381 
19382 	mutex_enter(&pmportinfo->pmport_mutex);
19383 
19384 	/* Clear attach event flag first */
19385 	pmportinfo->pmport_event_flags &= ~SATA_EVNT_DEVICE_ATTACHED;
19386 
19387 	/* If the port is in SHUTDOWN or FAILED state, ignore event. */
19388 	if ((pmportinfo->pmport_state &
19389 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
19390 		pmportinfo->pmport_dev_attach_time = 0;
19391 		mutex_exit(&pmportinfo->pmport_mutex);
19392 		return;
19393 	}
19394 
19395 	/*
19396 	 * If the sata_drive_info structure is found attached to the port info,
19397 	 * despite the fact the device was removed and now it is re-attached,
19398 	 * the old drive info structure was not removed.
19399 	 * Arbitrarily release device info structure.
19400 	 */
19401 	if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL) {
19402 		sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
19403 		SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
19404 		(void) kmem_free((void *)sdinfo,
19405 		    sizeof (sata_drive_info_t));
19406 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19407 		    "Arbitrarily detaching old device info.", NULL);
19408 	}
19409 	pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
19410 
19411 	/* For sanity, re-probe the port */
19412 	sata_device.satadev_rev = SATA_DEVICE_REV;
19413 	sata_device.satadev_addr = *saddr;
19414 
19415 	/*
19416 	 * We have to exit mutex, because the HBA probe port function may
19417 	 * block on its own mutex.
19418 	 */
19419 	mutex_exit(&pmportinfo->pmport_mutex);
19420 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
19421 	    (SATA_DIP(sata_hba_inst), &sata_device);
19422 	mutex_enter(&pmportinfo->pmport_mutex);
19423 
19424 	sata_update_pmport_info(sata_hba_inst, &sata_device);
19425 	if (rval != SATA_SUCCESS) {
19426 		/* Something went wrong? Fail the port */
19427 		pmportinfo->pmport_state = SATA_PSTATE_FAILED;
19428 		pmportinfo->pmport_dev_attach_time = 0;
19429 		mutex_exit(&pmportinfo->pmport_mutex);
19430 		SATA_LOG_D((sata_hba_inst, CE_WARN,
19431 		    "SATA port %d:%d probing failed", cport, pmport));
19432 		return;
19433 	} else {
19434 		/* pmport probed successfully */
19435 		pmportinfo->pmport_state |=
19436 		    SATA_STATE_PROBED | SATA_STATE_READY;
19437 	}
19438 	/*
19439 	 * Check if a device is still attached. For sanity, check also
19440 	 * link status - if no link, there is no device.
19441 	 */
19442 	if ((sata_device.satadev_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
19443 	    SATA_PORT_DEVLINK_UP || sata_device.satadev_type ==
19444 	    SATA_DTYPE_NONE) {
19445 		/*
19446 		 * No device - ignore attach event.
19447 		 */
19448 		pmportinfo->pmport_dev_attach_time = 0;
19449 		mutex_exit(&pmportinfo->pmport_mutex);
19450 		SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19451 		    "Ignoring attach - no device connected to port %d:%d",
19452 		    cport, pmport);
19453 		return;
19454 	}
19455 
19456 	mutex_exit(&pmportinfo->pmport_mutex);
19457 	/*
19458 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
19459 	 * with the hint: SE_HINT_INSERT
19460 	 */
19461 	sata_gen_sysevent(sata_hba_inst, saddr, SE_HINT_INSERT);
19462 
19463 	/*
19464 	 * Port reprobing will take care of the creation of the device
19465 	 * info structure and determination of the device type.
19466 	 */
19467 	sata_device.satadev_addr = *saddr;
19468 	(void) sata_reprobe_port(sata_hba_inst, &sata_device,
19469 	    SATA_DEV_IDENTIFY_NORETRY);
19470 
19471 	mutex_enter(&pmportinfo->pmport_mutex);
19472 	if ((pmportinfo->pmport_state & SATA_STATE_READY) &&
19473 	    (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE)) {
19474 		/* Some device is attached to the port */
19475 		if (pmportinfo->pmport_dev_type == SATA_DTYPE_UNKNOWN) {
19476 			/*
19477 			 * A device was not successfully attached.
19478 			 * Track retry time for device identification.
19479 			 */
19480 			if (pmportinfo->pmport_dev_attach_time != 0) {
19481 				clock_t cur_time = ddi_get_lbolt();
19482 				/*
19483 				 * If the retry time limit was not exceeded,
19484 				 * reinstate attach event.
19485 				 */
19486 				if ((cur_time -
19487 				    pmportinfo->pmport_dev_attach_time) <
19488 				    drv_usectohz(
19489 				    SATA_DEV_IDENTIFY_TIMEOUT)) {
19490 					/* OK, restore attach event */
19491 					pmportinfo->pmport_event_flags |=
19492 					    SATA_EVNT_DEVICE_ATTACHED;
19493 				} else {
19494 					/* Timeout - cannot identify device */
19495 					pmportinfo->pmport_dev_attach_time = 0;
19496 					sata_log(sata_hba_inst, CE_WARN,
19497 					    "Could not identify SATA device "
19498 					    "at port %d:%d",
19499 					    cport, pmport);
19500 				}
19501 			} else {
19502 				/*
19503 				 * Start tracking time for device
19504 				 * identification.
19505 				 * Save current time (lbolt value).
19506 				 */
19507 				pmportinfo->pmport_dev_attach_time =
19508 				    ddi_get_lbolt();
19509 				/* Restore attach event */
19510 				pmportinfo->pmport_event_flags |=
19511 				    SATA_EVNT_DEVICE_ATTACHED;
19512 			}
19513 		} else {
19514 			/*
19515 			 * If device was successfully attached, the subsequent
19516 			 * action depends on a state of the
19517 			 * sata_auto_online variable. If it is set to zero.
19518 			 * an explicit 'configure' command will be needed to
19519 			 * configure it. If its value is non-zero, we will
19520 			 * attempt to online (configure) the device.
19521 			 * First, log the message indicating that a device
19522 			 * was attached.
19523 			 */
19524 			pmportinfo->pmport_dev_attach_time = 0;
19525 			sata_log(sata_hba_inst, CE_WARN,
19526 			    "SATA device detected at port %d:%d",
19527 			    cport, pmport);
19528 
19529 			if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL) {
19530 				sata_drive_info_t new_sdinfo;
19531 
19532 				/* Log device info data */
19533 				new_sdinfo = *(SATA_PMPORTINFO_DRV_INFO(
19534 				    pmportinfo));
19535 				sata_show_drive_info(sata_hba_inst,
19536 				    &new_sdinfo);
19537 			}
19538 
19539 			mutex_exit(&pmportinfo->pmport_mutex);
19540 
19541 			/*
19542 			 * Make sure that there is no target node for that
19543 			 * device. If so, release it. It should not happen,
19544 			 * unless we had problem removing the node when
19545 			 * device was detached.
19546 			 */
19547 			tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst),
19548 			    saddr->cport, saddr->pmport);
19549 			mutex_enter(&pmportinfo->pmport_mutex);
19550 			if (tdip != NULL) {
19551 
19552 #ifdef SATA_DEBUG
19553 				if ((pmportinfo->pmport_event_flags &
19554 				    SATA_EVNT_TARGET_NODE_CLEANUP) == 0)
19555 					sata_log(sata_hba_inst, CE_WARN,
19556 					    "sata_process_device_attached: "
19557 					    "old device target node exists!");
19558 #endif
19559 				/*
19560 				 * target node exists - try to unconfigure
19561 				 * device and remove the node.
19562 				 */
19563 				mutex_exit(&pmportinfo->pmport_mutex);
19564 				rval = ndi_devi_offline(tdip,
19565 				    NDI_DEVI_REMOVE);
19566 				mutex_enter(&pmportinfo->pmport_mutex);
19567 
19568 				if (rval == NDI_SUCCESS) {
19569 					pmportinfo->pmport_event_flags &=
19570 					    ~SATA_EVNT_TARGET_NODE_CLEANUP;
19571 					pmportinfo->pmport_tgtnode_clean =
19572 					    B_TRUE;
19573 				} else {
19574 					/*
19575 					 * PROBLEM - the target node remained
19576 					 * and it belongs to a previously
19577 					 * attached device.
19578 					 * This happens when the file was open
19579 					 * or the node was waiting for
19580 					 * resources at the time the
19581 					 * associated device was removed.
19582 					 * Instruct event daemon to retry the
19583 					 * cleanup later.
19584 					 */
19585 					sata_log(sata_hba_inst,
19586 					    CE_WARN,
19587 					    "Application(s) accessing "
19588 					    "previously attached SATA "
19589 					    "device have to release "
19590 					    "it before newly inserted "
19591 					    "device can be made accessible."
19592 					    "at port %d:%d",
19593 					    cport, pmport);
19594 					pmportinfo->pmport_event_flags |=
19595 					    SATA_EVNT_TARGET_NODE_CLEANUP;
19596 					pmportinfo->pmport_tgtnode_clean =
19597 					    B_FALSE;
19598 				}
19599 			}
19600 			if (sata_auto_online != 0) {
19601 				pmportinfo->pmport_event_flags |=
19602 				    SATA_EVNT_AUTOONLINE_DEVICE;
19603 			}
19604 
19605 		}
19606 	} else {
19607 		pmportinfo->pmport_dev_attach_time = 0;
19608 	}
19609 
19610 	event_flags = pmportinfo->pmport_event_flags;
19611 	mutex_exit(&pmportinfo->pmport_mutex);
19612 	if (event_flags != 0) {
19613 		mutex_enter(&sata_hba_inst->satahba_mutex);
19614 		sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
19615 		mutex_exit(&sata_hba_inst->satahba_mutex);
19616 		mutex_enter(&sata_mutex);
19617 		sata_event_pending |= SATA_EVNT_MAIN;
19618 		mutex_exit(&sata_mutex);
19619 	}
19620 
19621 	/* clear the reset_in_progress events */
19622 	if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL) {
19623 		if (pmportinfo->pmport_dev_type & SATA_VALID_DEV_TYPE) {
19624 			/* must clear flags on cport */
19625 			sata_pmult_info_t *pminfo =
19626 			    SATA_PMULT_INFO(sata_hba_inst,
19627 			    saddr->cport);
19628 			pminfo->pmult_event_flags |=
19629 			    SATA_EVNT_CLEAR_DEVICE_RESET;
19630 		}
19631 	}
19632 }
19633 
19634 /*
19635  * Device Target Node Cleanup Event processing.
19636  * If the target node associated with a sata port device is in
19637  * DEVI_DEVICE_REMOVED state, an attempt is made to remove it.
19638  * If the target node cannot be removed, the event flag is left intact,
19639  * so that event daemon may re-run this function later.
19640  *
19641  * This function cannot be called in interrupt context (it may sleep).
19642  *
19643  * NOTE: Processes cport events only, not port multiplier ports.
19644  */
19645 static void
19646 sata_process_target_node_cleanup(sata_hba_inst_t *sata_hba_inst,
19647     sata_address_t *saddr)
19648 {
19649 	sata_cport_info_t *cportinfo;
19650 	dev_info_t *tdip;
19651 
19652 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19653 	    "Processing port %d device target node cleanup", saddr->cport);
19654 
19655 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
19656 
19657 	/*
19658 	 * Check if there is target node for that device and it is in the
19659 	 * DEVI_DEVICE_REMOVED state. If so, release it.
19660 	 */
19661 	tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst), saddr->cport,
19662 	    saddr->pmport);
19663 	if (tdip != NULL) {
19664 		/*
19665 		 * target node exists - check if it is target node of
19666 		 * a removed device.
19667 		 */
19668 		if (sata_check_device_removed(tdip) == B_TRUE) {
19669 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19670 			    "sata_process_target_node_cleanup: "
19671 			    "old device target node exists!", NULL);
19672 			/*
19673 			 * Unconfigure and remove the target node
19674 			 */
19675 			if (ndi_devi_offline(tdip, NDI_DEVI_REMOVE) ==
19676 			    NDI_SUCCESS) {
19677 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19678 				    saddr->cport)->cport_mutex);
19679 				cportinfo->cport_event_flags &=
19680 				    ~SATA_EVNT_TARGET_NODE_CLEANUP;
19681 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19682 				    saddr->cport)->cport_mutex);
19683 				return;
19684 			}
19685 			/*
19686 			 * Event daemon will retry the cleanup later.
19687 			 */
19688 			mutex_enter(&sata_hba_inst->satahba_mutex);
19689 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
19690 			mutex_exit(&sata_hba_inst->satahba_mutex);
19691 			mutex_enter(&sata_mutex);
19692 			sata_event_pending |= SATA_EVNT_MAIN;
19693 			mutex_exit(&sata_mutex);
19694 		}
19695 	} else {
19696 		if (saddr->qual == SATA_ADDR_CPORT ||
19697 		    saddr->qual == SATA_ADDR_DCPORT) {
19698 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19699 			    saddr->cport)->cport_mutex);
19700 			cportinfo->cport_event_flags &=
19701 			    ~SATA_EVNT_TARGET_NODE_CLEANUP;
19702 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19703 			    saddr->cport)->cport_mutex);
19704 		} else {
19705 			/* sanity check */
19706 			if (SATA_CPORT_DEV_TYPE(sata_hba_inst, saddr->cport) !=
19707 			    SATA_DTYPE_PMULT || SATA_PMULT_INFO(sata_hba_inst,
19708 			    saddr->cport) == NULL)
19709 				return;
19710 			if (SATA_PMPORT_INFO(sata_hba_inst, saddr->cport,
19711 			    saddr->pmport) == NULL)
19712 				return;
19713 
19714 			mutex_enter(&SATA_PMPORT_INFO(sata_hba_inst,
19715 			    saddr->cport, saddr->pmport)->pmport_mutex);
19716 			SATA_PMPORT_INFO(sata_hba_inst, saddr->cport,
19717 			    saddr->pmport)->pmport_event_flags &=
19718 			    ~SATA_EVNT_TARGET_NODE_CLEANUP;
19719 			mutex_exit(&SATA_PMPORT_INFO(sata_hba_inst,
19720 			    saddr->cport, saddr->pmport)->pmport_mutex);
19721 		}
19722 	}
19723 }
19724 
19725 /*
19726  * Device AutoOnline Event processing.
19727  * If attached device is to be onlined, an attempt is made to online this
19728  * device, but only if there is no lingering (old) target node present.
19729  * If the device cannot be onlined, the event flag is left intact,
19730  * so that event daemon may re-run this function later.
19731  *
19732  * This function cannot be called in interrupt context (it may sleep).
19733  *
19734  * NOTE: Processes cport events only, not port multiplier ports.
19735  */
19736 static void
19737 sata_process_device_autoonline(sata_hba_inst_t *sata_hba_inst,
19738     sata_address_t *saddr)
19739 {
19740 	sata_cport_info_t *cportinfo;
19741 	sata_drive_info_t *sdinfo;
19742 	sata_device_t sata_device;
19743 	dev_info_t *tdip;
19744 
19745 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19746 	    "Processing port %d attached device auto-onlining", saddr->cport);
19747 
19748 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
19749 
19750 	/*
19751 	 * Check if device is present and recognized. If not, reset event.
19752 	 */
19753 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19754 	if ((cportinfo->cport_dev_type & SATA_VALID_DEV_TYPE) == 0) {
19755 		/* Nothing to online */
19756 		cportinfo->cport_event_flags &= ~SATA_EVNT_AUTOONLINE_DEVICE;
19757 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19758 		    saddr->cport)->cport_mutex);
19759 		return;
19760 	}
19761 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19762 
19763 	/*
19764 	 * Check if there is target node for this device and if it is in the
19765 	 * DEVI_DEVICE_REMOVED state. If so, abort onlining but keep
19766 	 * the event for later processing.
19767 	 */
19768 	tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst), saddr->cport,
19769 	    saddr->pmport);
19770 	if (tdip != NULL) {
19771 		/*
19772 		 * target node exists - check if it is target node of
19773 		 * a removed device.
19774 		 */
19775 		if (sata_check_device_removed(tdip) == B_TRUE) {
19776 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19777 			    "sata_process_device_autoonline: "
19778 			    "old device target node exists!", NULL);
19779 			/*
19780 			 * Event daemon will retry device onlining later.
19781 			 */
19782 			mutex_enter(&sata_hba_inst->satahba_mutex);
19783 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
19784 			mutex_exit(&sata_hba_inst->satahba_mutex);
19785 			mutex_enter(&sata_mutex);
19786 			sata_event_pending |= SATA_EVNT_MAIN;
19787 			mutex_exit(&sata_mutex);
19788 			return;
19789 		}
19790 		/*
19791 		 * If the target node is not in the 'removed" state, assume
19792 		 * that it belongs to this device. There is nothing more to do,
19793 		 * but reset the event.
19794 		 */
19795 	} else {
19796 
19797 		/*
19798 		 * Try to online the device
19799 		 * If there is any reset-related event, remove it. We are
19800 		 * configuring the device and no state restoring is needed.
19801 		 */
19802 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19803 		    saddr->cport)->cport_mutex);
19804 		sata_device.satadev_addr = *saddr;
19805 		if (saddr->qual == SATA_ADDR_CPORT)
19806 			sata_device.satadev_addr.qual = SATA_ADDR_DCPORT;
19807 		else
19808 			sata_device.satadev_addr.qual = SATA_ADDR_DPMPORT;
19809 		sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
19810 		if (sdinfo != NULL) {
19811 			if (sdinfo->satadrv_event_flags &
19812 			    (SATA_EVNT_DEVICE_RESET |
19813 			    SATA_EVNT_INPROC_DEVICE_RESET))
19814 				sdinfo->satadrv_event_flags = 0;
19815 			sdinfo->satadrv_event_flags |=
19816 			    SATA_EVNT_CLEAR_DEVICE_RESET;
19817 
19818 			/* Need to create a new target node. */
19819 			cportinfo->cport_tgtnode_clean = B_TRUE;
19820 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19821 			    saddr->cport)->cport_mutex);
19822 			tdip = sata_create_target_node(SATA_DIP(sata_hba_inst),
19823 			    sata_hba_inst, &sata_device.satadev_addr);
19824 			if (tdip == NULL) {
19825 				/*
19826 				 * Configure (onlining) failed.
19827 				 * We will NOT retry
19828 				 */
19829 				SATA_LOG_D((sata_hba_inst, CE_WARN,
19830 				    "sata_process_device_autoonline: "
19831 				    "configuring SATA device at port %d failed",
19832 				    saddr->cport));
19833 			}
19834 		} else {
19835 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19836 			    saddr->cport)->cport_mutex);
19837 		}
19838 
19839 	}
19840 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19841 	cportinfo->cport_event_flags &= ~SATA_EVNT_AUTOONLINE_DEVICE;
19842 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19843 	    saddr->cport)->cport_mutex);
19844 }
19845 
19846 
19847 static void
19848 sata_gen_sysevent(sata_hba_inst_t *sata_hba_inst, sata_address_t *saddr,
19849     int hint)
19850 {
19851 	char ap[MAXPATHLEN];
19852 	nvlist_t *ev_attr_list = NULL;
19853 	int err;
19854 
19855 	/* Allocate and build sysevent attribute list */
19856 	err = nvlist_alloc(&ev_attr_list, NV_UNIQUE_NAME_TYPE, DDI_NOSLEEP);
19857 	if (err != 0) {
19858 		SATA_LOG_D((sata_hba_inst, CE_WARN,
19859 		    "sata_gen_sysevent: "
19860 		    "cannot allocate memory for sysevent attributes\n"));
19861 		return;
19862 	}
19863 	/* Add hint attribute */
19864 	err = nvlist_add_string(ev_attr_list, DR_HINT, SE_HINT2STR(hint));
19865 	if (err != 0) {
19866 		SATA_LOG_D((sata_hba_inst, CE_WARN,
19867 		    "sata_gen_sysevent: "
19868 		    "failed to add DR_HINT attr for sysevent"));
19869 		nvlist_free(ev_attr_list);
19870 		return;
19871 	}
19872 	/*
19873 	 * Add AP attribute.
19874 	 * Get controller pathname and convert it into AP pathname by adding
19875 	 * a target number.
19876 	 */
19877 	(void) snprintf(ap, MAXPATHLEN, "/devices");
19878 	(void) ddi_pathname(SATA_DIP(sata_hba_inst), ap + strlen(ap));
19879 	(void) snprintf(ap + strlen(ap), MAXPATHLEN - strlen(ap), ":%d",
19880 	    SATA_MAKE_AP_NUMBER(saddr->cport, saddr->pmport, saddr->qual));
19881 
19882 	err = nvlist_add_string(ev_attr_list, DR_AP_ID, ap);
19883 	if (err != 0) {
19884 		SATA_LOG_D((sata_hba_inst, CE_WARN,
19885 		    "sata_gen_sysevent: "
19886 		    "failed to add DR_AP_ID attr for sysevent"));
19887 		nvlist_free(ev_attr_list);
19888 		return;
19889 	}
19890 
19891 	/* Generate/log sysevent */
19892 	err = ddi_log_sysevent(SATA_DIP(sata_hba_inst), DDI_VENDOR_SUNW, EC_DR,
19893 	    ESC_DR_AP_STATE_CHANGE, ev_attr_list, NULL, DDI_NOSLEEP);
19894 	if (err != DDI_SUCCESS) {
19895 		SATA_LOG_D((sata_hba_inst, CE_WARN,
19896 		    "sata_gen_sysevent: "
19897 		    "cannot log sysevent, err code %x\n", err));
19898 	}
19899 
19900 	nvlist_free(ev_attr_list);
19901 }
19902 
19903 
19904 
19905 
19906 /*
19907  * Set DEVI_DEVICE_REMOVED state in the SATA device target node.
19908  */
19909 static void
19910 sata_set_device_removed(dev_info_t *tdip)
19911 {
19912 	int circ;
19913 
19914 	ASSERT(tdip != NULL);
19915 
19916 	ndi_devi_enter(tdip, &circ);
19917 	mutex_enter(&DEVI(tdip)->devi_lock);
19918 	DEVI_SET_DEVICE_REMOVED(tdip);
19919 	mutex_exit(&DEVI(tdip)->devi_lock);
19920 	ndi_devi_exit(tdip, circ);
19921 }
19922 
19923 
19924 /*
19925  * Set internal event instructing event daemon to try
19926  * to perform the target node cleanup.
19927  */
19928 static void
19929 sata_set_target_node_cleanup(sata_hba_inst_t *sata_hba_inst,
19930     sata_address_t *saddr)
19931 {
19932 	if (saddr->qual == SATA_ADDR_CPORT ||
19933 	    saddr->qual == SATA_ADDR_DCPORT) {
19934 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19935 		    saddr->cport)->cport_mutex);
19936 		SATA_CPORT_EVENT_FLAGS(sata_hba_inst, saddr->cport) |=
19937 		    SATA_EVNT_TARGET_NODE_CLEANUP;
19938 		SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
19939 		    cport_tgtnode_clean = B_FALSE;
19940 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19941 		    saddr->cport)->cport_mutex);
19942 	} else {
19943 		mutex_enter(&SATA_PMPORT_INFO(sata_hba_inst,
19944 		    saddr->cport, saddr->pmport)->pmport_mutex);
19945 		SATA_PMPORT_EVENT_FLAGS(sata_hba_inst, saddr->cport,
19946 		    saddr->pmport) |= SATA_EVNT_TARGET_NODE_CLEANUP;
19947 		SATA_PMPORT_INFO(sata_hba_inst, saddr->cport, saddr->pmport)->
19948 		    pmport_tgtnode_clean = B_FALSE;
19949 		mutex_exit(&SATA_PMPORT_INFO(sata_hba_inst,
19950 		    saddr->cport, saddr->pmport)->pmport_mutex);
19951 	}
19952 	mutex_enter(&sata_hba_inst->satahba_mutex);
19953 	sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
19954 	mutex_exit(&sata_hba_inst->satahba_mutex);
19955 	mutex_enter(&sata_mutex);
19956 	sata_event_pending |= SATA_EVNT_MAIN;
19957 	mutex_exit(&sata_mutex);
19958 }
19959 
19960 
19961 /*
19962  * Check if the SATA device target node is in DEVI_DEVICE_REMOVED state,
19963  * i.e. check if the target node state indicates that it belongs to a removed
19964  * device.
19965  *
19966  * Returns B_TRUE if the target node is in DEVI_DEVICE_REMOVED state,
19967  * B_FALSE otherwise.
19968  */
19969 static boolean_t
19970 sata_check_device_removed(dev_info_t *tdip)
19971 {
19972 	ASSERT(tdip != NULL);
19973 
19974 	if (DEVI_IS_DEVICE_REMOVED(tdip))
19975 		return (B_TRUE);
19976 	else
19977 		return (B_FALSE);
19978 }
19979 
19980 /* ************************ FAULT INJECTTION **************************** */
19981 
19982 #ifdef SATA_INJECT_FAULTS
19983 
19984 static	uint32_t sata_fault_count = 0;
19985 static	uint32_t sata_fault_suspend_count = 0;
19986 
19987 /*
19988  * Inject sata pkt fault
19989  * It modifies returned values of the sata packet.
19990  * It returns immediately if:
19991  * pkt fault injection is not enabled (via sata_inject_fault,
19992  * sata_inject_fault_count), or invalid fault is specified (sata_fault_type),
19993  * or pkt does not contain command to be faulted (set in sata_fault_cmd), or
19994  * pkt is not directed to specified fault controller/device
19995  * (sata_fault_ctrl_dev and sata_fault_device).
19996  * If fault controller is not specified, fault injection applies to all
19997  * controllers and devices.
19998  *
19999  * First argument is the pointer to the executed sata packet.
20000  * Second argument is a pointer to a value returned by the HBA tran_start
20001  * function.
20002  * Third argument specifies injected error. Injected sata packet faults
20003  * are the satapkt_reason values.
20004  * SATA_PKT_BUSY		-1	Not completed, busy
20005  * SATA_PKT_DEV_ERROR		1	Device reported error
20006  * SATA_PKT_QUEUE_FULL		2	Not accepted, queue full
20007  * SATA_PKT_PORT_ERROR		3	Not completed, port error
20008  * SATA_PKT_CMD_UNSUPPORTED	4	Cmd unsupported
20009  * SATA_PKT_ABORTED		5	Aborted by request
20010  * SATA_PKT_TIMEOUT		6	Operation timeut
20011  * SATA_PKT_RESET		7	Aborted by reset request
20012  *
20013  * Additional global variables affecting the execution:
20014  *
20015  * sata_inject_fault_count variable specifies number of times in row the
20016  * error is injected. Value of -1 specifies permanent fault, ie. every time
20017  * the fault injection point is reached, the fault is injected and a pause
20018  * between fault injection specified by sata_inject_fault_pause_count is
20019  * ignored). Fault injection routine decrements sata_inject_fault_count
20020  * (if greater than zero) until it reaches 0. No fault is injected when
20021  * sata_inject_fault_count is 0 (zero).
20022  *
20023  * sata_inject_fault_pause_count variable specifies number of times a fault
20024  * injection is bypassed (pause between fault injections).
20025  * If set to 0, a fault is injected only a number of times specified by
20026  * sata_inject_fault_count.
20027  *
20028  * The fault counts are static, so for periodic errors they have to be manually
20029  * reset to start repetition sequence from scratch.
20030  * If the original value returned by the HBA tran_start function is not
20031  * SATA_TRAN_ACCEPTED and pkt reason is not SATA_PKT_COMPLETED, no error
20032  * is injected (to avoid masking real problems);
20033  *
20034  * NOTE: In its current incarnation, this function should be invoked only for
20035  * commands executed in SYNCHRONOUS mode.
20036  */
20037 
20038 
20039 static void
20040 sata_inject_pkt_fault(sata_pkt_t *spkt, int *rval, int fault)
20041 {
20042 
20043 	if (sata_inject_fault != SATA_INJECT_PKT_FAULT)
20044 		return;
20045 
20046 	if (sata_inject_fault_count == 0)
20047 		return;
20048 
20049 	if (fault == 0)
20050 		return;
20051 
20052 	if (sata_fault_cmd != spkt->satapkt_cmd.satacmd_cmd_reg)
20053 		return;
20054 
20055 	if (sata_fault_ctrl != NULL) {
20056 		sata_pkt_txlate_t *spx =
20057 		    (sata_pkt_txlate_t *)spkt->satapkt_framework_private;
20058 
20059 		if (sata_fault_ctrl != NULL && sata_fault_ctrl !=
20060 		    spx->txlt_sata_hba_inst->satahba_dip)
20061 			return;
20062 
20063 		if (sata_fault_device.satadev_addr.cport !=
20064 		    spkt->satapkt_device.satadev_addr.cport ||
20065 		    sata_fault_device.satadev_addr.pmport !=
20066 		    spkt->satapkt_device.satadev_addr.pmport ||
20067 		    sata_fault_device.satadev_addr.qual !=
20068 		    spkt->satapkt_device.satadev_addr.qual)
20069 			return;
20070 	}
20071 
20072 	/* Modify pkt return parameters */
20073 	if (*rval != SATA_TRAN_ACCEPTED ||
20074 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
20075 		sata_fault_count = 0;
20076 		sata_fault_suspend_count = 0;
20077 		return;
20078 	}
20079 	if (sata_fault_count == 0 && sata_fault_suspend_count != 0) {
20080 		/* Pause in the injection */
20081 		sata_fault_suspend_count -= 1;
20082 		return;
20083 	}
20084 
20085 	if (sata_fault_count == 0 && sata_fault_suspend_count == 0) {
20086 		/*
20087 		 * Init inject fault cycle. If fault count is set to -1,
20088 		 * it is a permanent fault.
20089 		 */
20090 		if (sata_inject_fault_count != -1) {
20091 			sata_fault_count = sata_inject_fault_count;
20092 			sata_fault_suspend_count =
20093 			    sata_inject_fault_pause_count;
20094 			if (sata_fault_suspend_count == 0)
20095 				sata_inject_fault_count = 0;
20096 		}
20097 	}
20098 
20099 	if (sata_fault_count != 0)
20100 		sata_fault_count -= 1;
20101 
20102 	switch (fault) {
20103 	case SATA_PKT_BUSY:
20104 		*rval = SATA_TRAN_BUSY;
20105 		spkt->satapkt_reason = SATA_PKT_BUSY;
20106 		break;
20107 
20108 	case SATA_PKT_QUEUE_FULL:
20109 		*rval = SATA_TRAN_QUEUE_FULL;
20110 		spkt->satapkt_reason = SATA_PKT_QUEUE_FULL;
20111 		break;
20112 
20113 	case SATA_PKT_CMD_UNSUPPORTED:
20114 		*rval = SATA_TRAN_CMD_UNSUPPORTED;
20115 		spkt->satapkt_reason = SATA_PKT_CMD_UNSUPPORTED;
20116 		break;
20117 
20118 	case SATA_PKT_PORT_ERROR:
20119 		/* This is "rejected" command */
20120 		*rval = SATA_TRAN_PORT_ERROR;
20121 		spkt->satapkt_reason = SATA_PKT_PORT_ERROR;
20122 		/* Additional error setup could be done here - port state */
20123 		break;
20124 
20125 	case SATA_PKT_DEV_ERROR:
20126 		spkt->satapkt_reason = SATA_PKT_DEV_ERROR;
20127 		/*
20128 		 * Additional error setup could be done here
20129 		 */
20130 		break;
20131 
20132 	case SATA_PKT_ABORTED:
20133 		spkt->satapkt_reason = SATA_PKT_ABORTED;
20134 		break;
20135 
20136 	case SATA_PKT_TIMEOUT:
20137 		spkt->satapkt_reason = SATA_PKT_TIMEOUT;
20138 		/* Additional error setup could be done here */
20139 		break;
20140 
20141 	case SATA_PKT_RESET:
20142 		spkt->satapkt_reason = SATA_PKT_RESET;
20143 		/*
20144 		 * Additional error setup could be done here - device reset
20145 		 */
20146 		break;
20147 
20148 	default:
20149 		break;
20150 	}
20151 }
20152 
20153 #endif
20154 
20155 /*
20156  * SATA Trace Ring Buffer
20157  * ----------------------
20158  *
20159  * Overview
20160  *
20161  * The SATA trace ring buffer is a ring buffer created and managed by
20162  * the SATA framework module that can be used by any module or driver
20163  * within the SATA framework to store debug messages.
20164  *
20165  * Ring Buffer Interfaces:
20166  *
20167  *	sata_vtrace_debug()	<-- Adds debug message to ring buffer
20168  *	sata_trace_debug()	<-- Wraps varargs into sata_vtrace_debug()
20169  *
20170  *	Note that the sata_trace_debug() interface was created to give
20171  *	consumers the flexibilty of sending debug messages to ring buffer
20172  *	as variable arguments.  Consumers can send type va_list debug
20173  *	messages directly to sata_vtrace_debug(). The sata_trace_debug()
20174  *	and sata_vtrace_debug() relationship is similar to that of
20175  *	cmn_err(9F) and vcmn_err(9F).
20176  *
20177  * Below is a diagram of the SATA trace ring buffer interfaces and
20178  * sample consumers:
20179  *
20180  * +---------------------------------+
20181  * |    o  o  SATA Framework Module  |
20182  * | o  SATA  o     +------------------+      +------------------+
20183  * |o   Trace  o <--|sata_vtrace_debug/|<-----|SATA HBA Driver #1|
20184  * |o   R-Buf  o    |sata_trace_debug  |<--+  +------------------+
20185  * | o        o     +------------------+   |  +------------------+
20186  * |    o  o                ^        |     +--|SATA HBA Driver #2|
20187  * |                        |        |        +------------------+
20188  * |           +------------------+  |
20189  * |           |SATA Debug Message|  |
20190  * |           +------------------+  |
20191  * +---------------------------------+
20192  *
20193  * Supporting Routines:
20194  *
20195  *	sata_trace_rbuf_alloc()	<-- Initializes ring buffer
20196  *	sata_trace_rbuf_free()	<-- Destroys ring buffer
20197  *	sata_trace_dmsg_alloc() <-- Creates or reuses buffer in ring buffer
20198  *	sata_trace_dmsg_free()	<-- Destroys content of ring buffer
20199  *
20200  * The default SATA trace ring buffer size is defined by DMSG_RING_SIZE.
20201  * The ring buffer size can be adjusted by setting dmsg_ring_size in
20202  * /etc/system to desired size in unit of bytes.
20203  *
20204  * The individual debug message size in the ring buffer is restricted
20205  * to DMSG_BUF_SIZE.
20206  */
20207 void
20208 sata_vtrace_debug(dev_info_t *dip, const char *fmt, va_list ap)
20209 {
20210 	sata_trace_dmsg_t *dmsg;
20211 
20212 	if (sata_debug_rbuf == NULL) {
20213 		return;
20214 	}
20215 
20216 	/*
20217 	 * If max size of ring buffer is smaller than size
20218 	 * required for one debug message then just return
20219 	 * since we have no room for the debug message.
20220 	 */
20221 	if (sata_debug_rbuf->maxsize < (sizeof (sata_trace_dmsg_t))) {
20222 		return;
20223 	}
20224 
20225 	mutex_enter(&sata_debug_rbuf->lock);
20226 
20227 	/* alloc or reuse on ring buffer */
20228 	dmsg = sata_trace_dmsg_alloc();
20229 
20230 	if (dmsg == NULL) {
20231 		/* resource allocation failed */
20232 		mutex_exit(&sata_debug_rbuf->lock);
20233 		return;
20234 	}
20235 
20236 	dmsg->dip = dip;
20237 	gethrestime(&dmsg->timestamp);
20238 
20239 	(void) vsnprintf(dmsg->buf, sizeof (dmsg->buf), fmt, ap);
20240 
20241 	mutex_exit(&sata_debug_rbuf->lock);
20242 }
20243 
20244 void
20245 sata_trace_debug(dev_info_t *dip, const char *fmt, ...)
20246 {
20247 	va_list ap;
20248 
20249 	va_start(ap, fmt);
20250 	sata_vtrace_debug(dip, fmt, ap);
20251 	va_end(ap);
20252 }
20253 
20254 /*
20255  * This routine is used to manage debug messages
20256  * on ring buffer.
20257  */
20258 static sata_trace_dmsg_t *
20259 sata_trace_dmsg_alloc(void)
20260 {
20261 	sata_trace_dmsg_t *dmsg_alloc, *dmsg = sata_debug_rbuf->dmsgp;
20262 
20263 	if (sata_debug_rbuf->looped == TRUE) {
20264 		sata_debug_rbuf->dmsgp = dmsg->next;
20265 		return (sata_debug_rbuf->dmsgp);
20266 	}
20267 
20268 	/*
20269 	 * If we're looping for the first time,
20270 	 * connect the ring.
20271 	 */
20272 	if (((sata_debug_rbuf->size + (sizeof (sata_trace_dmsg_t))) >
20273 	    sata_debug_rbuf->maxsize) && (sata_debug_rbuf->dmsgh != NULL)) {
20274 		dmsg->next = sata_debug_rbuf->dmsgh;
20275 		sata_debug_rbuf->dmsgp = sata_debug_rbuf->dmsgh;
20276 		sata_debug_rbuf->looped = TRUE;
20277 		return (sata_debug_rbuf->dmsgp);
20278 	}
20279 
20280 	/* If we've gotten this far then memory allocation is needed */
20281 	dmsg_alloc = kmem_zalloc(sizeof (sata_trace_dmsg_t), KM_NOSLEEP);
20282 	if (dmsg_alloc == NULL) {
20283 		sata_debug_rbuf->allocfailed++;
20284 		return (dmsg_alloc);
20285 	} else {
20286 		sata_debug_rbuf->size += sizeof (sata_trace_dmsg_t);
20287 	}
20288 
20289 	if (sata_debug_rbuf->dmsgp != NULL) {
20290 		dmsg->next = dmsg_alloc;
20291 		sata_debug_rbuf->dmsgp = dmsg->next;
20292 		return (sata_debug_rbuf->dmsgp);
20293 	} else {
20294 		/*
20295 		 * We should only be here if we're initializing
20296 		 * the ring buffer.
20297 		 */
20298 		if (sata_debug_rbuf->dmsgh == NULL) {
20299 			sata_debug_rbuf->dmsgh = dmsg_alloc;
20300 		} else {
20301 			/* Something is wrong */
20302 			kmem_free(dmsg_alloc, sizeof (sata_trace_dmsg_t));
20303 			return (NULL);
20304 		}
20305 
20306 		sata_debug_rbuf->dmsgp = dmsg_alloc;
20307 		return (sata_debug_rbuf->dmsgp);
20308 	}
20309 }
20310 
20311 
20312 /*
20313  * Free all messages on debug ring buffer.
20314  */
20315 static void
20316 sata_trace_dmsg_free(void)
20317 {
20318 	sata_trace_dmsg_t *dmsg_next, *dmsg = sata_debug_rbuf->dmsgh;
20319 
20320 	while (dmsg != NULL) {
20321 		dmsg_next = dmsg->next;
20322 		kmem_free(dmsg, sizeof (sata_trace_dmsg_t));
20323 
20324 		/*
20325 		 * If we've looped around the ring than we're done.
20326 		 */
20327 		if (dmsg_next == sata_debug_rbuf->dmsgh) {
20328 			break;
20329 		} else {
20330 			dmsg = dmsg_next;
20331 		}
20332 	}
20333 }
20334 
20335 
20336 /*
20337  * This function can block
20338  */
20339 static void
20340 sata_trace_rbuf_alloc(void)
20341 {
20342 	sata_debug_rbuf = kmem_zalloc(sizeof (sata_trace_rbuf_t), KM_SLEEP);
20343 
20344 	mutex_init(&sata_debug_rbuf->lock, NULL, MUTEX_DRIVER, NULL);
20345 
20346 	if (dmsg_ring_size > 0) {
20347 		sata_debug_rbuf->maxsize = (size_t)dmsg_ring_size;
20348 	}
20349 }
20350 
20351 
20352 static void
20353 sata_trace_rbuf_free(void)
20354 {
20355 	sata_trace_dmsg_free();
20356 	mutex_destroy(&sata_debug_rbuf->lock);
20357 	kmem_free(sata_debug_rbuf, sizeof (sata_trace_rbuf_t));
20358 }
20359 
20360 /*
20361  * If SATA_DEBUG is not defined then this routine is called instead
20362  * of sata_log() via the SATA_LOG_D macro.
20363  */
20364 static void
20365 sata_trace_log(sata_hba_inst_t *sata_hba_inst, uint_t level,
20366     const char *fmt, ...)
20367 {
20368 #ifndef __lock_lint
20369 	_NOTE(ARGUNUSED(level))
20370 #endif
20371 
20372 	dev_info_t *dip = NULL;
20373 	va_list ap;
20374 
20375 	if (sata_hba_inst != NULL) {
20376 		dip = SATA_DIP(sata_hba_inst);
20377 	}
20378 
20379 	va_start(ap, fmt);
20380 	sata_vtrace_debug(dip, fmt, ap);
20381 	va_end(ap);
20382 }
20383