xref: /titanic_51/usr/src/uts/common/io/sata/impl/sata.c (revision be6802e44a2dc59129ccfb75410526d5c1d023ee)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 
28 /*
29  * SATA Framework
30  * Generic SATA Host Adapter Implementation
31  */
32 
33 #include <sys/conf.h>
34 #include <sys/file.h>
35 #include <sys/ddi.h>
36 #include <sys/sunddi.h>
37 #include <sys/modctl.h>
38 #include <sys/cmn_err.h>
39 #include <sys/errno.h>
40 #include <sys/thread.h>
41 #include <sys/kstat.h>
42 #include <sys/note.h>
43 #include <sys/sysevent.h>
44 #include <sys/sysevent/eventdefs.h>
45 #include <sys/sysevent/dr.h>
46 #include <sys/taskq.h>
47 #include <sys/disp.h>
48 
49 #include <sys/sata/impl/sata.h>
50 #include <sys/sata/sata_hba.h>
51 #include <sys/sata/sata_defs.h>
52 #include <sys/sata/sata_cfgadm.h>
53 
54 /* Debug flags - defined in sata.h */
55 int	sata_debug_flags = 0;
56 int	sata_msg = 0;
57 
58 /*
59  * Flags enabling selected SATA HBA framework functionality
60  */
61 #define	SATA_ENABLE_QUEUING		1
62 #define	SATA_ENABLE_NCQ			2
63 #define	SATA_ENABLE_PROCESS_EVENTS	4
64 int sata_func_enable =
65 	SATA_ENABLE_PROCESS_EVENTS | SATA_ENABLE_QUEUING | SATA_ENABLE_NCQ;
66 
67 /*
68  * Global variable setting default maximum queue depth (NCQ or TCQ)
69  * Note:minimum queue depth is 1
70  */
71 int sata_max_queue_depth = SATA_MAX_QUEUE_DEPTH; /* max NCQ/TCQ queue depth */
72 
73 /*
74  * Currently used default NCQ/TCQ queue depth. It is set-up during the driver
75  * initialization, using value from sata_max_queue_depth
76  * It is adjusted to minimum supported by the controller and by the device,
77  * if queueing is enabled.
78  */
79 static	int sata_current_max_qdepth;
80 
81 /*
82  * Global variable determining the default behavior after device hotpluggin.
83  * If non-zero, the hotplugged device is onlined (if possible) without explicit
84  * IOCTL request (AP_CONFIGURE).
85  * If zero, hotplugged device is identified, but not onlined.
86  * Enabling (AP_CONNECT) device port with an attached device does not result
87  * in device onlining regardless of the flag setting
88  */
89 int sata_auto_online = 0;
90 
91 #ifdef SATA_DEBUG
92 
93 #define	SATA_LOG_D(args)	sata_log args
94 uint64_t mbuf_count = 0;
95 uint64_t mbuffail_count = 0;
96 
97 sata_atapi_cmd_t sata_atapi_trace[64];
98 uint32_t sata_atapi_trace_index = 0;
99 int sata_atapi_trace_save = 1;
100 static	void sata_save_atapi_trace(sata_pkt_txlate_t *, int);
101 #define	SATAATAPITRACE(spx, count)	if (sata_atapi_trace_save) \
102     sata_save_atapi_trace(spx, count);
103 
104 #else
105 #define	SATA_LOG_D(arg)
106 #define	SATAATAPITRACE(spx, count)
107 #endif
108 
109 #if 0
110 static void
111 sata_test_atapi_packet_command(sata_hba_inst_t *, int);
112 #endif
113 
114 #ifdef SATA_INJECT_FAULTS
115 
116 #define		SATA_INJECT_PKT_FAULT	1
117 uint32_t	sata_inject_fault = 0;
118 
119 uint32_t	sata_inject_fault_count = 0;
120 uint32_t	sata_inject_fault_pause_count = 0;
121 uint32_t	sata_fault_type = 0;
122 uint32_t	sata_fault_cmd = 0;
123 dev_info_t	*sata_fault_ctrl = NULL;
124 sata_device_t	sata_fault_device;
125 
126 static	void sata_inject_pkt_fault(sata_pkt_t *, int *, int);
127 
128 #endif
129 
130 #define	LEGACY_HWID_LEN	64	/* Model (40) + Serial (20) + pad */
131 
132 static char sata_rev_tag[] = {"1.43"};
133 
134 /*
135  * SATA cb_ops functions
136  */
137 static 	int sata_hba_open(dev_t *, int, int, cred_t *);
138 static 	int sata_hba_close(dev_t, int, int, cred_t *);
139 static 	int sata_hba_ioctl(dev_t, int, intptr_t, int, cred_t *,	int *);
140 
141 /*
142  * SCSA required entry points
143  */
144 static	int sata_scsi_tgt_init(dev_info_t *, dev_info_t *,
145     scsi_hba_tran_t *, struct scsi_device *);
146 static	int sata_scsi_tgt_probe(struct scsi_device *,
147     int (*callback)(void));
148 static void sata_scsi_tgt_free(dev_info_t *, dev_info_t *,
149     scsi_hba_tran_t *, struct scsi_device *);
150 static 	int sata_scsi_start(struct scsi_address *, struct scsi_pkt *);
151 static 	int sata_scsi_abort(struct scsi_address *, struct scsi_pkt *);
152 static 	int sata_scsi_reset(struct scsi_address *, int);
153 static 	int sata_scsi_getcap(struct scsi_address *, char *, int);
154 static 	int sata_scsi_setcap(struct scsi_address *, char *, int, int);
155 static 	struct scsi_pkt *sata_scsi_init_pkt(struct scsi_address *,
156     struct scsi_pkt *, struct buf *, int, int, int, int, int (*)(caddr_t),
157     caddr_t);
158 static 	void sata_scsi_destroy_pkt(struct scsi_address *, struct scsi_pkt *);
159 static 	void sata_scsi_dmafree(struct scsi_address *, struct scsi_pkt *);
160 static 	void sata_scsi_sync_pkt(struct scsi_address *, struct scsi_pkt *);
161 
162 /*
163  * SATA HBA interface functions are defined in sata_hba.h header file
164  */
165 
166 /* Event processing functions */
167 static	void sata_event_daemon(void *);
168 static	void sata_event_thread_control(int);
169 static	void sata_process_controller_events(sata_hba_inst_t *sata_hba_inst);
170 static	void sata_process_device_reset(sata_hba_inst_t *, sata_address_t *);
171 static	void sata_process_port_failed_event(sata_hba_inst_t *,
172     sata_address_t *);
173 static	void sata_process_port_link_events(sata_hba_inst_t *,
174     sata_address_t *);
175 static	void sata_process_device_detached(sata_hba_inst_t *, sata_address_t *);
176 static	void sata_process_device_attached(sata_hba_inst_t *, sata_address_t *);
177 static	void sata_process_port_pwr_change(sata_hba_inst_t *, sata_address_t *);
178 static	void sata_process_cntrl_pwr_level_change(sata_hba_inst_t *);
179 static	void sata_process_target_node_cleanup(sata_hba_inst_t *,
180     sata_address_t *);
181 static	void sata_process_device_autoonline(sata_hba_inst_t *,
182     sata_address_t *saddr);
183 
184 /*
185  * Local translation functions
186  */
187 static	int sata_txlt_inquiry(sata_pkt_txlate_t *);
188 static	int sata_txlt_test_unit_ready(sata_pkt_txlate_t *);
189 static	int sata_txlt_start_stop_unit(sata_pkt_txlate_t *);
190 static	int sata_txlt_read_capacity(sata_pkt_txlate_t *);
191 static	int sata_txlt_request_sense(sata_pkt_txlate_t *);
192 static 	int sata_txlt_read(sata_pkt_txlate_t *);
193 static 	int sata_txlt_write(sata_pkt_txlate_t *);
194 static 	int sata_txlt_log_sense(sata_pkt_txlate_t *);
195 static 	int sata_txlt_log_select(sata_pkt_txlate_t *);
196 static 	int sata_txlt_mode_sense(sata_pkt_txlate_t *);
197 static 	int sata_txlt_mode_select(sata_pkt_txlate_t *);
198 static 	int sata_txlt_synchronize_cache(sata_pkt_txlate_t *);
199 static 	int sata_txlt_write_buffer(sata_pkt_txlate_t *);
200 static 	int sata_txlt_nodata_cmd_immediate(sata_pkt_txlate_t *);
201 
202 static 	int sata_hba_start(sata_pkt_txlate_t *, int *);
203 static	int sata_txlt_invalid_command(sata_pkt_txlate_t *);
204 static	int sata_txlt_lba_out_of_range(sata_pkt_txlate_t *);
205 static 	void sata_txlt_rw_completion(sata_pkt_t *);
206 static 	void sata_txlt_nodata_cmd_completion(sata_pkt_t *);
207 static 	void sata_txlt_download_mcode_cmd_completion(sata_pkt_t *);
208 static 	int sata_emul_rw_completion(sata_pkt_txlate_t *);
209 static 	struct scsi_extended_sense *sata_immediate_error_response(
210     sata_pkt_txlate_t *, int);
211 static	struct scsi_extended_sense *sata_arq_sense(sata_pkt_txlate_t *);
212 
213 static 	int sata_txlt_atapi(sata_pkt_txlate_t *);
214 static 	void sata_txlt_atapi_completion(sata_pkt_t *);
215 
216 /*
217  * Local functions for ioctl
218  */
219 static	int32_t sata_get_port_num(sata_hba_inst_t *,  struct devctl_iocdata *);
220 static	void sata_cfgadm_state(sata_hba_inst_t *, int32_t,
221     devctl_ap_state_t *);
222 static	dev_info_t *sata_get_target_dip(dev_info_t *, int32_t);
223 static	dev_info_t *sata_get_scsi_target_dip(dev_info_t *, sata_address_t *);
224 static	dev_info_t *sata_devt_to_devinfo(dev_t);
225 static	int sata_ioctl_connect(sata_hba_inst_t *, sata_device_t *);
226 static	int sata_ioctl_disconnect(sata_hba_inst_t *, sata_device_t *);
227 static	int sata_ioctl_configure(sata_hba_inst_t *, sata_device_t *);
228 static	int sata_ioctl_unconfigure(sata_hba_inst_t *, sata_device_t *);
229 static	int sata_ioctl_activate(sata_hba_inst_t *, sata_device_t *);
230 static	int sata_ioctl_deactivate(sata_hba_inst_t *, sata_device_t *);
231 static	int sata_ioctl_reset_port(sata_hba_inst_t *, sata_device_t *);
232 static	int sata_ioctl_reset_device(sata_hba_inst_t *, sata_device_t *);
233 static	int sata_ioctl_reset_all(sata_hba_inst_t *);
234 static	int sata_ioctl_port_self_test(sata_hba_inst_t *, sata_device_t *);
235 static	int sata_ioctl_get_device_path(sata_hba_inst_t *, sata_device_t *,
236     sata_ioctl_data_t *, int mode);
237 static	int sata_ioctl_get_ap_type(sata_hba_inst_t *, sata_device_t *,
238     sata_ioctl_data_t *, int mode);
239 static	int sata_ioctl_get_model_info(sata_hba_inst_t *, sata_device_t *,
240     sata_ioctl_data_t *, int mode);
241 static	int sata_ioctl_get_revfirmware_info(sata_hba_inst_t *, sata_device_t *,
242     sata_ioctl_data_t *, int mode);
243 static	int sata_ioctl_get_serialnumber_info(sata_hba_inst_t *,
244     sata_device_t *, sata_ioctl_data_t *, int mode);
245 
246 /*
247  * Local functions
248  */
249 static 	void sata_remove_hba_instance(dev_info_t *);
250 static 	int sata_validate_sata_hba_tran(dev_info_t *, sata_hba_tran_t *);
251 static 	void sata_probe_ports(sata_hba_inst_t *);
252 static 	int sata_reprobe_port(sata_hba_inst_t *, sata_device_t *, int);
253 static 	int sata_add_device(dev_info_t *, sata_hba_inst_t *, int cport,
254     int pmport);
255 static 	dev_info_t *sata_create_target_node(dev_info_t *, sata_hba_inst_t *,
256     sata_address_t *);
257 static 	int sata_validate_scsi_address(sata_hba_inst_t *,
258     struct scsi_address *, sata_device_t *);
259 static 	int sata_validate_sata_address(sata_hba_inst_t *, int, int, int);
260 static	sata_pkt_t *sata_pkt_alloc(sata_pkt_txlate_t *, int (*)(caddr_t));
261 static	void sata_pkt_free(sata_pkt_txlate_t *);
262 static	int sata_dma_buf_setup(sata_pkt_txlate_t *, int, int (*)(caddr_t),
263     caddr_t, ddi_dma_attr_t *);
264 static	void sata_common_free_dma_rsrcs(sata_pkt_txlate_t *);
265 static	int sata_probe_device(sata_hba_inst_t *, sata_device_t *);
266 static	sata_drive_info_t *sata_get_device_info(sata_hba_inst_t *,
267     sata_device_t *);
268 static 	int sata_identify_device(sata_hba_inst_t *, sata_drive_info_t *);
269 static	void sata_reidentify_device(sata_pkt_txlate_t *);
270 static	struct buf *sata_alloc_local_buffer(sata_pkt_txlate_t *, int);
271 static 	void sata_free_local_buffer(sata_pkt_txlate_t *);
272 static 	uint64_t sata_check_capacity(sata_drive_info_t *);
273 void 	sata_adjust_dma_attr(sata_drive_info_t *, ddi_dma_attr_t *,
274     ddi_dma_attr_t *);
275 static 	int sata_fetch_device_identify_data(sata_hba_inst_t *,
276     sata_drive_info_t *);
277 static	void sata_update_port_info(sata_hba_inst_t *, sata_device_t *);
278 static	void sata_update_port_scr(sata_port_scr_t *, sata_device_t *);
279 static	int sata_set_dma_mode(sata_hba_inst_t *, sata_drive_info_t *);
280 static	int sata_set_cache_mode(sata_hba_inst_t *, sata_drive_info_t *, int);
281 static	int sata_set_rmsn(sata_hba_inst_t *, sata_drive_info_t *, int);
282 static	int sata_set_drive_features(sata_hba_inst_t *,
283     sata_drive_info_t *, int flag);
284 static	void sata_init_write_cache_mode(sata_drive_info_t *sdinfo);
285 static	int sata_initialize_device(sata_hba_inst_t *, sata_drive_info_t *);
286 static	void sata_identdev_to_inquiry(sata_hba_inst_t *, sata_drive_info_t *,
287     uint8_t *);
288 static	int sata_get_atapi_inquiry_data(sata_hba_inst_t *, sata_address_t *,
289     struct scsi_inquiry *);
290 static	int sata_build_msense_page_1(sata_drive_info_t *, int, uint8_t *);
291 static	int sata_build_msense_page_8(sata_drive_info_t *, int, uint8_t *);
292 static	int sata_build_msense_page_1a(sata_drive_info_t *, int, uint8_t *);
293 static	int sata_build_msense_page_1c(sata_drive_info_t *, int, uint8_t *);
294 static	int sata_mode_select_page_8(sata_pkt_txlate_t *,
295     struct mode_cache_scsi3 *, int, int *, int *, int *);
296 static	int sata_mode_select_page_1c(sata_pkt_txlate_t *,
297     struct mode_info_excpt_page *, int, int *, int *, int *);
298 static	int sata_build_msense_page_30(sata_drive_info_t *, int, uint8_t *);
299 static	int sata_mode_select_page_30(sata_pkt_txlate_t *,
300     struct mode_acoustic_management *, int, int *, int *, int *);
301 
302 static	int sata_build_lsense_page_0(sata_drive_info_t *, uint8_t *);
303 static	int sata_build_lsense_page_10(sata_drive_info_t *, uint8_t *,
304     sata_hba_inst_t *);
305 static	int sata_build_lsense_page_2f(sata_drive_info_t *, uint8_t *,
306     sata_hba_inst_t *);
307 static	int sata_build_lsense_page_30(sata_drive_info_t *, uint8_t *,
308     sata_hba_inst_t *);
309 static	void sata_save_drive_settings(sata_drive_info_t *);
310 static	void sata_show_drive_info(sata_hba_inst_t *, sata_drive_info_t *);
311 static	void sata_log(sata_hba_inst_t *, uint_t, char *fmt, ...);
312 static	int sata_fetch_smart_return_status(sata_hba_inst_t *,
313     sata_drive_info_t *);
314 static	int sata_fetch_smart_data(sata_hba_inst_t *, sata_drive_info_t *,
315     struct smart_data *);
316 static	int sata_smart_selftest_log(sata_hba_inst_t *,
317     sata_drive_info_t *,
318     struct smart_selftest_log *);
319 static	int sata_ext_smart_selftest_read_log(sata_hba_inst_t *,
320     sata_drive_info_t *, struct smart_ext_selftest_log *, uint16_t);
321 static	int sata_smart_read_log(sata_hba_inst_t *, sata_drive_info_t *,
322     uint8_t *, uint8_t, uint8_t);
323 static	int sata_read_log_ext_directory(sata_hba_inst_t *, sata_drive_info_t *,
324     struct read_log_ext_directory *);
325 static	void sata_gen_sysevent(sata_hba_inst_t *, sata_address_t *, int);
326 static	void sata_xlate_errors(sata_pkt_txlate_t *);
327 static	void sata_decode_device_error(sata_pkt_txlate_t *,
328     struct scsi_extended_sense *);
329 static	void sata_set_device_removed(dev_info_t *);
330 static	boolean_t sata_check_device_removed(dev_info_t *);
331 static	void sata_set_target_node_cleanup(sata_hba_inst_t *, sata_address_t *);
332 static	int sata_ncq_err_ret_cmd_setup(sata_pkt_txlate_t *,
333     sata_drive_info_t *);
334 static	int sata_atapi_err_ret_cmd_setup(sata_pkt_txlate_t *,
335     sata_drive_info_t *);
336 static	void sata_atapi_packet_cmd_setup(sata_cmd_t *, sata_drive_info_t *);
337 static	void sata_fixed_sense_data_preset(struct scsi_extended_sense *);
338 static  void sata_target_devid_register(dev_info_t *, sata_drive_info_t *);
339 static  int sata_check_modser(char *, int);
340 
341 
342 
343 /*
344  * SATA Framework will ignore SATA HBA driver cb_ops structure and
345  * register following one with SCSA framework.
346  * Open & close are provided, so scsi framework will not use its own
347  */
348 static struct cb_ops sata_cb_ops = {
349 	sata_hba_open,			/* open */
350 	sata_hba_close,			/* close */
351 	nodev,				/* strategy */
352 	nodev,				/* print */
353 	nodev,				/* dump */
354 	nodev,				/* read */
355 	nodev,				/* write */
356 	sata_hba_ioctl,			/* ioctl */
357 	nodev,				/* devmap */
358 	nodev,				/* mmap */
359 	nodev,				/* segmap */
360 	nochpoll,			/* chpoll */
361 	ddi_prop_op,			/* cb_prop_op */
362 	0,				/* streamtab */
363 	D_NEW | D_MP,			/* cb_flag */
364 	CB_REV,				/* rev */
365 	nodev,				/* aread */
366 	nodev				/* awrite */
367 };
368 
369 
370 extern struct mod_ops mod_miscops;
371 extern uchar_t	scsi_cdb_size[];
372 
373 static struct modlmisc modlmisc = {
374 	&mod_miscops,			/* Type of module */
375 	"SATA Module"			/* module name */
376 };
377 
378 
379 static struct modlinkage modlinkage = {
380 	MODREV_1,
381 	(void *)&modlmisc,
382 	NULL
383 };
384 
385 /*
386  * Default sata pkt timeout. Used when a target driver scsi_pkt time is zero,
387  * i.e. when scsi_pkt has not timeout specified.
388  */
389 static int sata_default_pkt_time = 60;	/* 60 seconds */
390 
391 /*
392  * Intermediate buffer device access attributes - they are required,
393  * but not necessarily used.
394  */
395 static ddi_device_acc_attr_t sata_acc_attr = {
396 	DDI_DEVICE_ATTR_V0,
397 	DDI_STRUCTURE_LE_ACC,
398 	DDI_STRICTORDER_ACC
399 };
400 
401 
402 /*
403  * Mutexes protecting structures in multithreaded operations.
404  * Because events are relatively rare, a single global mutex protecting
405  * data structures should be sufficient. To increase performance, add
406  * separate mutex per each sata port and use global mutex only to protect
407  * common data structures.
408  */
409 static	kmutex_t sata_mutex;		/* protects sata_hba_list */
410 static	kmutex_t sata_log_mutex;	/* protects log */
411 
412 static 	char sata_log_buf[256];
413 
414 /* Default write cache setting for SATA hard disks */
415 int	sata_write_cache = 1;		/* enabled */
416 
417 /* Default write cache setting for SATA ATAPI CD/DVD */
418 int	sata_atapicdvd_write_cache = 1; /* enabled */
419 
420 /* Default write cache setting for SATA ATAPI tape */
421 int	sata_atapitape_write_cache = 1; /* enabled */
422 
423 /* Default write cache setting for SATA ATAPI disk */
424 int	sata_atapidisk_write_cache = 1;	/* enabled */
425 
426 /*
427  * Linked list of HBA instances
428  */
429 static 	sata_hba_inst_t *sata_hba_list = NULL;
430 static 	sata_hba_inst_t *sata_hba_list_tail = NULL;
431 /*
432  * Pointer to per-instance SATA HBA soft structure is stored in sata_hba_tran
433  * structure and in sata soft state.
434  */
435 
436 /*
437  * Event daemon related variables
438  */
439 static 	kmutex_t sata_event_mutex;
440 static 	kcondvar_t sata_event_cv;
441 static 	kthread_t *sata_event_thread = NULL;
442 static 	int sata_event_thread_terminate = 0;
443 static 	int sata_event_pending = 0;
444 static 	int sata_event_thread_active = 0;
445 extern 	pri_t minclsyspri;
446 
447 /*
448  * NCQ error recovery command
449  */
450 static const sata_cmd_t sata_rle_cmd = {
451 	SATA_CMD_REV,
452 	NULL,
453 	{
454 		SATA_DIR_READ
455 	},
456 	ATA_ADDR_LBA48,
457 	0,
458 	0,
459 	0,
460 	0,
461 	0,
462 	1,
463 	READ_LOG_EXT_NCQ_ERROR_RECOVERY,
464 	0,
465 	0,
466 	0,
467 	SATAC_READ_LOG_EXT,
468 	0,
469 	0,
470 	0,
471 };
472 
473 /*
474  * ATAPI error recovery CDB
475  */
476 static const uint8_t sata_rqsense_cdb[SATA_ATAPI_RQSENSE_CDB_LEN] = {
477 	SCMD_REQUEST_SENSE,
478 	0,			/* Only fixed RQ format is supported */
479 	0,
480 	0,
481 	SATA_ATAPI_MIN_RQSENSE_LEN, /* Less data may be returned */
482 	0
483 };
484 
485 
486 /* Warlock directives */
487 
488 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", scsi_hba_tran))
489 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", scsi_device))
490 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", dev_ops))
491 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", scsi_extended_sense))
492 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", scsi_arq_status))
493 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", ddi_dma_attr))
494 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", ddi_dma_cookie_t))
495 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", devctl_ap_state))
496 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", dev_info::devi_state))
497 _NOTE(MUTEX_PROTECTS_DATA(sata_mutex, sata_hba_list))
498 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_hba_list))
499 _NOTE(MUTEX_PROTECTS_DATA(sata_mutex, sata_hba_inst::satahba_next))
500 _NOTE(MUTEX_PROTECTS_DATA(sata_mutex, sata_hba_inst::satahba_prev))
501 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", \
502     sata_hba_inst::satahba_scsi_tran))
503 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", sata_hba_inst::satahba_tran))
504 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", sata_hba_inst::satahba_dip))
505 _NOTE(SCHEME_PROTECTS_DATA("Scheme", sata_hba_inst::satahba_attached))
506 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_hba_inst::satahba_dev_port))
507 _NOTE(MUTEX_PROTECTS_DATA(sata_hba_inst::satahba_mutex,
508     sata_hba_inst::satahba_event_flags))
509 _NOTE(MUTEX_PROTECTS_DATA(sata_cport_info::cport_mutex, \
510     sata_cport_info::cport_devp))
511 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_cport_info::cport_devp))
512 _NOTE(SCHEME_PROTECTS_DATA("Scheme", sata_cport_info::cport_addr))
513 _NOTE(MUTEX_PROTECTS_DATA(sata_cport_info::cport_mutex, \
514     sata_cport_info::cport_dev_type))
515 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_cport_info::cport_dev_type))
516 _NOTE(MUTEX_PROTECTS_DATA(sata_cport_info::cport_mutex, \
517     sata_cport_info::cport_state))
518 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_cport_info::cport_state))
519 _NOTE(MUTEX_PROTECTS_DATA(sata_cport_info::cport_mutex, \
520     sata_pmport_info::pmport_state))
521 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_pmport_info::pmport_state))
522 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_pmport_info::pmport_dev_type))
523 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_pmport_info::pmport_sata_drive))
524 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_pmult_info::pmult_dev_port))
525 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_pmult_info::pmult_num_dev_ports))
526 #ifdef SATA_DEBUG
527 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", mbuf_count))
528 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", mbuffail_count))
529 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", sata_atapi_trace))
530 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", sata_atapi_trace_index))
531 #endif
532 
533 /* End of warlock directives */
534 
535 /* ************** loadable module configuration functions ************** */
536 
537 int
538 _init()
539 {
540 	int rval;
541 
542 	mutex_init(&sata_mutex, NULL, MUTEX_DRIVER, NULL);
543 	mutex_init(&sata_event_mutex, NULL, MUTEX_DRIVER, NULL);
544 	mutex_init(&sata_log_mutex, NULL, MUTEX_DRIVER, NULL);
545 	cv_init(&sata_event_cv, NULL, CV_DRIVER, NULL);
546 	if ((rval = mod_install(&modlinkage)) != 0) {
547 #ifdef SATA_DEBUG
548 		cmn_err(CE_WARN, "sata: _init: mod_install failed\n");
549 #endif
550 		mutex_destroy(&sata_log_mutex);
551 		cv_destroy(&sata_event_cv);
552 		mutex_destroy(&sata_event_mutex);
553 		mutex_destroy(&sata_mutex);
554 	}
555 	return (rval);
556 }
557 
558 int
559 _fini()
560 {
561 	int rval;
562 
563 	if ((rval = mod_remove(&modlinkage)) != 0)
564 		return (rval);
565 
566 	mutex_destroy(&sata_log_mutex);
567 	cv_destroy(&sata_event_cv);
568 	mutex_destroy(&sata_event_mutex);
569 	mutex_destroy(&sata_mutex);
570 	return (rval);
571 }
572 
573 int
574 _info(struct modinfo *modinfop)
575 {
576 	return (mod_info(&modlinkage, modinfop));
577 }
578 
579 
580 
581 /* ********************* SATA HBA entry points ********************* */
582 
583 
584 /*
585  * Called by SATA HBA from _init().
586  * Registers HBA driver instance/sata framework pair with scsi framework, by
587  * calling scsi_hba_init().
588  *
589  * SATA HBA driver cb_ops are ignored - SATA HBA framework cb_ops are used
590  * instead. SATA HBA framework cb_ops pointer overwrites SATA HBA driver
591  * cb_ops pointer in SATA HBA driver dev_ops structure.
592  * SATA HBA framework cb_ops supplies cb_open cb_close and cb_ioctl vectors.
593  *
594  * Return status of the scsi_hba_init() is returned to a calling SATA HBA
595  * driver.
596  */
597 int
598 sata_hba_init(struct modlinkage *modlp)
599 {
600 	int rval;
601 	struct dev_ops *hba_ops;
602 
603 	SATADBG1(SATA_DBG_HBA_IF, NULL,
604 	    "sata_hba_init: name %s \n",
605 	    ((struct modldrv *)(modlp->ml_linkage[0]))->drv_linkinfo);
606 	/*
607 	 * Fill-up cb_ops and dev_ops when necessary
608 	 */
609 	hba_ops = ((struct modldrv *)(modlp->ml_linkage[0]))->drv_dev_ops;
610 	/*
611 	 * Provide pointer to SATA dev_ops
612 	 */
613 	hba_ops->devo_cb_ops = &sata_cb_ops;
614 
615 	/*
616 	 * Register SATA HBA with SCSI framework
617 	 */
618 	if ((rval = scsi_hba_init(modlp)) != 0) {
619 		SATADBG1(SATA_DBG_HBA_IF, NULL,
620 		    "sata_hba_init: scsi hba init failed\n", NULL);
621 		return (rval);
622 	}
623 
624 	return (0);
625 }
626 
627 
628 /* HBA attach stages */
629 #define	HBA_ATTACH_STAGE_SATA_HBA_INST	1
630 #define	HBA_ATTACH_STAGE_SCSI_ATTACHED	2
631 #define	HBA_ATTACH_STAGE_SETUP		4
632 #define	HBA_ATTACH_STAGE_LINKED		8
633 
634 
635 /*
636  *
637  * Called from SATA HBA driver's attach routine to attach an instance of
638  * the HBA.
639  *
640  * For DDI_ATTACH command:
641  * sata_hba_inst structure is allocated here and initialized with pointers to
642  * SATA framework implementation of required scsi tran functions.
643  * The scsi_tran's tran_hba_private field is used by SATA Framework to point
644  * to the soft structure (sata_hba_inst) allocated by SATA framework for
645  * SATA HBA instance related data.
646  * The scsi_tran's tran_hba_private field is used by SATA framework to
647  * store a pointer to per-HBA-instance of sata_hba_inst structure.
648  * The sata_hba_inst structure is cross-linked to scsi tran structure.
649  * Among other info, a pointer to sata_hba_tran structure is stored in
650  * sata_hba_inst. The sata_hba_inst structures for different HBA instances are
651  * linked together into the list, pointed to by sata_hba_list.
652  * On the first HBA instance attach the sata event thread is initialized.
653  * Attachment points are created for all SATA ports of the HBA being attached.
654  * All HBA instance's SATA ports are probed and type of plugged devices is
655  * determined. For each device of a supported type, a target node is created.
656  *
657  * DDI_SUCCESS is returned when attachment process is successful,
658  * DDI_FAILURE is returned otherwise.
659  *
660  * For DDI_RESUME command:
661  * Not implemented at this time (postponed until phase 2 of the development).
662  */
663 int
664 sata_hba_attach(dev_info_t *dip, sata_hba_tran_t *sata_tran,
665     ddi_attach_cmd_t cmd)
666 {
667 	sata_hba_inst_t	*sata_hba_inst;
668 	scsi_hba_tran_t *scsi_tran = NULL;
669 	int hba_attach_state = 0;
670 	char taskq_name[MAXPATHLEN];
671 
672 	SATADBG3(SATA_DBG_HBA_IF, NULL,
673 	    "sata_hba_attach: node %s (%s%d)\n",
674 	    ddi_node_name(dip), ddi_driver_name(dip),
675 	    ddi_get_instance(dip));
676 
677 	if (cmd == DDI_RESUME) {
678 		/*
679 		 * Postponed until phase 2 of the development
680 		 */
681 		return (DDI_FAILURE);
682 	}
683 
684 	if (cmd != DDI_ATTACH) {
685 		return (DDI_FAILURE);
686 	}
687 
688 	/* cmd == DDI_ATTACH */
689 
690 	if (sata_validate_sata_hba_tran(dip, sata_tran) != SATA_SUCCESS) {
691 		SATA_LOG_D((NULL, CE_WARN,
692 		    "sata_hba_attach: invalid sata_hba_tran"));
693 		return (DDI_FAILURE);
694 	}
695 	/*
696 	 * Allocate and initialize SCSI tran structure.
697 	 * SATA copy of tran_bus_config is provided to create port nodes.
698 	 */
699 	scsi_tran = scsi_hba_tran_alloc(dip, SCSI_HBA_CANSLEEP);
700 	if (scsi_tran == NULL)
701 		return (DDI_FAILURE);
702 	/*
703 	 * Allocate soft structure for SATA HBA instance.
704 	 * There is a separate softstate for each HBA instance.
705 	 */
706 	sata_hba_inst = kmem_zalloc(sizeof (struct sata_hba_inst), KM_SLEEP);
707 	ASSERT(sata_hba_inst != NULL); /* this should not fail */
708 	mutex_init(&sata_hba_inst->satahba_mutex, NULL, MUTEX_DRIVER, NULL);
709 	hba_attach_state |= HBA_ATTACH_STAGE_SATA_HBA_INST;
710 
711 	/*
712 	 * scsi_trans's tran_hba_private is used by SATA Framework to point to
713 	 * soft structure allocated by SATA framework for
714 	 * SATA HBA instance related data.
715 	 */
716 	scsi_tran->tran_hba_private	= sata_hba_inst;
717 	scsi_tran->tran_tgt_private	= NULL;
718 
719 	scsi_tran->tran_tgt_init	= sata_scsi_tgt_init;
720 	scsi_tran->tran_tgt_probe	= sata_scsi_tgt_probe;
721 	scsi_tran->tran_tgt_free	= sata_scsi_tgt_free;
722 
723 	scsi_tran->tran_start		= sata_scsi_start;
724 	scsi_tran->tran_reset		= sata_scsi_reset;
725 	scsi_tran->tran_abort		= sata_scsi_abort;
726 	scsi_tran->tran_getcap		= sata_scsi_getcap;
727 	scsi_tran->tran_setcap		= sata_scsi_setcap;
728 	scsi_tran->tran_init_pkt	= sata_scsi_init_pkt;
729 	scsi_tran->tran_destroy_pkt	= sata_scsi_destroy_pkt;
730 
731 	scsi_tran->tran_dmafree		= sata_scsi_dmafree;
732 	scsi_tran->tran_sync_pkt	= sata_scsi_sync_pkt;
733 
734 	scsi_tran->tran_reset_notify	= NULL;
735 	scsi_tran->tran_get_bus_addr	= NULL;
736 	scsi_tran->tran_quiesce		= NULL;
737 	scsi_tran->tran_unquiesce	= NULL;
738 	scsi_tran->tran_bus_reset	= NULL;
739 
740 	if (scsi_hba_attach_setup(dip, sata_tran->sata_tran_hba_dma_attr,
741 	    scsi_tran, 0) != DDI_SUCCESS) {
742 #ifdef SATA_DEBUG
743 		cmn_err(CE_WARN, "?SATA: %s%d hba scsi attach failed",
744 		    ddi_driver_name(dip), ddi_get_instance(dip));
745 #endif
746 		goto fail;
747 	}
748 	hba_attach_state |= HBA_ATTACH_STAGE_SCSI_ATTACHED;
749 
750 	if (!ddi_prop_exists(DDI_DEV_T_ANY, dip, DDI_PROP_DONTPASS, "sata")) {
751 		if (ddi_prop_update_int(DDI_DEV_T_NONE, dip,
752 		    "sata", 1) != DDI_PROP_SUCCESS) {
753 			SATA_LOG_D((NULL, CE_WARN, "sata_hba_attach: "
754 			    "failed to create hba sata prop"));
755 			goto fail;
756 		}
757 	}
758 
759 	/*
760 	 * Save pointers in hba instance soft state.
761 	 */
762 	sata_hba_inst->satahba_scsi_tran = scsi_tran;
763 	sata_hba_inst->satahba_tran = sata_tran;
764 	sata_hba_inst->satahba_dip = dip;
765 
766 	/*
767 	 * Create a task queue to handle emulated commands completion
768 	 * Use node name, dash, instance number as the queue name.
769 	 */
770 	taskq_name[0] = '\0';
771 	(void) strlcat(taskq_name, DEVI(dip)->devi_node_name,
772 	    sizeof (taskq_name));
773 	(void) snprintf(taskq_name + strlen(taskq_name),
774 	    sizeof (taskq_name) - strlen(taskq_name),
775 	    "-%d", DEVI(dip)->devi_instance);
776 	sata_hba_inst->satahba_taskq = taskq_create(taskq_name, 1,
777 	    minclsyspri, 1, sata_tran->sata_tran_hba_num_cports * 4,
778 	    TASKQ_DYNAMIC);
779 
780 	hba_attach_state |= HBA_ATTACH_STAGE_SETUP;
781 
782 	/*
783 	 * Create events thread if not created yet.
784 	 */
785 	sata_event_thread_control(1);
786 
787 	/*
788 	 * Link this hba instance into the list.
789 	 */
790 	mutex_enter(&sata_mutex);
791 
792 	if (sata_hba_list == NULL) {
793 		/*
794 		 * The first instance of HBA is attached.
795 		 * Set current/active default maximum NCQ/TCQ queue depth for
796 		 * all SATA devices. It is done here and now, to eliminate the
797 		 * possibility of the dynamic, programatic modification of the
798 		 * queue depth via global (and public) sata_max_queue_depth
799 		 * variable (this would require special handling in HBA drivers)
800 		 */
801 		sata_current_max_qdepth = sata_max_queue_depth;
802 		if (sata_current_max_qdepth > 32)
803 			sata_current_max_qdepth = 32;
804 		else if (sata_current_max_qdepth < 1)
805 			sata_current_max_qdepth = 1;
806 	}
807 
808 	sata_hba_inst->satahba_next = NULL;
809 	sata_hba_inst->satahba_prev = sata_hba_list_tail;
810 	if (sata_hba_list == NULL) {
811 		sata_hba_list = sata_hba_inst;
812 	}
813 	if (sata_hba_list_tail != NULL) {
814 		sata_hba_list_tail->satahba_next = sata_hba_inst;
815 	}
816 	sata_hba_list_tail = sata_hba_inst;
817 	mutex_exit(&sata_mutex);
818 	hba_attach_state |= HBA_ATTACH_STAGE_LINKED;
819 
820 	/*
821 	 * Create SATA HBA devctl minor node for sata_hba_open, close, ioctl
822 	 * SATA HBA driver should not use its own open/close entry points.
823 	 *
824 	 * Make sure that instance number doesn't overflow
825 	 * when forming minor numbers.
826 	 */
827 	ASSERT(ddi_get_instance(dip) <= (L_MAXMIN >> INST_MINOR_SHIFT));
828 	if (ddi_create_minor_node(dip, "devctl", S_IFCHR,
829 	    INST2DEVCTL(ddi_get_instance(dip)),
830 	    DDI_NT_SATA_NEXUS, 0) != DDI_SUCCESS) {
831 #ifdef SATA_DEBUG
832 		cmn_err(CE_WARN, "sata_hba_attach: "
833 		    "cannot create devctl minor node");
834 #endif
835 		goto fail;
836 	}
837 
838 
839 	/*
840 	 * Set-up kstats here, if necessary.
841 	 * (postponed until future phase of the development).
842 	 */
843 
844 	/*
845 	 * Indicate that HBA is attached. This will enable events processing
846 	 * for this HBA.
847 	 */
848 	sata_hba_inst->satahba_attached = 1;
849 	/*
850 	 * Probe controller ports. This operation will describe a current
851 	 * controller/port/multipliers/device configuration and will create
852 	 * attachment points.
853 	 * We may end-up with just a controller with no devices attached.
854 	 * For the ports with a supported device attached, device target nodes
855 	 * are created and devices are initialized.
856 	 */
857 	sata_probe_ports(sata_hba_inst);
858 
859 	return (DDI_SUCCESS);
860 
861 fail:
862 	if (hba_attach_state & HBA_ATTACH_STAGE_LINKED) {
863 		(void) sata_remove_hba_instance(dip);
864 		if (sata_hba_list == NULL)
865 			sata_event_thread_control(0);
866 	}
867 
868 	if (hba_attach_state & HBA_ATTACH_STAGE_SETUP) {
869 		(void) ddi_prop_remove(DDI_DEV_T_ANY, dip, "sata");
870 		taskq_destroy(sata_hba_inst->satahba_taskq);
871 	}
872 
873 	if (hba_attach_state & HBA_ATTACH_STAGE_SCSI_ATTACHED)
874 		(void) scsi_hba_detach(dip);
875 
876 	if (hba_attach_state & HBA_ATTACH_STAGE_SATA_HBA_INST) {
877 		mutex_destroy(&sata_hba_inst->satahba_mutex);
878 		kmem_free((void *)sata_hba_inst,
879 		    sizeof (struct sata_hba_inst));
880 		scsi_hba_tran_free(scsi_tran);
881 	}
882 
883 	sata_log(NULL, CE_WARN, "?SATA: %s%d hba attach failed",
884 	    ddi_driver_name(dip), ddi_get_instance(dip));
885 
886 	return (DDI_FAILURE);
887 }
888 
889 
890 /*
891  * Called by SATA HBA from to detach an instance of the driver.
892  *
893  * For DDI_DETACH command:
894  * Free local structures allocated for SATA HBA instance during
895  * sata_hba_attach processing.
896  *
897  * Returns DDI_SUCCESS when HBA was detached, DDI_FAILURE otherwise.
898  *
899  * For DDI_SUSPEND command:
900  * Not implemented at this time (postponed until phase 2 of the development)
901  * Returnd DDI_SUCCESS.
902  *
903  * When the last HBA instance is detached, the event daemon is terminated.
904  *
905  * NOTE: cport support only, no port multiplier support.
906  */
907 int
908 sata_hba_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
909 {
910 	dev_info_t	*tdip;
911 	sata_hba_inst_t	*sata_hba_inst;
912 	scsi_hba_tran_t *scsi_hba_tran;
913 	sata_cport_info_t *cportinfo;
914 	sata_drive_info_t *sdinfo;
915 	int ncport;
916 
917 	SATADBG3(SATA_DBG_HBA_IF, NULL, "sata_hba_detach: node %s (%s%d)\n",
918 	    ddi_node_name(dip), ddi_driver_name(dip), ddi_get_instance(dip));
919 
920 	switch (cmd) {
921 	case DDI_DETACH:
922 
923 		if ((scsi_hba_tran = ddi_get_driver_private(dip)) == NULL)
924 			return (DDI_FAILURE);
925 
926 		sata_hba_inst = scsi_hba_tran->tran_hba_private;
927 		if (sata_hba_inst == NULL)
928 			return (DDI_FAILURE);
929 
930 		if (scsi_hba_detach(dip) == DDI_FAILURE) {
931 			sata_hba_inst->satahba_attached = 1;
932 			return (DDI_FAILURE);
933 		}
934 
935 		/*
936 		 * Free all target nodes - at this point
937 		 * devices should be at least offlined
938 		 * otherwise scsi_hba_detach() should not be called.
939 		 */
940 		for (ncport = 0; ncport < SATA_NUM_CPORTS(sata_hba_inst);
941 		    ncport++) {
942 			cportinfo = SATA_CPORT_INFO(sata_hba_inst, ncport);
943 			if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
944 				sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
945 				if (sdinfo != NULL) {
946 					tdip = sata_get_target_dip(dip,
947 					    ncport);
948 					if (tdip != NULL) {
949 						if (ndi_devi_offline(tdip,
950 						    NDI_DEVI_REMOVE) !=
951 						    NDI_SUCCESS) {
952 							SATA_LOG_D((
953 							    sata_hba_inst,
954 							    CE_WARN,
955 							    "sata_hba_detach: "
956 							    "Target node not "
957 							    "removed !"));
958 							return (DDI_FAILURE);
959 						}
960 					}
961 				}
962 			}
963 		}
964 		/*
965 		 * Disable sata event daemon processing for this HBA
966 		 */
967 		sata_hba_inst->satahba_attached = 0;
968 
969 		/*
970 		 * Remove event daemon thread, if it is last HBA instance.
971 		 */
972 
973 		mutex_enter(&sata_mutex);
974 		if (sata_hba_list->satahba_next == NULL) {
975 			mutex_exit(&sata_mutex);
976 			sata_event_thread_control(0);
977 			mutex_enter(&sata_mutex);
978 		}
979 		mutex_exit(&sata_mutex);
980 
981 		/* Remove this HBA instance from the HBA list */
982 		sata_remove_hba_instance(dip);
983 
984 		/*
985 		 * At this point there should be no target nodes attached.
986 		 * Detach and destroy device and port info structures.
987 		 */
988 		for (ncport = 0; ncport < SATA_NUM_CPORTS(sata_hba_inst);
989 		    ncport++) {
990 			cportinfo = SATA_CPORT_INFO(sata_hba_inst, ncport);
991 			if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
992 				sdinfo =
993 				    cportinfo->cport_devp.cport_sata_drive;
994 				if (sdinfo != NULL) {
995 					/* Release device structure */
996 					kmem_free(sdinfo,
997 					    sizeof (sata_drive_info_t));
998 				}
999 				/* Release cport info */
1000 				mutex_destroy(&cportinfo->cport_mutex);
1001 				kmem_free(cportinfo,
1002 				    sizeof (sata_cport_info_t));
1003 			}
1004 		}
1005 
1006 		scsi_hba_tran_free(sata_hba_inst->satahba_scsi_tran);
1007 
1008 		(void) ddi_prop_remove(DDI_DEV_T_ANY, dip, "sata");
1009 
1010 		taskq_destroy(sata_hba_inst->satahba_taskq);
1011 
1012 		mutex_destroy(&sata_hba_inst->satahba_mutex);
1013 		kmem_free((void *)sata_hba_inst,
1014 		    sizeof (struct sata_hba_inst));
1015 
1016 		return (DDI_SUCCESS);
1017 
1018 	case DDI_SUSPEND:
1019 		/*
1020 		 * Postponed until phase 2
1021 		 */
1022 		return (DDI_FAILURE);
1023 
1024 	default:
1025 		return (DDI_FAILURE);
1026 	}
1027 }
1028 
1029 
1030 /*
1031  * Called by an HBA drive from _fini() routine.
1032  * Unregisters SATA HBA instance/SATA framework pair from the scsi framework.
1033  */
1034 void
1035 sata_hba_fini(struct modlinkage *modlp)
1036 {
1037 	SATADBG1(SATA_DBG_HBA_IF, NULL,
1038 	    "sata_hba_fini: name %s\n",
1039 	    ((struct modldrv *)(modlp->ml_linkage[0]))->drv_linkinfo);
1040 
1041 	scsi_hba_fini(modlp);
1042 }
1043 
1044 
1045 /*
1046  * Default open and close routine for sata_hba framework.
1047  *
1048  */
1049 /*
1050  * Open devctl node.
1051  *
1052  * Returns:
1053  * 0 if node was open successfully, error code otherwise.
1054  *
1055  *
1056  */
1057 
1058 static int
1059 sata_hba_open(dev_t *devp, int flags, int otyp, cred_t *credp)
1060 {
1061 #ifndef __lock_lint
1062 	_NOTE(ARGUNUSED(credp))
1063 #endif
1064 	int rv = 0;
1065 	dev_info_t *dip;
1066 	scsi_hba_tran_t *scsi_hba_tran;
1067 	sata_hba_inst_t	*sata_hba_inst;
1068 
1069 	SATADBG1(SATA_DBG_IOCTL_IF, NULL, "sata_hba_open: entered", NULL);
1070 
1071 	if (otyp != OTYP_CHR)
1072 		return (EINVAL);
1073 
1074 	dip = sata_devt_to_devinfo(*devp);
1075 	if (dip == NULL)
1076 		return (ENXIO);
1077 
1078 	if ((scsi_hba_tran = ddi_get_driver_private(dip)) == NULL)
1079 		return (ENXIO);
1080 
1081 	sata_hba_inst = scsi_hba_tran->tran_hba_private;
1082 	if (sata_hba_inst == NULL || sata_hba_inst->satahba_attached == 0)
1083 		return (ENXIO);
1084 
1085 	mutex_enter(&sata_mutex);
1086 	if (flags & FEXCL) {
1087 		if (sata_hba_inst->satahba_open_flag != 0) {
1088 			rv = EBUSY;
1089 		} else {
1090 			sata_hba_inst->satahba_open_flag =
1091 			    SATA_DEVCTL_EXOPENED;
1092 		}
1093 	} else {
1094 		if (sata_hba_inst->satahba_open_flag == SATA_DEVCTL_EXOPENED) {
1095 			rv = EBUSY;
1096 		} else {
1097 			sata_hba_inst->satahba_open_flag =
1098 			    SATA_DEVCTL_SOPENED;
1099 		}
1100 	}
1101 	mutex_exit(&sata_mutex);
1102 
1103 	return (rv);
1104 }
1105 
1106 
1107 /*
1108  * Close devctl node.
1109  * Returns:
1110  * 0 if node was closed successfully, error code otherwise.
1111  *
1112  */
1113 
1114 static int
1115 sata_hba_close(dev_t dev, int flag, int otyp, cred_t *credp)
1116 {
1117 #ifndef __lock_lint
1118 	_NOTE(ARGUNUSED(credp))
1119 	_NOTE(ARGUNUSED(flag))
1120 #endif
1121 	dev_info_t *dip;
1122 	scsi_hba_tran_t *scsi_hba_tran;
1123 	sata_hba_inst_t	*sata_hba_inst;
1124 
1125 	SATADBG1(SATA_DBG_IOCTL_IF, NULL, "sata_hba_close: entered", NULL);
1126 
1127 	if (otyp != OTYP_CHR)
1128 		return (EINVAL);
1129 
1130 	dip = sata_devt_to_devinfo(dev);
1131 	if (dip == NULL)
1132 		return (ENXIO);
1133 
1134 	if ((scsi_hba_tran = ddi_get_driver_private(dip)) == NULL)
1135 		return (ENXIO);
1136 
1137 	sata_hba_inst = scsi_hba_tran->tran_hba_private;
1138 	if (sata_hba_inst == NULL || sata_hba_inst->satahba_attached == 0)
1139 		return (ENXIO);
1140 
1141 	mutex_enter(&sata_mutex);
1142 	sata_hba_inst->satahba_open_flag = 0;
1143 	mutex_exit(&sata_mutex);
1144 	return (0);
1145 }
1146 
1147 
1148 
1149 /*
1150  * Standard IOCTL commands for SATA hotplugging.
1151  * Implemented DEVCTL_AP commands:
1152  * DEVCTL_AP_CONNECT
1153  * DEVCTL_AP_DISCONNECT
1154  * DEVCTL_AP_CONFIGURE
1155  * DEVCTL_UNCONFIGURE
1156  * DEVCTL_AP_CONTROL
1157  *
1158  * Commands passed to default ndi ioctl handler:
1159  * DEVCTL_DEVICE_GETSTATE
1160  * DEVCTL_DEVICE_ONLINE
1161  * DEVCTL_DEVICE_OFFLINE
1162  * DEVCTL_DEVICE_REMOVE
1163  * DEVCTL_DEVICE_INSERT
1164  * DEVCTL_BUS_GETSTATE
1165  *
1166  * All other cmds are passed to HBA if it provide ioctl handler, or failed
1167  * if not.
1168  *
1169  * Returns:
1170  * 0 if successful,
1171  * error code if operation failed.
1172  *
1173  * NOTE: Port Multiplier is not supported.
1174  *
1175  */
1176 
1177 static int
1178 sata_hba_ioctl(dev_t dev, int cmd, intptr_t arg, int mode, cred_t *credp,
1179     int *rvalp)
1180 {
1181 #ifndef __lock_lint
1182 	_NOTE(ARGUNUSED(credp))
1183 	_NOTE(ARGUNUSED(rvalp))
1184 #endif
1185 	int rv = 0;
1186 	int32_t	comp_port = -1;
1187 	dev_info_t *dip;
1188 	devctl_ap_state_t ap_state;
1189 	struct devctl_iocdata *dcp = NULL;
1190 	scsi_hba_tran_t *scsi_hba_tran;
1191 	sata_hba_inst_t *sata_hba_inst;
1192 	sata_device_t sata_device;
1193 	sata_cport_info_t *cportinfo;
1194 	int cport, pmport, qual;
1195 	int rval = SATA_SUCCESS;
1196 
1197 	dip = sata_devt_to_devinfo(dev);
1198 	if (dip == NULL)
1199 		return (ENXIO);
1200 
1201 	if ((scsi_hba_tran = ddi_get_driver_private(dip)) == NULL)
1202 		return (ENXIO);
1203 
1204 	sata_hba_inst = scsi_hba_tran->tran_hba_private;
1205 	if (sata_hba_inst == NULL)
1206 		return (ENXIO);
1207 
1208 	if (sata_hba_inst->satahba_tran == NULL)
1209 		return (ENXIO);
1210 
1211 	switch (cmd) {
1212 
1213 	case DEVCTL_DEVICE_GETSTATE:
1214 	case DEVCTL_DEVICE_ONLINE:
1215 	case DEVCTL_DEVICE_OFFLINE:
1216 	case DEVCTL_DEVICE_REMOVE:
1217 	case DEVCTL_BUS_GETSTATE:
1218 		/*
1219 		 * There may be more cases that we want to pass to default
1220 		 * handler rather than fail them.
1221 		 */
1222 		return (ndi_devctl_ioctl(dip, cmd, arg, mode, 0));
1223 	}
1224 
1225 	/* read devctl ioctl data */
1226 	if (cmd != DEVCTL_AP_CONTROL) {
1227 		if (ndi_dc_allochdl((void *)arg, &dcp) != NDI_SUCCESS)
1228 			return (EFAULT);
1229 
1230 		if ((comp_port = sata_get_port_num(sata_hba_inst, dcp)) ==
1231 		    -1) {
1232 			if (dcp)
1233 				ndi_dc_freehdl(dcp);
1234 			return (EINVAL);
1235 		}
1236 
1237 		cport = SCSI_TO_SATA_CPORT(comp_port);
1238 		pmport = SCSI_TO_SATA_PMPORT(comp_port);
1239 		/* Only cport is considered now, i.e. SATA_ADDR_CPORT */
1240 		qual = SATA_ADDR_CPORT;
1241 		if (sata_validate_sata_address(sata_hba_inst, cport, pmport,
1242 		    qual) != 0) {
1243 			ndi_dc_freehdl(dcp);
1244 			return (EINVAL);
1245 		}
1246 
1247 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
1248 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
1249 		    cport_mutex);
1250 		if (cportinfo->cport_event_flags & SATA_EVNT_LOCK_PORT_BUSY) {
1251 			/*
1252 			 * Cannot process ioctl request now. Come back later.
1253 			 */
1254 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
1255 			    cport_mutex);
1256 			ndi_dc_freehdl(dcp);
1257 			return (EBUSY);
1258 		}
1259 		/* Block event processing for this port */
1260 		cportinfo->cport_event_flags |= SATA_APCTL_LOCK_PORT_BUSY;
1261 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
1262 
1263 		sata_device.satadev_addr.cport = cport;
1264 		sata_device.satadev_addr.pmport = pmport;
1265 		sata_device.satadev_addr.qual = qual;
1266 		sata_device.satadev_rev = SATA_DEVICE_REV;
1267 	}
1268 
1269 	switch (cmd) {
1270 
1271 	case DEVCTL_AP_DISCONNECT:
1272 
1273 		/*
1274 		 * Normally, cfgadm sata plugin will try to offline
1275 		 * (unconfigure) device before this request. Nevertheless,
1276 		 * if a device is still configured, we need to
1277 		 * attempt to offline and unconfigure device first, and we will
1278 		 * deactivate the port regardless of the unconfigure
1279 		 * operation results.
1280 		 *
1281 		 */
1282 		rv = sata_ioctl_disconnect(sata_hba_inst, &sata_device);
1283 
1284 		break;
1285 
1286 	case DEVCTL_AP_UNCONFIGURE:
1287 
1288 		/*
1289 		 * The unconfigure operation uses generic nexus operation to
1290 		 * offline a device. It leaves a target device node attached.
1291 		 * and obviously sata_drive_info attached as well, because
1292 		 * from the hardware point of view nothing has changed.
1293 		 */
1294 		rv = sata_ioctl_unconfigure(sata_hba_inst, &sata_device);
1295 		break;
1296 
1297 	case DEVCTL_AP_CONNECT:
1298 	{
1299 		/*
1300 		 * The sata cfgadm pluging will invoke this operation only if
1301 		 * port was found in the disconnect state (failed state
1302 		 * is also treated as the disconnected state).
1303 		 * If port activation is successful and a device is found
1304 		 * attached to the port, the initialization sequence is
1305 		 * executed to probe the port and attach
1306 		 * a device structure to a port structure. The device is not
1307 		 * set in configured state (system-wise) by this operation.
1308 		 */
1309 
1310 		rv = sata_ioctl_connect(sata_hba_inst, &sata_device);
1311 
1312 		break;
1313 	}
1314 
1315 	case DEVCTL_AP_CONFIGURE:
1316 	{
1317 		/*
1318 		 * A port may be in an active or shutdown state.
1319 		 * If port is in a failed state, operation is aborted.
1320 		 * If a port is in a shutdown state, sata_tran_port_activate()
1321 		 * is invoked prior to any other operation.
1322 		 *
1323 		 * Onlining the device involves creating a new target node.
1324 		 * If there is an old target node present (belonging to
1325 		 * previously removed device), the operation is aborted - the
1326 		 * old node has to be released and removed before configure
1327 		 * operation is attempted.
1328 		 */
1329 
1330 		rv = sata_ioctl_configure(sata_hba_inst, &sata_device);
1331 
1332 		break;
1333 	}
1334 
1335 	case DEVCTL_AP_GETSTATE:
1336 
1337 		sata_cfgadm_state(sata_hba_inst, comp_port, &ap_state);
1338 
1339 		ap_state.ap_last_change = (time_t)-1;
1340 		ap_state.ap_error_code = 0;
1341 		ap_state.ap_in_transition = 0;
1342 
1343 		/* Copy the return AP-state information to the user space */
1344 		if (ndi_dc_return_ap_state(&ap_state, dcp) != NDI_SUCCESS) {
1345 			rv = EFAULT;
1346 		}
1347 		break;
1348 
1349 	case DEVCTL_AP_CONTROL:
1350 	{
1351 		/*
1352 		 * Generic devctl for hardware specific functionality
1353 		 */
1354 		sata_ioctl_data_t	ioc;
1355 
1356 		ASSERT(dcp == NULL);
1357 
1358 		/* Copy in user ioctl data first */
1359 #ifdef _MULTI_DATAMODEL
1360 		if (ddi_model_convert_from(mode & FMODELS) ==
1361 		    DDI_MODEL_ILP32) {
1362 
1363 			sata_ioctl_data_32_t	ioc32;
1364 
1365 			if (ddi_copyin((void *)arg, (void *)&ioc32,
1366 			    sizeof (ioc32), mode) != 0) {
1367 				rv = EFAULT;
1368 				break;
1369 			}
1370 			ioc.cmd 	= (uint_t)ioc32.cmd;
1371 			ioc.port	= (uint_t)ioc32.port;
1372 			ioc.get_size	= (uint_t)ioc32.get_size;
1373 			ioc.buf		= (caddr_t)(uintptr_t)ioc32.buf;
1374 			ioc.bufsiz	= (uint_t)ioc32.bufsiz;
1375 			ioc.misc_arg	= (uint_t)ioc32.misc_arg;
1376 		} else
1377 #endif /* _MULTI_DATAMODEL */
1378 		if (ddi_copyin((void *)arg, (void *)&ioc, sizeof (ioc),
1379 		    mode) != 0) {
1380 			return (EFAULT);
1381 		}
1382 
1383 		SATADBG2(SATA_DBG_IOCTL_IF, sata_hba_inst,
1384 		    "sata_hba_ioctl: DEVCTL_AP_CONTROL "
1385 		    "cmd 0x%x, port 0x%x", ioc.cmd, ioc.port);
1386 
1387 		/*
1388 		 * To avoid BE/LE and 32/64 issues, a get_size always returns
1389 		 * a 32-bit number.
1390 		 */
1391 		if (ioc.get_size != 0 && ioc.bufsiz != (sizeof (uint32_t))) {
1392 			return (EINVAL);
1393 		}
1394 		/* validate address */
1395 		cport = SCSI_TO_SATA_CPORT(ioc.port);
1396 		pmport = SCSI_TO_SATA_PMPORT(ioc.port);
1397 		qual = SCSI_TO_SATA_ADDR_QUAL(ioc.port);
1398 
1399 		/* Override address qualifier - handle cport only for now */
1400 		qual = SATA_ADDR_CPORT;
1401 
1402 		if (sata_validate_sata_address(sata_hba_inst, cport,
1403 		    pmport, qual) != 0)
1404 			return (EINVAL);
1405 
1406 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
1407 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
1408 		    cport_mutex);
1409 		/* Is the port locked by event processing daemon ? */
1410 		if (cportinfo->cport_event_flags & SATA_EVNT_LOCK_PORT_BUSY) {
1411 			/*
1412 			 * Cannot process ioctl request now. Come back later
1413 			 */
1414 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
1415 			    cport_mutex);
1416 			return (EBUSY);
1417 		}
1418 		/* Block event processing for this port */
1419 		cportinfo->cport_event_flags |= SATA_APCTL_LOCK_PORT_BUSY;
1420 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
1421 
1422 
1423 		sata_device.satadev_addr.cport = cport;
1424 		sata_device.satadev_addr.pmport = pmport;
1425 		sata_device.satadev_addr.qual = qual;
1426 		sata_device.satadev_rev = SATA_DEVICE_REV;
1427 
1428 		switch (ioc.cmd) {
1429 
1430 		case SATA_CFGA_RESET_PORT:
1431 			/*
1432 			 * There is no protection for configured device.
1433 			 */
1434 			rv = sata_ioctl_reset_port(sata_hba_inst, &sata_device);
1435 			break;
1436 
1437 		case SATA_CFGA_RESET_DEVICE:
1438 			/*
1439 			 * There is no protection for configured device.
1440 			 */
1441 			rv = sata_ioctl_reset_device(sata_hba_inst,
1442 			    &sata_device);
1443 			break;
1444 
1445 		case SATA_CFGA_RESET_ALL:
1446 			/*
1447 			 * There is no protection for configured devices.
1448 			 */
1449 			rv = sata_ioctl_reset_all(sata_hba_inst);
1450 			/*
1451 			 * We return here, because common return is for
1452 			 * a single port operation - we have already unlocked
1453 			 * all ports and no dc handle was allocated.
1454 			 */
1455 			return (rv);
1456 
1457 		case SATA_CFGA_PORT_DEACTIVATE:
1458 			/*
1459 			 * Arbitrarily unconfigure attached device, if any.
1460 			 * Even if the unconfigure fails, proceed with the
1461 			 * port deactivation.
1462 			 */
1463 			rv = sata_ioctl_deactivate(sata_hba_inst, &sata_device);
1464 
1465 			break;
1466 
1467 		case SATA_CFGA_PORT_ACTIVATE:
1468 
1469 			rv = sata_ioctl_activate(sata_hba_inst, &sata_device);
1470 			break;
1471 
1472 		case SATA_CFGA_PORT_SELF_TEST:
1473 
1474 			rv = sata_ioctl_port_self_test(sata_hba_inst,
1475 			    &sata_device);
1476 			break;
1477 
1478 		case SATA_CFGA_GET_DEVICE_PATH:
1479 			if (qual == SATA_ADDR_CPORT)
1480 				sata_device.satadev_addr.qual =
1481 				    SATA_ADDR_DCPORT;
1482 			else
1483 				sata_device.satadev_addr.qual =
1484 				    SATA_ADDR_DPMPORT;
1485 			rv = sata_ioctl_get_device_path(sata_hba_inst,
1486 			    &sata_device, &ioc, mode);
1487 			break;
1488 
1489 		case SATA_CFGA_GET_AP_TYPE:
1490 
1491 			rv = sata_ioctl_get_ap_type(sata_hba_inst,
1492 			    &sata_device, &ioc, mode);
1493 			break;
1494 
1495 		case SATA_CFGA_GET_MODEL_INFO:
1496 
1497 			rv = sata_ioctl_get_model_info(sata_hba_inst,
1498 			    &sata_device, &ioc, mode);
1499 			break;
1500 
1501 		case SATA_CFGA_GET_REVFIRMWARE_INFO:
1502 
1503 			rv = sata_ioctl_get_revfirmware_info(sata_hba_inst,
1504 			    &sata_device, &ioc, mode);
1505 			break;
1506 
1507 		case SATA_CFGA_GET_SERIALNUMBER_INFO:
1508 
1509 			rv = sata_ioctl_get_serialnumber_info(sata_hba_inst,
1510 			    &sata_device, &ioc, mode);
1511 			break;
1512 
1513 		default:
1514 			rv = EINVAL;
1515 			break;
1516 
1517 		} /* End of DEVCTL_AP_CONTROL cmd switch */
1518 
1519 		break;
1520 	}
1521 
1522 	default:
1523 	{
1524 		/*
1525 		 * If we got here, we got an IOCTL that SATA HBA Framework
1526 		 * does not recognize. Pass ioctl to HBA driver, in case
1527 		 * it could process it.
1528 		 */
1529 		sata_hba_tran_t *sata_tran = sata_hba_inst->satahba_tran;
1530 		dev_info_t	*mydip = SATA_DIP(sata_hba_inst);
1531 
1532 		SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
1533 		    "IOCTL 0x%2x not supported in SATA framework, "
1534 		    "passthrough to HBA", cmd);
1535 
1536 		if (sata_tran->sata_tran_ioctl == NULL) {
1537 			rv = EINVAL;
1538 			break;
1539 		}
1540 		rval = (*sata_tran->sata_tran_ioctl)(mydip, cmd, arg);
1541 		if (rval != 0) {
1542 			SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
1543 			    "IOCTL 0x%2x failed in HBA", cmd);
1544 			rv = rval;
1545 		}
1546 		break;
1547 	}
1548 
1549 	} /* End of main IOCTL switch */
1550 
1551 	if (dcp) {
1552 		ndi_dc_freehdl(dcp);
1553 	}
1554 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
1555 	cportinfo->cport_event_flags &= ~SATA_APCTL_LOCK_PORT_BUSY;
1556 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
1557 
1558 	return (rv);
1559 }
1560 
1561 
1562 /*
1563  * Create error retrieval sata packet
1564  *
1565  * A sata packet is allocated and set-up to contain specified error retrieval
1566  * command and appropriate dma-able data buffer.
1567  * No association with any scsi packet is made and no callback routine is
1568  * specified.
1569  *
1570  * Returns a pointer to sata packet upon successfull packet creation.
1571  * Returns NULL, if packet cannot be created.
1572  */
1573 sata_pkt_t *
1574 sata_get_error_retrieval_pkt(dev_info_t *dip, sata_device_t *sata_device,
1575     int pkt_type)
1576 {
1577 	sata_hba_inst_t	*sata_hba_inst;
1578 	sata_pkt_txlate_t *spx;
1579 	sata_pkt_t *spkt;
1580 	sata_drive_info_t *sdinfo;
1581 
1582 	mutex_enter(&sata_mutex);
1583 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
1584 	    sata_hba_inst = sata_hba_inst->satahba_next) {
1585 		if (SATA_DIP(sata_hba_inst) == dip)
1586 			break;
1587 	}
1588 	mutex_exit(&sata_mutex);
1589 	ASSERT(sata_hba_inst != NULL);
1590 
1591 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
1592 	if (sdinfo == NULL) {
1593 		sata_log(sata_hba_inst, CE_WARN,
1594 		    "sata: error recovery request for non-attached device at "
1595 		    "cport %d", sata_device->satadev_addr.cport);
1596 		return (NULL);
1597 	}
1598 
1599 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
1600 	spx->txlt_sata_hba_inst = sata_hba_inst;
1601 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
1602 	spkt = sata_pkt_alloc(spx, NULL);
1603 	if (spkt == NULL) {
1604 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
1605 		return (NULL);
1606 	}
1607 	/* address is needed now */
1608 	spkt->satapkt_device.satadev_addr = sata_device->satadev_addr;
1609 
1610 	switch (pkt_type) {
1611 	case SATA_ERR_RETR_PKT_TYPE_NCQ:
1612 		if (sata_ncq_err_ret_cmd_setup(spx, sdinfo) == SATA_SUCCESS)
1613 			return (spkt);
1614 		break;
1615 
1616 	case SATA_ERR_RETR_PKT_TYPE_ATAPI:
1617 		if (sata_atapi_err_ret_cmd_setup(spx, sdinfo) == SATA_SUCCESS)
1618 			return (spkt);
1619 		break;
1620 
1621 	default:
1622 		break;
1623 	}
1624 
1625 	sata_pkt_free(spx);
1626 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
1627 	return (NULL);
1628 
1629 }
1630 
1631 
1632 /*
1633  * Free error retrieval sata packet
1634  *
1635  * Free sata packet and any associated resources allocated previously by
1636  * sata_get_error_retrieval_pkt().
1637  *
1638  * Void return.
1639  */
1640 void
1641 sata_free_error_retrieval_pkt(sata_pkt_t *sata_pkt)
1642 {
1643 	sata_pkt_txlate_t *spx =
1644 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
1645 
1646 	ASSERT(sata_pkt != NULL);
1647 
1648 	sata_free_local_buffer(spx);
1649 	sata_pkt_free(spx);
1650 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
1651 
1652 }
1653 
1654 /*
1655  * sata_name_child is for composing the name of the node
1656  * the format of the name is "target,0".
1657  */
1658 static int
1659 sata_name_child(dev_info_t *dip, char *name, int namelen)
1660 {
1661 	int target;
1662 
1663 	target = ddi_prop_get_int(DDI_DEV_T_ANY, dip,
1664 	    DDI_PROP_DONTPASS, "target", -1);
1665 	if (target == -1)
1666 		return (DDI_FAILURE);
1667 	(void) snprintf(name, namelen, "%x,0", target);
1668 	return (DDI_SUCCESS);
1669 }
1670 
1671 
1672 
1673 /* ****************** SCSA required entry points *********************** */
1674 
1675 /*
1676  * Implementation of scsi tran_tgt_init.
1677  * sata_scsi_tgt_init() initializes scsi_device structure
1678  *
1679  * If successful, DDI_SUCCESS is returned.
1680  * DDI_FAILURE is returned if addressed device does not exist
1681  */
1682 
1683 static int
1684 sata_scsi_tgt_init(dev_info_t *hba_dip, dev_info_t *tgt_dip,
1685     scsi_hba_tran_t *hba_tran, struct scsi_device *sd)
1686 {
1687 #ifndef __lock_lint
1688 	_NOTE(ARGUNUSED(hba_dip))
1689 	_NOTE(ARGUNUSED(tgt_dip))
1690 #endif
1691 	sata_device_t		sata_device;
1692 	sata_drive_info_t	*sdinfo;
1693 	struct sata_id		*sid;
1694 	sata_hba_inst_t		*sata_hba_inst;
1695 	char			model[SATA_ID_MODEL_LEN + 1];
1696 	char			fw[SATA_ID_FW_LEN + 1];
1697 	char			*vid, *pid;
1698 	int			i;
1699 
1700 	/*
1701 	 * Fail tran_tgt_init for .conf stub node
1702 	 */
1703 	if (ndi_dev_is_persistent_node(tgt_dip) == 0) {
1704 		(void) ndi_merge_node(tgt_dip, sata_name_child);
1705 		ddi_set_name_addr(tgt_dip, NULL);
1706 		return (DDI_FAILURE);
1707 	}
1708 
1709 	sata_hba_inst = (sata_hba_inst_t *)(hba_tran->tran_hba_private);
1710 
1711 	/* Validate scsi device address */
1712 	if (sata_validate_scsi_address(sata_hba_inst, &sd->sd_address,
1713 	    &sata_device) != 0)
1714 		return (DDI_FAILURE);
1715 
1716 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
1717 	    sata_device.satadev_addr.cport)));
1718 
1719 	/* sata_device now contains a valid sata address */
1720 	sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
1721 	if (sdinfo == NULL) {
1722 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
1723 		    sata_device.satadev_addr.cport)));
1724 		return (DDI_FAILURE);
1725 	}
1726 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
1727 	    sata_device.satadev_addr.cport)));
1728 
1729 	/*
1730 	 * Check if we need to create a legacy devid (i.e cmdk style) for
1731 	 * the target disks.
1732 	 *
1733 	 * HBA devinfo node will have the property "use-cmdk-devid-format"
1734 	 * if we need to create cmdk-style devid for all the disk devices
1735 	 * attached to this controller. This property may have been set
1736 	 * from HBA driver's .conf file or by the HBA driver in its
1737 	 * attach(9F) function.
1738 	 */
1739 	if ((sdinfo->satadrv_type == SATA_DTYPE_ATADISK) &&
1740 	    (ddi_getprop(DDI_DEV_T_ANY, hba_dip, DDI_PROP_DONTPASS,
1741 	    "use-cmdk-devid-format", 0) == 1)) {
1742 		/* register a legacy devid for this target node */
1743 		sata_target_devid_register(tgt_dip, sdinfo);
1744 	}
1745 
1746 
1747 	/*
1748 	 * 'Identify Device Data' does not always fit in standard SCSI
1749 	 * INQUIRY data, so establish INQUIRY_* properties with full-form
1750 	 * of information.
1751 	 */
1752 	sid = &sdinfo->satadrv_id;
1753 #ifdef	_LITTLE_ENDIAN
1754 	swab(sid->ai_model, model, SATA_ID_MODEL_LEN);
1755 	swab(sid->ai_fw, fw, SATA_ID_FW_LEN);
1756 #else	/* _LITTLE_ENDIAN */
1757 	bcopy(sid->ai_model, model, SATA_ID_MODEL_LEN);
1758 	bcopy(sid->ai_fw, fw, SATA_ID_FW_LEN);
1759 #endif	/* _LITTLE_ENDIAN */
1760 	model[SATA_ID_MODEL_LEN] = 0;
1761 	fw[SATA_ID_FW_LEN] = 0;
1762 
1763 	/* split model into into vid/pid */
1764 	for (i = 0, pid = model; i < SATA_ID_MODEL_LEN; i++, pid++)
1765 		if ((*pid == ' ') || (*pid == '\t'))
1766 			break;
1767 	if (i < SATA_ID_MODEL_LEN) {
1768 		vid = model;
1769 		*pid++ = 0;		/* terminate vid, establish pid */
1770 	} else {
1771 		vid = NULL;		/* vid will stay "ATA     " */
1772 		pid = model;		/* model is all pid */
1773 	}
1774 
1775 	if (vid)
1776 		(void) scsi_hba_prop_update_inqstring(sd, INQUIRY_VENDOR_ID,
1777 		    vid, strlen(vid));
1778 	if (pid)
1779 		(void) scsi_hba_prop_update_inqstring(sd, INQUIRY_PRODUCT_ID,
1780 		    pid, strlen(pid));
1781 	(void) scsi_hba_prop_update_inqstring(sd, INQUIRY_REVISION_ID,
1782 	    fw, strlen(fw));
1783 
1784 	return (DDI_SUCCESS);
1785 }
1786 
1787 /*
1788  * Implementation of scsi tran_tgt_probe.
1789  * Probe target, by calling default scsi routine scsi_hba_probe()
1790  */
1791 static int
1792 sata_scsi_tgt_probe(struct scsi_device *sd, int (*callback)(void))
1793 {
1794 	sata_hba_inst_t *sata_hba_inst =
1795 	    (sata_hba_inst_t *)(sd->sd_address.a_hba_tran->tran_hba_private);
1796 	int rval;
1797 
1798 	rval = scsi_hba_probe(sd, callback);
1799 
1800 	if (rval == SCSIPROBE_EXISTS) {
1801 		/*
1802 		 * Set property "pm-capable" on the target device node, so that
1803 		 * the target driver will not try to fetch scsi cycle counters
1804 		 * before enabling device power-management.
1805 		 */
1806 		if ((ddi_prop_update_int(DDI_DEV_T_NONE, sd->sd_dev,
1807 		    "pm-capable", 1)) != DDI_PROP_SUCCESS) {
1808 			sata_log(sata_hba_inst, CE_WARN,
1809 			    "SATA device at port %d: "
1810 			    "will not be power-managed ",
1811 			    SCSI_TO_SATA_CPORT(sd->sd_address.a_target));
1812 			SATA_LOG_D((sata_hba_inst, CE_WARN,
1813 			    "failure updating pm-capable property"));
1814 		}
1815 	}
1816 	return (rval);
1817 }
1818 
1819 /*
1820  * Implementation of scsi tran_tgt_free.
1821  * Release all resources allocated for scsi_device
1822  */
1823 static void
1824 sata_scsi_tgt_free(dev_info_t *hba_dip, dev_info_t *tgt_dip,
1825     scsi_hba_tran_t *hba_tran, struct scsi_device *sd)
1826 {
1827 #ifndef __lock_lint
1828 	_NOTE(ARGUNUSED(hba_dip))
1829 #endif
1830 	sata_device_t		sata_device;
1831 	sata_drive_info_t	*sdinfo;
1832 	sata_hba_inst_t		*sata_hba_inst;
1833 	ddi_devid_t		devid;
1834 
1835 	sata_hba_inst = (sata_hba_inst_t *)(hba_tran->tran_hba_private);
1836 
1837 	/* Validate scsi device address */
1838 	if (sata_validate_scsi_address(sata_hba_inst, &sd->sd_address,
1839 	    &sata_device) != 0)
1840 		return;
1841 
1842 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
1843 	    sata_device.satadev_addr.cport)));
1844 
1845 	/* sata_device now should contain a valid sata address */
1846 	sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
1847 	if (sdinfo == NULL) {
1848 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
1849 		    sata_device.satadev_addr.cport)));
1850 		return;
1851 	}
1852 	/*
1853 	 * We did not allocate any resources in sata_scsi_tgt_init()
1854 	 * other than few properties.
1855 	 * Free them.
1856 	 */
1857 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
1858 	    sata_device.satadev_addr.cport)));
1859 	(void) ndi_prop_remove(DDI_DEV_T_NONE, tgt_dip, "pm-capable");
1860 
1861 	/*
1862 	 * If devid was previously created but not freed up from
1863 	 * sd(7D) driver (i.e during detach(9F)) then do it here.
1864 	 */
1865 	if ((sdinfo->satadrv_type == SATA_DTYPE_ATADISK) &&
1866 	    (ddi_getprop(DDI_DEV_T_ANY, hba_dip, DDI_PROP_DONTPASS,
1867 	    "use-cmdk-devid-format", 0) == 1) &&
1868 	    (ddi_devid_get(tgt_dip, &devid) == DDI_SUCCESS)) {
1869 		ddi_devid_unregister(tgt_dip);
1870 		ddi_devid_free(devid);
1871 	}
1872 }
1873 
1874 /*
1875  * Implementation of scsi tran_init_pkt
1876  * Upon successful return, scsi pkt buffer has DMA resources allocated.
1877  *
1878  * It seems that we should always allocate pkt, even if the address is
1879  * for non-existing device - just use some default for dma_attr.
1880  * The reason is that there is no way to communicate this to a caller here.
1881  * Subsequent call to sata_scsi_start may fail appropriately.
1882  * Simply returning NULL does not seem to discourage a target driver...
1883  *
1884  * Returns a pointer to initialized scsi_pkt, or NULL otherwise.
1885  */
1886 static struct scsi_pkt *
1887 sata_scsi_init_pkt(struct scsi_address *ap, struct scsi_pkt *pkt,
1888     struct buf *bp, int cmdlen, int statuslen, int tgtlen, int flags,
1889     int (*callback)(caddr_t), caddr_t arg)
1890 {
1891 	sata_hba_inst_t *sata_hba_inst =
1892 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
1893 	dev_info_t *dip = SATA_DIP(sata_hba_inst);
1894 	sata_device_t sata_device;
1895 	sata_drive_info_t *sdinfo;
1896 	sata_pkt_txlate_t *spx;
1897 	ddi_dma_attr_t cur_dma_attr;
1898 	int rval;
1899 	boolean_t new_pkt = TRUE;
1900 
1901 	ASSERT(ap->a_hba_tran->tran_hba_dip == dip);
1902 
1903 	/*
1904 	 * We need to translate the address, even if it could be
1905 	 * a bogus one, for a non-existing device
1906 	 */
1907 	sata_device.satadev_addr.qual = SCSI_TO_SATA_ADDR_QUAL(ap->a_target);
1908 	sata_device.satadev_addr.cport = SCSI_TO_SATA_CPORT(ap->a_target);
1909 	sata_device.satadev_addr.pmport = SCSI_TO_SATA_PMPORT(ap->a_target);
1910 	sata_device.satadev_rev = SATA_DEVICE_REV;
1911 
1912 	if (pkt == NULL) {
1913 		/*
1914 		 * Have to allocate a brand new scsi packet.
1915 		 * We need to operate with auto request sense enabled.
1916 		 */
1917 		pkt = scsi_hba_pkt_alloc(dip, ap, cmdlen,
1918 		    MAX(statuslen, sizeof (struct scsi_arq_status)),
1919 		    tgtlen, sizeof (sata_pkt_txlate_t), callback, arg);
1920 
1921 		if (pkt == NULL)
1922 			return (NULL);
1923 
1924 		/* Fill scsi packet structure */
1925 		pkt->pkt_comp		= (void (*)())NULL;
1926 		pkt->pkt_time		= 0;
1927 		pkt->pkt_resid		= 0;
1928 		pkt->pkt_statistics	= 0;
1929 		pkt->pkt_reason		= 0;
1930 
1931 		/*
1932 		 * pkt_hba_private will point to sata pkt txlate structure
1933 		 */
1934 		spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
1935 		bzero(spx, sizeof (sata_pkt_txlate_t));
1936 
1937 		spx->txlt_scsi_pkt = pkt;
1938 		spx->txlt_sata_hba_inst = sata_hba_inst;
1939 
1940 		/* Allocate sata_pkt */
1941 		spx->txlt_sata_pkt = sata_pkt_alloc(spx, callback);
1942 		if (spx->txlt_sata_pkt == NULL) {
1943 			/* Could not allocate sata pkt */
1944 			scsi_hba_pkt_free(ap, pkt);
1945 			return (NULL);
1946 		}
1947 		/* Set sata address */
1948 		spx->txlt_sata_pkt->satapkt_device.satadev_addr =
1949 		    sata_device.satadev_addr;
1950 		spx->txlt_sata_pkt->satapkt_device.satadev_rev =
1951 		    sata_device.satadev_rev;
1952 
1953 		if ((bp == NULL) || (bp->b_bcount == 0))
1954 			return (pkt);
1955 
1956 		spx->txlt_total_residue = bp->b_bcount;
1957 	} else {
1958 		new_pkt = FALSE;
1959 		/*
1960 		 * Packet was preallocated/initialized by previous call
1961 		 */
1962 		spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
1963 
1964 		if ((bp == NULL) || (bp->b_bcount == 0)) {
1965 			return (pkt);
1966 		}
1967 
1968 		/* Pkt is available already: spx->txlt_scsi_pkt == pkt; */
1969 	}
1970 
1971 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = bp;
1972 
1973 	/*
1974 	 * We use an adjusted version of the dma_attr, to account
1975 	 * for device addressing limitations.
1976 	 * sata_adjust_dma_attr() will handle sdinfo == NULL which may
1977 	 * happen when a device is not yet configured.
1978 	 */
1979 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
1980 	    sata_device.satadev_addr.cport)));
1981 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
1982 	    &spx->txlt_sata_pkt->satapkt_device);
1983 	/* NULL sdinfo may be passsed to sata_adjust_dma_attr() */
1984 	sata_adjust_dma_attr(sdinfo,
1985 	    SATA_DMA_ATTR(spx->txlt_sata_hba_inst), &cur_dma_attr);
1986 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
1987 	    sata_device.satadev_addr.cport)));
1988 	/*
1989 	 * Allocate necessary DMA resources for the packet's data buffer
1990 	 * NOTE:
1991 	 * In case of read/write commands, DMA resource allocation here is
1992 	 * based on the premise that the transfer length specified in
1993 	 * the read/write scsi cdb will match exactly DMA resources -
1994 	 * returning correct packet residue is crucial.
1995 	 */
1996 	if ((rval = sata_dma_buf_setup(spx, flags, callback, arg,
1997 	    &cur_dma_attr)) != DDI_SUCCESS) {
1998 		/*
1999 		 * If a DMA allocation request fails with
2000 		 * DDI_DMA_NOMAPPING, indicate the error by calling
2001 		 * bioerror(9F) with bp and an error code of EFAULT.
2002 		 * If a DMA allocation request fails with
2003 		 * DDI_DMA_TOOBIG, indicate the error by calling
2004 		 * bioerror(9F) with bp and an error code of EINVAL.
2005 		 * For DDI_DMA_NORESOURCES, we may have some of them allocated.
2006 		 * Request may be repeated later - there is no real error.
2007 		 */
2008 		switch (rval) {
2009 		case DDI_DMA_NORESOURCES:
2010 			bioerror(bp, 0);
2011 			break;
2012 		case DDI_DMA_NOMAPPING:
2013 		case DDI_DMA_BADATTR:
2014 			bioerror(bp, EFAULT);
2015 			break;
2016 		case DDI_DMA_TOOBIG:
2017 		default:
2018 			bioerror(bp, EINVAL);
2019 			break;
2020 		}
2021 		if (new_pkt == TRUE) {
2022 			/*
2023 			 * Since this is a new packet, we can clean-up
2024 			 * everything
2025 			 */
2026 			sata_scsi_destroy_pkt(ap, pkt);
2027 		} else {
2028 			/*
2029 			 * This is a re-used packet. It will be target driver's
2030 			 * responsibility to eventually destroy it (which
2031 			 * will free allocated resources).
2032 			 * Here, we just "complete" the request, leaving
2033 			 * allocated resources intact, so the request may
2034 			 * be retried.
2035 			 */
2036 			spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
2037 			sata_pkt_free(spx);
2038 		}
2039 		return (NULL);
2040 	}
2041 	/* Set number of bytes that are not yet accounted for */
2042 	pkt->pkt_resid = spx->txlt_total_residue;
2043 	ASSERT(pkt->pkt_resid >= 0);
2044 
2045 	return (pkt);
2046 }
2047 
2048 /*
2049  * Implementation of scsi tran_start.
2050  * Translate scsi cmd into sata operation and return status.
2051  * ATAPI CDBs are passed to ATAPI devices - the device determines what commands
2052  * are supported.
2053  * For SATA hard disks, supported scsi commands:
2054  * SCMD_INQUIRY
2055  * SCMD_TEST_UNIT_READY
2056  * SCMD_START_STOP
2057  * SCMD_READ_CAPACITY
2058  * SCMD_REQUEST_SENSE
2059  * SCMD_LOG_SENSE_G1
2060  * SCMD_LOG_SELECT_G1
2061  * SCMD_MODE_SENSE	(specific pages)
2062  * SCMD_MODE_SENSE_G1	(specific pages)
2063  * SCMD_MODE_SELECT	(specific pages)
2064  * SCMD_MODE_SELECT_G1	(specific pages)
2065  * SCMD_SYNCHRONIZE_CACHE
2066  * SCMD_SYNCHRONIZE_CACHE_G1
2067  * SCMD_READ
2068  * SCMD_READ_G1
2069  * SCMD_READ_G4
2070  * SCMD_READ_G5
2071  * SCMD_WRITE
2072  * SCMD_WRITE_BUFFER
2073  * SCMD_WRITE_G1
2074  * SCMD_WRITE_G4
2075  * SCMD_WRITE_G5
2076  * SCMD_SEEK		(noop)
2077  * SCMD_SDIAG
2078  *
2079  * All other commands are rejected as unsupported.
2080  *
2081  * Returns:
2082  * TRAN_ACCEPT if command was executed successfully or accepted by HBA driver
2083  * for execution. TRAN_ACCEPT may be returned also if device was removed but
2084  * a callback could be scheduled.
2085  * TRAN_BADPKT if cmd was directed to invalid address.
2086  * TRAN_FATAL_ERROR is command was rejected due to hardware error, including
2087  * some unspecified error. TRAN_FATAL_ERROR may be also returned if a device
2088  * was removed and there was no callback specified in scsi pkt.
2089  * TRAN_BUSY if command could not be executed becasue HBA driver or SATA
2090  * framework was busy performing some other operation(s).
2091  *
2092  */
2093 static int
2094 sata_scsi_start(struct scsi_address *ap, struct scsi_pkt *pkt)
2095 {
2096 	sata_hba_inst_t *sata_hba_inst =
2097 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2098 	sata_pkt_txlate_t *spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
2099 	sata_drive_info_t *sdinfo;
2100 	struct buf *bp;
2101 	int cport;
2102 	int rval;
2103 
2104 	SATADBG1(SATA_DBG_SCSI_IF, sata_hba_inst,
2105 	    "sata_scsi_start: cmd 0x%02x\n", pkt->pkt_cdbp[0]);
2106 
2107 	ASSERT(spx != NULL &&
2108 	    spx->txlt_scsi_pkt == pkt && spx->txlt_sata_pkt != NULL);
2109 
2110 	cport = SCSI_TO_SATA_CPORT(ap->a_target);
2111 
2112 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
2113 	sdinfo = sata_get_device_info(sata_hba_inst,
2114 	    &spx->txlt_sata_pkt->satapkt_device);
2115 	if (sdinfo == NULL ||
2116 	    SATA_CPORT_INFO(sata_hba_inst, cport)->cport_tgtnode_clean ==
2117 	    B_FALSE ||
2118 	    (sdinfo->satadrv_state & SATA_DSTATE_FAILED) != 0) {
2119 
2120 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
2121 		pkt->pkt_reason = CMD_DEV_GONE;
2122 		/*
2123 		 * The sd target driver is checking CMD_DEV_GONE pkt_reason
2124 		 * only in callback function (for normal requests) and
2125 		 * in the dump code path.
2126 		 * So, if the callback is available, we need to do
2127 		 * the callback rather than returning TRAN_FATAL_ERROR here.
2128 		 */
2129 		if (pkt->pkt_comp != NULL) {
2130 			/* scsi callback required */
2131 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
2132 			    (task_func_t *)pkt->pkt_comp,
2133 			    (void *)pkt, TQ_SLEEP) == NULL)
2134 				/* Scheduling the callback failed */
2135 				return (TRAN_BUSY);
2136 			return (TRAN_ACCEPT);
2137 		}
2138 		/* No callback available */
2139 		return (TRAN_FATAL_ERROR);
2140 	}
2141 
2142 	if (sdinfo->satadrv_type & SATA_DTYPE_ATAPI) {
2143 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
2144 		rval = sata_txlt_atapi(spx);
2145 		SATADBG1(SATA_DBG_SCSI_IF, sata_hba_inst,
2146 		    "sata_scsi_start atapi: rval %d\n", rval);
2147 		return (rval);
2148 	}
2149 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
2150 
2151 	/* ATA Disk commands processing starts here */
2152 
2153 	bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
2154 
2155 	switch (pkt->pkt_cdbp[0]) {
2156 
2157 	case SCMD_INQUIRY:
2158 		/* Mapped to identify device */
2159 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2160 			bp_mapin(bp);
2161 		rval = sata_txlt_inquiry(spx);
2162 		break;
2163 
2164 	case SCMD_TEST_UNIT_READY:
2165 		/*
2166 		 * SAT "SATA to ATA Translation" doc specifies translation
2167 		 * to ATA CHECK POWER MODE.
2168 		 */
2169 		rval = sata_txlt_test_unit_ready(spx);
2170 		break;
2171 
2172 	case SCMD_START_STOP:
2173 		/* Mapping depends on the command */
2174 		rval = sata_txlt_start_stop_unit(spx);
2175 		break;
2176 
2177 	case SCMD_READ_CAPACITY:
2178 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2179 			bp_mapin(bp);
2180 		rval = sata_txlt_read_capacity(spx);
2181 		break;
2182 
2183 	case SCMD_REQUEST_SENSE:
2184 		/*
2185 		 * Always No Sense, since we force ARQ
2186 		 */
2187 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2188 			bp_mapin(bp);
2189 		rval = sata_txlt_request_sense(spx);
2190 		break;
2191 
2192 	case SCMD_LOG_SENSE_G1:
2193 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2194 			bp_mapin(bp);
2195 		rval = sata_txlt_log_sense(spx);
2196 		break;
2197 
2198 	case SCMD_LOG_SELECT_G1:
2199 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2200 			bp_mapin(bp);
2201 		rval = sata_txlt_log_select(spx);
2202 		break;
2203 
2204 	case SCMD_MODE_SENSE:
2205 	case SCMD_MODE_SENSE_G1:
2206 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2207 			bp_mapin(bp);
2208 		rval = sata_txlt_mode_sense(spx);
2209 		break;
2210 
2211 
2212 	case SCMD_MODE_SELECT:
2213 	case SCMD_MODE_SELECT_G1:
2214 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2215 			bp_mapin(bp);
2216 		rval = sata_txlt_mode_select(spx);
2217 		break;
2218 
2219 	case SCMD_SYNCHRONIZE_CACHE:
2220 	case SCMD_SYNCHRONIZE_CACHE_G1:
2221 		rval = sata_txlt_synchronize_cache(spx);
2222 		break;
2223 
2224 	case SCMD_READ:
2225 	case SCMD_READ_G1:
2226 	case SCMD_READ_G4:
2227 	case SCMD_READ_G5:
2228 		rval = sata_txlt_read(spx);
2229 		break;
2230 	case SCMD_WRITE_BUFFER:
2231 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2232 			bp_mapin(bp);
2233 		rval = sata_txlt_write_buffer(spx);
2234 		break;
2235 
2236 	case SCMD_WRITE:
2237 	case SCMD_WRITE_G1:
2238 	case SCMD_WRITE_G4:
2239 	case SCMD_WRITE_G5:
2240 		rval = sata_txlt_write(spx);
2241 		break;
2242 
2243 	case SCMD_SEEK:
2244 		rval = sata_txlt_nodata_cmd_immediate(spx);
2245 		break;
2246 
2247 		/* Other cases will be filed later */
2248 		/* postponed until phase 2 of the development */
2249 	default:
2250 		rval = sata_txlt_invalid_command(spx);
2251 		break;
2252 	}
2253 
2254 	SATADBG1(SATA_DBG_SCSI_IF, sata_hba_inst,
2255 	    "sata_scsi_start: rval %d\n", rval);
2256 
2257 	return (rval);
2258 }
2259 
2260 /*
2261  * Implementation of scsi tran_abort.
2262  * Abort specific pkt or all packets.
2263  *
2264  * Returns 1 if one or more packets were aborted, returns 0 otherwise
2265  *
2266  * May be called from an interrupt level.
2267  */
2268 static int
2269 sata_scsi_abort(struct scsi_address *ap, struct scsi_pkt *scsi_pkt)
2270 {
2271 	sata_hba_inst_t *sata_hba_inst =
2272 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2273 	sata_device_t	sata_device;
2274 	sata_pkt_t	*sata_pkt;
2275 
2276 	SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
2277 	    "sata_scsi_abort: %s at target: 0x%x\n",
2278 	    scsi_pkt == NULL ? "all packets" : "one pkt", ap->a_target);
2279 
2280 	/* Validate address */
2281 	if (sata_validate_scsi_address(sata_hba_inst, ap, &sata_device) != 0)
2282 		/* Invalid address */
2283 		return (0);
2284 
2285 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2286 	    sata_device.satadev_addr.cport)));
2287 	if (sata_get_device_info(sata_hba_inst, &sata_device) == NULL) {
2288 		/* invalid address */
2289 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2290 		    sata_device.satadev_addr.cport)));
2291 		return (0);
2292 	}
2293 	if (scsi_pkt == NULL) {
2294 		/*
2295 		 * Abort all packets.
2296 		 * Although we do not have specific packet, we still need
2297 		 * dummy packet structure to pass device address to HBA.
2298 		 * Allocate one, without sleeping. Fail if pkt cannot be
2299 		 * allocated.
2300 		 */
2301 		sata_pkt = kmem_zalloc(sizeof (sata_pkt_t), KM_NOSLEEP);
2302 		if (sata_pkt == NULL) {
2303 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2304 			    sata_device.satadev_addr.cport)));
2305 			SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_pkt_abort: "
2306 			    "could not allocate sata_pkt"));
2307 			return (0);
2308 		}
2309 		sata_pkt->satapkt_rev = SATA_PKT_REV;
2310 		sata_pkt->satapkt_device = sata_device;
2311 		sata_pkt->satapkt_device.satadev_rev = SATA_DEVICE_REV;
2312 	} else {
2313 		if (scsi_pkt->pkt_ha_private == NULL) {
2314 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2315 			    sata_device.satadev_addr.cport)));
2316 			return (0); /* Bad scsi pkt */
2317 		}
2318 		/* extract pointer to sata pkt */
2319 		sata_pkt = ((sata_pkt_txlate_t *)scsi_pkt->pkt_ha_private)->
2320 		    txlt_sata_pkt;
2321 	}
2322 
2323 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2324 	    sata_device.satadev_addr.cport)));
2325 	/* Send abort request to HBA */
2326 	if ((*SATA_ABORT_FUNC(sata_hba_inst))
2327 	    (SATA_DIP(sata_hba_inst), sata_pkt,
2328 	    scsi_pkt == NULL ? SATA_ABORT_ALL_PACKETS : SATA_ABORT_PACKET) ==
2329 	    SATA_SUCCESS) {
2330 		if (scsi_pkt == NULL)
2331 			kmem_free(sata_pkt, sizeof (sata_pkt_t));
2332 		/* Success */
2333 		return (1);
2334 	}
2335 	/* Else, something did not go right */
2336 	if (scsi_pkt == NULL)
2337 		kmem_free(sata_pkt, sizeof (sata_pkt_t));
2338 	/* Failure */
2339 	return (0);
2340 }
2341 
2342 
2343 /*
2344  * Implementation of scsi tran_reset.
2345  * RESET_ALL request is translated into port reset.
2346  * RESET_TARGET requests is translated into a device reset,
2347  * RESET_LUN request is accepted only for LUN 0 and translated into
2348  * device reset.
2349  * The target reset should cause all HBA active and queued packets to
2350  * be terminated and returned with pkt reason SATA_PKT_RESET prior to
2351  * the return. HBA should report reset event for the device.
2352  *
2353  * Returns 1 upon success, 0 upon failure.
2354  */
2355 static int
2356 sata_scsi_reset(struct scsi_address *ap, int level)
2357 {
2358 	sata_hba_inst_t	*sata_hba_inst =
2359 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2360 	sata_device_t	sata_device;
2361 	int		val;
2362 
2363 	SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
2364 	    "sata_scsi_reset: level %d target: 0x%x\n",
2365 	    level, ap->a_target);
2366 
2367 	/* Validate address */
2368 	val = sata_validate_scsi_address(sata_hba_inst, ap, &sata_device);
2369 	if (val == -1)
2370 		/* Invalid address */
2371 		return (0);
2372 
2373 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2374 	    sata_device.satadev_addr.cport)));
2375 	if (sata_get_device_info(sata_hba_inst, &sata_device) == NULL) {
2376 		/* invalid address */
2377 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2378 		    sata_device.satadev_addr.cport)));
2379 		return (0);
2380 	}
2381 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2382 	    sata_device.satadev_addr.cport)));
2383 	if (level == RESET_ALL) {
2384 		/* port reset - cport only */
2385 		sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
2386 		if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))
2387 		    (SATA_DIP(sata_hba_inst), &sata_device) == SATA_SUCCESS)
2388 			return (1);
2389 		else
2390 			return (0);
2391 
2392 	} else if (val == 0 &&
2393 	    (level == RESET_TARGET || level == RESET_LUN)) {
2394 		/* reset device (device attached) */
2395 		if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))
2396 		    (SATA_DIP(sata_hba_inst), &sata_device) == SATA_SUCCESS)
2397 			return (1);
2398 		else
2399 			return (0);
2400 	}
2401 	return (0);
2402 }
2403 
2404 
2405 /*
2406  * Implementation of scsi tran_getcap (get transport/device capabilities).
2407  * Supported capabilities for SATA hard disks:
2408  * auto-rqsense		(always supported)
2409  * tagged-qing		(supported if HBA supports it)
2410  * untagged-qing	(could be supported if disk supports it, but because
2411  *			 caching behavior allowing untagged queuing actually
2412  *			 results in reduced performance.  sd tries to throttle
2413  *			 back to only 3 outstanding commands, which may
2414  *			 work for real SCSI disks, but with read ahead
2415  *			 caching, having more than 1 outstanding command
2416  *			 results in cache thrashing.)
2417  * sector_size
2418  * dma_max
2419  * interconnect-type	(INTERCONNECT_SATA)
2420  *
2421  * Supported capabilities for ATAPI CD/DVD devices:
2422  * auto-rqsense		(always supported)
2423  * sector_size
2424  * dma_max
2425  * max-cdb-length
2426  * interconnect-type	(INTERCONNECT_SATA)
2427  *
2428  * Supported capabilities for ATAPI TAPE devices:
2429  * auto-rqsense		(always supported)
2430  * dma_max
2431  * max-cdb-length
2432  *
2433  * Supported capabilities for SATA ATAPI hard disks:
2434  * auto-rqsense		(always supported)
2435  * interconnect-type	(INTERCONNECT_SATA)
2436  * max-cdb-length
2437  *
2438  * Request for other capabilities is rejected as unsupported.
2439  *
2440  * Returns supported capability value, or -1 if capability is unsuppported or
2441  * the address is invalid - no device.
2442  */
2443 
2444 static int
2445 sata_scsi_getcap(struct scsi_address *ap, char *cap, int whom)
2446 {
2447 
2448 	sata_hba_inst_t 	*sata_hba_inst =
2449 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2450 	sata_device_t		sata_device;
2451 	sata_drive_info_t	*sdinfo;
2452 	ddi_dma_attr_t		adj_dma_attr;
2453 	int 			rval;
2454 
2455 	SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
2456 	    "sata_scsi_getcap: target: 0x%x, cap: %s\n",
2457 	    ap->a_target, cap);
2458 
2459 	/*
2460 	 * We want to process the capabilities on per port granularity.
2461 	 * So, we are specifically restricting ourselves to whom != 0
2462 	 * to exclude the controller wide handling.
2463 	 */
2464 	if (cap == NULL || whom == 0)
2465 		return (-1);
2466 
2467 	if (sata_validate_scsi_address(sata_hba_inst, ap, &sata_device) != 0) {
2468 		/* Invalid address */
2469 		return (-1);
2470 	}
2471 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2472 	    sata_device.satadev_addr.cport)));
2473 	if ((sdinfo = sata_get_device_info(sata_hba_inst, &sata_device)) ==
2474 	    NULL) {
2475 		/* invalid address */
2476 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2477 		    sata_device.satadev_addr.cport)));
2478 		return (-1);
2479 	}
2480 
2481 	switch (scsi_hba_lookup_capstr(cap)) {
2482 	case SCSI_CAP_ARQ:
2483 		rval = 1;		/* ARQ supported, turned on */
2484 		break;
2485 
2486 	case SCSI_CAP_SECTOR_SIZE:
2487 		if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK)
2488 			rval = SATA_DISK_SECTOR_SIZE;	/* fixed size */
2489 		else if (sdinfo->satadrv_type == SATA_DTYPE_ATAPICD)
2490 			rval = SATA_ATAPI_SECTOR_SIZE;
2491 		else rval = -1;
2492 		break;
2493 
2494 	/*
2495 	 * untagged queuing cause a performance inversion because of
2496 	 * the way sd operates.  Because of this reason we do not
2497 	 * use it when available.
2498 	 */
2499 	case SCSI_CAP_UNTAGGED_QING:
2500 		if (sdinfo->satadrv_features_enabled &
2501 		    SATA_DEV_F_E_UNTAGGED_QING)
2502 			rval = 1;	/* Untagged queuing available */
2503 		else
2504 			rval = -1;	/* Untagged queuing not available */
2505 		break;
2506 
2507 	case SCSI_CAP_TAGGED_QING:
2508 		if ((sdinfo->satadrv_features_enabled &
2509 		    SATA_DEV_F_E_TAGGED_QING) &&
2510 		    (sdinfo->satadrv_max_queue_depth > 1))
2511 			rval = 1;	/* Tagged queuing available */
2512 		else
2513 			rval = -1;	/* Tagged queuing not available */
2514 		break;
2515 
2516 	case SCSI_CAP_DMA_MAX:
2517 		sata_adjust_dma_attr(sdinfo, SATA_DMA_ATTR(sata_hba_inst),
2518 		    &adj_dma_attr);
2519 		rval = (int)adj_dma_attr.dma_attr_maxxfer;
2520 		/* We rely on the fact that dma_attr_maxxfer < 0x80000000 */
2521 		break;
2522 
2523 	case SCSI_CAP_INTERCONNECT_TYPE:
2524 		rval = INTERCONNECT_SATA;	/* SATA interconnect type */
2525 		break;
2526 
2527 	case SCSI_CAP_CDB_LEN:
2528 		if (sdinfo->satadrv_type & SATA_DTYPE_ATAPI)
2529 			rval = sdinfo->satadrv_atapi_cdb_len;
2530 		else
2531 			rval = -1;
2532 		break;
2533 
2534 	default:
2535 		rval = -1;
2536 		break;
2537 	}
2538 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2539 	    sata_device.satadev_addr.cport)));
2540 	return (rval);
2541 }
2542 
2543 /*
2544  * Implementation of scsi tran_setcap
2545  *
2546  * Only SCSI_CAP_UNTAGGED_QING and  SCSI_CAP_TAGGED_QING are changeable.
2547  *
2548  */
2549 static int
2550 sata_scsi_setcap(struct scsi_address *ap, char *cap, int value, int whom)
2551 {
2552 	sata_hba_inst_t	*sata_hba_inst =
2553 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2554 	sata_device_t	sata_device;
2555 	sata_drive_info_t	*sdinfo;
2556 	int		rval;
2557 
2558 	SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
2559 	    "sata_scsi_setcap: target: 0x%x, cap: %s\n", ap->a_target, cap);
2560 
2561 	/*
2562 	 * We want to process the capabilities on per port granularity.
2563 	 * So, we are specifically restricting ourselves to whom != 0
2564 	 * to exclude the controller wide handling.
2565 	 */
2566 	if (cap == NULL || whom == 0) {
2567 		return (-1);
2568 	}
2569 
2570 	if (sata_validate_scsi_address(sata_hba_inst, ap, &sata_device) != 0) {
2571 		/* Invalid address */
2572 		return (-1);
2573 	}
2574 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2575 	    sata_device.satadev_addr.cport)));
2576 	if ((sdinfo = sata_get_device_info(sata_hba_inst,
2577 	    &sata_device)) == NULL) {
2578 		/* invalid address */
2579 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2580 		    sata_device.satadev_addr.cport)));
2581 		return (-1);
2582 	}
2583 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2584 	    sata_device.satadev_addr.cport)));
2585 
2586 	switch (scsi_hba_lookup_capstr(cap)) {
2587 	case SCSI_CAP_ARQ:
2588 	case SCSI_CAP_SECTOR_SIZE:
2589 	case SCSI_CAP_DMA_MAX:
2590 	case SCSI_CAP_INTERCONNECT_TYPE:
2591 		rval = 0;
2592 		break;
2593 	case SCSI_CAP_UNTAGGED_QING:
2594 		if (SATA_QDEPTH(sata_hba_inst) > 1) {
2595 			rval = 1;
2596 			if (value == 1) {
2597 				sdinfo->satadrv_features_enabled |=
2598 				    SATA_DEV_F_E_UNTAGGED_QING;
2599 			} else if (value == 0) {
2600 				sdinfo->satadrv_features_enabled &=
2601 				    ~SATA_DEV_F_E_UNTAGGED_QING;
2602 			} else {
2603 				rval = -1;
2604 			}
2605 		} else {
2606 			rval = 0;
2607 		}
2608 		break;
2609 	case SCSI_CAP_TAGGED_QING:
2610 		/* This can TCQ or NCQ */
2611 		if (sata_func_enable & SATA_ENABLE_QUEUING &&
2612 		    ((sdinfo->satadrv_features_support & SATA_DEV_F_TCQ &&
2613 		    SATA_FEATURES(sata_hba_inst) & SATA_CTLF_QCMD) ||
2614 		    (sata_func_enable & SATA_ENABLE_NCQ &&
2615 		    sdinfo->satadrv_features_support & SATA_DEV_F_NCQ &&
2616 		    SATA_FEATURES(sata_hba_inst) & SATA_CTLF_NCQ)) &&
2617 		    (sdinfo->satadrv_max_queue_depth > 1)) {
2618 			rval = 1;
2619 			if (value == 1) {
2620 				sdinfo->satadrv_features_enabled |=
2621 				    SATA_DEV_F_E_TAGGED_QING;
2622 			} else if (value == 0) {
2623 				sdinfo->satadrv_features_enabled &=
2624 				    ~SATA_DEV_F_E_TAGGED_QING;
2625 			} else {
2626 				rval = -1;
2627 			}
2628 		} else {
2629 			rval = 0;
2630 		}
2631 		break;
2632 	default:
2633 		rval = -1;
2634 		break;
2635 	}
2636 	return (rval);
2637 }
2638 
2639 /*
2640  * Implementations of scsi tran_destroy_pkt.
2641  * Free resources allocated by sata_scsi_init_pkt()
2642  */
2643 static void
2644 sata_scsi_destroy_pkt(struct scsi_address *ap, struct scsi_pkt *pkt)
2645 {
2646 	sata_pkt_txlate_t *spx;
2647 
2648 	spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
2649 
2650 	sata_common_free_dma_rsrcs(spx);
2651 
2652 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
2653 	sata_pkt_free(spx);
2654 
2655 	scsi_hba_pkt_free(ap, pkt);
2656 }
2657 
2658 /*
2659  * Implementation of scsi tran_dmafree.
2660  * Free DMA resources allocated by sata_scsi_init_pkt()
2661  */
2662 
2663 static void
2664 sata_scsi_dmafree(struct scsi_address *ap, struct scsi_pkt *pkt)
2665 {
2666 #ifndef __lock_lint
2667 	_NOTE(ARGUNUSED(ap))
2668 #endif
2669 	sata_pkt_txlate_t *spx;
2670 
2671 	ASSERT(pkt != NULL);
2672 	spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
2673 
2674 	sata_common_free_dma_rsrcs(spx);
2675 }
2676 
2677 /*
2678  * Implementation of scsi tran_sync_pkt.
2679  *
2680  * The assumption below is that pkt is unique - there is no need to check ap
2681  *
2682  * Synchronize DMA buffer and, if the intermediate buffer is used, copy data
2683  * into/from the real buffer.
2684  */
2685 static void
2686 sata_scsi_sync_pkt(struct scsi_address *ap, struct scsi_pkt *pkt)
2687 {
2688 #ifndef __lock_lint
2689 	_NOTE(ARGUNUSED(ap))
2690 #endif
2691 	int rval;
2692 	sata_pkt_txlate_t *spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
2693 	struct buf *bp;
2694 	int direction;
2695 
2696 	ASSERT(spx != NULL);
2697 	if (spx->txlt_buf_dma_handle != NULL) {
2698 		direction = spx->txlt_sata_pkt->
2699 		    satapkt_cmd.satacmd_flags.sata_data_direction;
2700 		if (spx->txlt_sata_pkt != NULL &&
2701 		    direction != SATA_DIR_NODATA_XFER) {
2702 			if (spx->txlt_tmp_buf != NULL) {
2703 				/* Intermediate DMA buffer used */
2704 				bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
2705 
2706 				if (direction & SATA_DIR_WRITE) {
2707 					bcopy(bp->b_un.b_addr,
2708 					    spx->txlt_tmp_buf, bp->b_bcount);
2709 				}
2710 			}
2711 			/* Sync the buffer for device or for CPU */
2712 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle,   0, 0,
2713 			    (direction & SATA_DIR_WRITE) ?
2714 			    DDI_DMA_SYNC_FORDEV :  DDI_DMA_SYNC_FORCPU);
2715 			ASSERT(rval == DDI_SUCCESS);
2716 			if (spx->txlt_tmp_buf != NULL &&
2717 			    !(direction & SATA_DIR_WRITE)) {
2718 				/* Intermediate DMA buffer used for read */
2719 				bcopy(spx->txlt_tmp_buf,
2720 				    bp->b_un.b_addr, bp->b_bcount);
2721 			}
2722 
2723 		}
2724 	}
2725 }
2726 
2727 
2728 
2729 /* *******************  SATA - SCSI Translation functions **************** */
2730 /*
2731  * SCSI to SATA pkt and command translation and SATA to SCSI status/error
2732  * translation.
2733  */
2734 
2735 /*
2736  * Checks if a device exists and can be access and translates common
2737  * scsi_pkt data to sata_pkt data.
2738  *
2739  * Returns TRAN_ACCEPT and scsi pkt_reason CMD_CMPLT if device exists and
2740  * sata_pkt was set-up.
2741  * Returns TRAN_ACCEPT and scsi pkt_reason CMD_DEV_GONE if device does not
2742  * exist and pkt_comp callback was scheduled.
2743  * Returns other TRAN_XXXXX values when error occured and command should be
2744  * rejected with the returned TRAN_XXXXX value.
2745  *
2746  * This function should be called with port mutex held.
2747  */
2748 static int
2749 sata_txlt_generic_pkt_info(sata_pkt_txlate_t *spx, int *reason)
2750 {
2751 	sata_drive_info_t *sdinfo;
2752 	sata_device_t sata_device;
2753 	const struct sata_cmd_flags sata_initial_cmd_flags = {
2754 		SATA_DIR_NODATA_XFER,
2755 		/* all other values to 0/FALSE */
2756 	};
2757 	/*
2758 	 * Pkt_reason has to be set if the pkt_comp callback is invoked,
2759 	 * and that implies TRAN_ACCEPT return value. Any other returned value
2760 	 * indicates that the scsi packet was not accepted (the reason will not
2761 	 * be checked by the scsi target driver).
2762 	 * To make debugging easier, we set pkt_reason to know value here.
2763 	 * It may be changed later when different completion reason is
2764 	 * determined.
2765 	 */
2766 	spx->txlt_scsi_pkt->pkt_reason = CMD_TRAN_ERR;
2767 	*reason = CMD_TRAN_ERR;
2768 
2769 	/* Validate address */
2770 	switch (sata_validate_scsi_address(spx->txlt_sata_hba_inst,
2771 	    &spx->txlt_scsi_pkt->pkt_address, &sata_device)) {
2772 
2773 	case -1:
2774 		/* Invalid address or invalid device type */
2775 		return (TRAN_BADPKT);
2776 	case 1:
2777 		/* valid address but no device - it has disappeared ? */
2778 		spx->txlt_scsi_pkt->pkt_reason = CMD_DEV_GONE;
2779 		*reason = CMD_DEV_GONE;
2780 		/*
2781 		 * The sd target driver is checking CMD_DEV_GONE pkt_reason
2782 		 * only in callback function (for normal requests) and
2783 		 * in the dump code path.
2784 		 * So, if the callback is available, we need to do
2785 		 * the callback rather than returning TRAN_FATAL_ERROR here.
2786 		 */
2787 		if (spx->txlt_scsi_pkt->pkt_comp != NULL) {
2788 			/* scsi callback required */
2789 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
2790 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
2791 			    (void *)spx->txlt_scsi_pkt,
2792 			    TQ_SLEEP) == NULL)
2793 				/* Scheduling the callback failed */
2794 				return (TRAN_BUSY);
2795 
2796 			return (TRAN_ACCEPT);
2797 		}
2798 		return (TRAN_FATAL_ERROR);
2799 	default:
2800 		/* all OK; pkt reason will be overwritten later */
2801 		break;
2802 	}
2803 	/*
2804 	 * If in an interrupt context, reject packet if it is to be
2805 	 * executed in polling mode
2806 	 */
2807 	if (servicing_interrupt() &&
2808 	    (spx->txlt_scsi_pkt->pkt_flags & FLAG_NOINTR) != 0) {
2809 		SATADBG1(SATA_DBG_INTR_CTX, spx->txlt_sata_hba_inst,
2810 		    "sata_scsi_start: rejecting synchronous command because "
2811 		    "of interrupt context\n", NULL);
2812 		return (TRAN_BUSY);
2813 	}
2814 
2815 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
2816 	    &spx->txlt_sata_pkt->satapkt_device);
2817 
2818 	/*
2819 	 * If device is in reset condition, reject the packet with
2820 	 * TRAN_BUSY, unless:
2821 	 * 1. system is panicking (dumping)
2822 	 * In such case only one thread is running and there is no way to
2823 	 * process reset.
2824 	 * 2. cfgadm operation is is progress (internal APCTL lock is set)
2825 	 * Some cfgadm operations involve drive commands, so reset condition
2826 	 * needs to be ignored for IOCTL operations.
2827 	 */
2828 	if ((sdinfo->satadrv_event_flags &
2829 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) != 0) {
2830 
2831 		if (!ddi_in_panic() &&
2832 		    ((SATA_CPORT_EVENT_FLAGS(spx->txlt_sata_hba_inst,
2833 		    sata_device.satadev_addr.cport) &
2834 		    SATA_APCTL_LOCK_PORT_BUSY) == 0)) {
2835 			spx->txlt_scsi_pkt->pkt_reason = CMD_INCOMPLETE;
2836 			*reason = CMD_INCOMPLETE;
2837 			SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
2838 			    "sata_scsi_start: rejecting command because "
2839 			    "of device reset state\n", NULL);
2840 			return (TRAN_BUSY);
2841 		}
2842 	}
2843 
2844 	/*
2845 	 * Fix the dev_type in the sata_pkt->satapkt_device. It was not set by
2846 	 * sata_scsi_pkt_init() because pkt init had to work also with
2847 	 * non-existing devices.
2848 	 * Now we know that the packet was set-up for a real device, so its
2849 	 * type is known.
2850 	 */
2851 	spx->txlt_sata_pkt->satapkt_device.satadev_type = sdinfo->satadrv_type;
2852 
2853 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags = sata_initial_cmd_flags;
2854 	if ((SATA_CPORT_INFO(spx->txlt_sata_hba_inst,
2855 	    sata_device.satadev_addr.cport)->cport_event_flags &
2856 	    SATA_APCTL_LOCK_PORT_BUSY) != 0) {
2857 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.
2858 		    sata_ignore_dev_reset = B_TRUE;
2859 	}
2860 	/*
2861 	 * At this point the generic translation routine determined that the
2862 	 * scsi packet should be accepted. Packet completion reason may be
2863 	 * changed later when a different completion reason is determined.
2864 	 */
2865 	spx->txlt_scsi_pkt->pkt_reason = CMD_CMPLT;
2866 	*reason = CMD_CMPLT;
2867 
2868 	if ((spx->txlt_scsi_pkt->pkt_flags & FLAG_NOINTR) != 0) {
2869 		/* Synchronous execution */
2870 		spx->txlt_sata_pkt->satapkt_op_mode = SATA_OPMODE_SYNCH |
2871 		    SATA_OPMODE_POLLING;
2872 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.
2873 		    sata_ignore_dev_reset = ddi_in_panic();
2874 	} else {
2875 		/* Asynchronous execution */
2876 		spx->txlt_sata_pkt->satapkt_op_mode = SATA_OPMODE_ASYNCH |
2877 		    SATA_OPMODE_INTERRUPTS;
2878 	}
2879 	/* Convert queuing information */
2880 	if (spx->txlt_scsi_pkt->pkt_flags & FLAG_STAG)
2881 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.sata_queue_stag =
2882 		    B_TRUE;
2883 	else if (spx->txlt_scsi_pkt->pkt_flags &
2884 	    (FLAG_OTAG | FLAG_HTAG | FLAG_HEAD))
2885 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.sata_queue_otag =
2886 		    B_TRUE;
2887 
2888 	/* Always limit pkt time */
2889 	if (spx->txlt_scsi_pkt->pkt_time == 0)
2890 		spx->txlt_sata_pkt->satapkt_time = sata_default_pkt_time;
2891 	else
2892 		/* Pass on scsi_pkt time */
2893 		spx->txlt_sata_pkt->satapkt_time =
2894 		    spx->txlt_scsi_pkt->pkt_time;
2895 
2896 	return (TRAN_ACCEPT);
2897 }
2898 
2899 
2900 /*
2901  * Translate ATA Identify Device data to SCSI Inquiry data.
2902  * This function may be called only for ATA devices.
2903  * This function should not be called for ATAPI devices - they
2904  * respond directly to SCSI Inquiry command.
2905  *
2906  * SATA Identify Device data has to be valid in sata_drive_info.
2907  * Buffer has to accomodate the inquiry length (36 bytes).
2908  *
2909  * This function should be called with a port mutex held.
2910  */
2911 static	void
2912 sata_identdev_to_inquiry(sata_hba_inst_t *sata_hba_inst,
2913     sata_drive_info_t *sdinfo, uint8_t *buf)
2914 {
2915 
2916 	struct scsi_inquiry *inq = (struct scsi_inquiry *)buf;
2917 	struct sata_id *sid = &sdinfo->satadrv_id;
2918 
2919 	/* Start with a nice clean slate */
2920 	bzero((void *)inq, sizeof (struct scsi_inquiry));
2921 
2922 	/*
2923 	 * Rely on the dev_type for setting paripheral qualifier.
2924 	 * Assume that  DTYPE_RODIRECT applies to CD/DVD R/W devices.
2925 	 * It could be that DTYPE_OPTICAL could also qualify in the future.
2926 	 * ATAPI Inquiry may provide more data to the target driver.
2927 	 */
2928 	inq->inq_dtype = sdinfo->satadrv_type == SATA_DTYPE_ATADISK ?
2929 	    DTYPE_DIRECT : DTYPE_RODIRECT; /* DTYPE_UNKNOWN; */
2930 
2931 	/* CFA type device is not a removable media device */
2932 	inq->inq_rmb = ((sid->ai_config != SATA_CFA_TYPE) &&
2933 	    (sid->ai_config & SATA_REM_MEDIA)) ? 1 : 0;
2934 	inq->inq_qual = 0;	/* Device type qualifier (obsolete in SCSI3? */
2935 	inq->inq_iso = 0;	/* ISO version */
2936 	inq->inq_ecma = 0;	/* ECMA version */
2937 	inq->inq_ansi = 3;	/* ANSI version - SCSI 3 */
2938 	inq->inq_aenc = 0;	/* Async event notification cap. */
2939 	inq->inq_trmiop = 0;	/* Supports TERMINATE I/O PROC msg - NO */
2940 	inq->inq_normaca = 0;	/* setting NACA bit supported - NO */
2941 	inq->inq_rdf = RDF_SCSI2; /* Response data format- SPC-3 */
2942 	inq->inq_len = 31;	/* Additional length */
2943 	inq->inq_dualp = 0;	/* dual port device - NO */
2944 	inq->inq_reladdr = 0;	/* Supports relative addressing - NO */
2945 	inq->inq_sync = 0;	/* Supports synchronous data xfers - NO */
2946 	inq->inq_linked = 0;	/* Supports linked commands - NO */
2947 				/*
2948 				 * Queuing support - controller has to
2949 				 * support some sort of command queuing.
2950 				 */
2951 	if (SATA_QDEPTH(sata_hba_inst) > 1)
2952 		inq->inq_cmdque = 1; /* Supports command queueing - YES */
2953 	else
2954 		inq->inq_cmdque = 0; /* Supports command queueing - NO */
2955 	inq->inq_sftre = 0;	/* Supports Soft Reset option - NO ??? */
2956 	inq->inq_wbus32 = 0;	/* Supports 32 bit wide data xfers - NO */
2957 	inq->inq_wbus16 = 0;	/* Supports 16 bit wide data xfers - NO */
2958 
2959 #ifdef	_LITTLE_ENDIAN
2960 	/* Swap text fields to match SCSI format */
2961 	bcopy("ATA     ", inq->inq_vid, 8);		/* Vendor ID */
2962 	swab(sid->ai_model, inq->inq_pid, 16);		/* Product ID */
2963 	if (strncmp(&sid->ai_fw[4], "    ", 4) == 0)
2964 		swab(sid->ai_fw, inq->inq_revision, 4);	/* Revision level */
2965 	else
2966 		swab(&sid->ai_fw[4], inq->inq_revision, 4);	/* Rev. level */
2967 #else	/* _LITTLE_ENDIAN */
2968 	bcopy("ATA     ", inq->inq_vid, 8);		/* Vendor ID */
2969 	bcopy(sid->ai_model, inq->inq_pid, 16);		/* Product ID */
2970 	if (strncmp(&sid->ai_fw[4], "    ", 4) == 0)
2971 		bcopy(sid->ai_fw, inq->inq_revision, 4); /* Revision level */
2972 	else
2973 		bcopy(&sid->ai_fw[4], inq->inq_revision, 4); /* Rev. level */
2974 #endif	/* _LITTLE_ENDIAN */
2975 }
2976 
2977 
2978 /*
2979  * Scsi response set up for invalid command (command not supported)
2980  *
2981  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
2982  */
2983 static int
2984 sata_txlt_invalid_command(sata_pkt_txlate_t *spx)
2985 {
2986 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
2987 	struct scsi_extended_sense *sense;
2988 
2989 	scsipkt->pkt_reason = CMD_CMPLT;
2990 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
2991 	    STATE_SENT_CMD | STATE_GOT_STATUS;
2992 
2993 	*scsipkt->pkt_scbp = STATUS_CHECK;
2994 
2995 	sense = sata_arq_sense(spx);
2996 	sense->es_key = KEY_ILLEGAL_REQUEST;
2997 	sense->es_add_code = SD_SCSI_ASC_INVALID_COMMAND_CODE;
2998 
2999 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3000 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
3001 
3002 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3003 	    scsipkt->pkt_comp != NULL)
3004 		/* scsi callback required */
3005 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3006 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3007 		    (void *)spx->txlt_scsi_pkt,
3008 		    TQ_SLEEP) == NULL)
3009 			/* Scheduling the callback failed */
3010 			return (TRAN_BUSY);
3011 	return (TRAN_ACCEPT);
3012 }
3013 
3014 /*
3015  * Scsi response setup for
3016  * emulated non-data command that requires no action/return data
3017  *
3018  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3019  */
3020 static 	int
3021 sata_txlt_nodata_cmd_immediate(sata_pkt_txlate_t *spx)
3022 {
3023 	int rval;
3024 	int reason;
3025 
3026 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3027 
3028 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
3029 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3030 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3031 		return (rval);
3032 	}
3033 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3034 
3035 	spx->txlt_scsi_pkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3036 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3037 	spx->txlt_scsi_pkt->pkt_reason = CMD_CMPLT;
3038 	*(spx->txlt_scsi_pkt->pkt_scbp) = STATUS_GOOD;
3039 
3040 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3041 	    "Scsi_pkt completion reason %x\n",
3042 	    spx->txlt_scsi_pkt->pkt_reason);
3043 
3044 	if ((spx->txlt_scsi_pkt->pkt_flags & FLAG_NOINTR) == 0 &&
3045 	    spx->txlt_scsi_pkt->pkt_comp != NULL)
3046 		/* scsi callback required */
3047 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3048 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3049 		    (void *)spx->txlt_scsi_pkt,
3050 		    TQ_SLEEP) == NULL)
3051 			/* Scheduling the callback failed */
3052 			return (TRAN_BUSY);
3053 	return (TRAN_ACCEPT);
3054 }
3055 
3056 
3057 /*
3058  * SATA translate command: Inquiry / Identify Device
3059  * Use cached Identify Device data for now, rather than issuing actual
3060  * Device Identify cmd request. If device is detached and re-attached,
3061  * asynchromous event processing should fetch and refresh Identify Device
3062  * data.
3063  * Two VPD pages are supported now:
3064  * Vital Product Data page
3065  * Unit Serial Number page
3066  *
3067  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3068  */
3069 
3070 #define	EVPD			1	/* Extended Vital Product Data flag */
3071 #define	CMDDT			2	/* Command Support Data - Obsolete */
3072 #define	INQUIRY_SUP_VPD_PAGE	0	/* Supported VDP Pages Page COde */
3073 #define	INQUIRY_USN_PAGE	0x80	/* Unit Serial Number Page Code */
3074 #define	INQUIRY_DEV_IDENTIFICATION_PAGE 0x83 /* Not needed yet */
3075 
3076 static int
3077 sata_txlt_inquiry(sata_pkt_txlate_t *spx)
3078 {
3079 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3080 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
3081 	sata_drive_info_t *sdinfo;
3082 	struct scsi_extended_sense *sense;
3083 	int count;
3084 	uint8_t *p;
3085 	int i, j;
3086 	uint8_t page_buf[0xff]; /* Max length */
3087 	int rval, reason;
3088 
3089 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3090 
3091 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
3092 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3093 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3094 		return (rval);
3095 	}
3096 
3097 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3098 	    &spx->txlt_sata_pkt->satapkt_device);
3099 
3100 	ASSERT(sdinfo != NULL);
3101 
3102 	scsipkt->pkt_reason = CMD_CMPLT;
3103 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3104 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3105 
3106 	/* Reject not supported request */
3107 	if (scsipkt->pkt_cdbp[1] & CMDDT) { /* No support for this bit */
3108 		*scsipkt->pkt_scbp = STATUS_CHECK;
3109 		sense = sata_arq_sense(spx);
3110 		sense->es_key = KEY_ILLEGAL_REQUEST;
3111 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
3112 		goto done;
3113 	}
3114 
3115 	/* Valid Inquiry request */
3116 	*scsipkt->pkt_scbp = STATUS_GOOD;
3117 
3118 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
3119 
3120 		/*
3121 		 * Because it is fully emulated command storing data
3122 		 * programatically in the specified buffer, release
3123 		 * preallocated DMA resources before storing data in the buffer,
3124 		 * so no unwanted DMA sync would take place.
3125 		 */
3126 		sata_scsi_dmafree(NULL, scsipkt);
3127 
3128 		if (!(scsipkt->pkt_cdbp[1] & EVPD)) {
3129 			/* Standard Inquiry Data request */
3130 			struct scsi_inquiry inq;
3131 			unsigned int bufsize;
3132 
3133 			sata_identdev_to_inquiry(spx->txlt_sata_hba_inst,
3134 			    sdinfo, (uint8_t *)&inq);
3135 			/* Copy no more than requested */
3136 			count = MIN(bp->b_bcount,
3137 			    sizeof (struct scsi_inquiry));
3138 			bufsize = scsipkt->pkt_cdbp[4];
3139 			bufsize |= scsipkt->pkt_cdbp[3] << 8;
3140 			count = MIN(count, bufsize);
3141 			bcopy(&inq, bp->b_un.b_addr, count);
3142 
3143 			scsipkt->pkt_state |= STATE_XFERRED_DATA;
3144 			scsipkt->pkt_resid = scsipkt->pkt_cdbp[4] > count ?
3145 			    bufsize - count : 0;
3146 		} else {
3147 			/*
3148 			 * peripheral_qualifier = 0;
3149 			 *
3150 			 * We are dealing only with HD and will be
3151 			 * dealing with CD/DVD devices soon
3152 			 */
3153 			uint8_t peripheral_device_type =
3154 			    sdinfo->satadrv_type == SATA_DTYPE_ATADISK ?
3155 			    DTYPE_DIRECT : DTYPE_RODIRECT;
3156 
3157 			switch ((uint_t)scsipkt->pkt_cdbp[2]) {
3158 			case INQUIRY_SUP_VPD_PAGE:
3159 				/*
3160 				 * Request for suported Vital Product Data
3161 				 * pages - assuming only 2 page codes
3162 				 * supported.
3163 				 */
3164 				page_buf[0] = peripheral_device_type;
3165 				page_buf[1] = INQUIRY_SUP_VPD_PAGE;
3166 				page_buf[2] = 0;
3167 				page_buf[3] = 2; /* page length */
3168 				page_buf[4] = INQUIRY_SUP_VPD_PAGE;
3169 				page_buf[5] = INQUIRY_USN_PAGE;
3170 				/* Copy no more than requested */
3171 				count = MIN(bp->b_bcount, 6);
3172 				bcopy(page_buf, bp->b_un.b_addr, count);
3173 				break;
3174 
3175 			case INQUIRY_USN_PAGE:
3176 				/*
3177 				 * Request for Unit Serial Number page.
3178 				 * Set-up the page.
3179 				 */
3180 				page_buf[0] = peripheral_device_type;
3181 				page_buf[1] = INQUIRY_USN_PAGE;
3182 				page_buf[2] = 0;
3183 				/* remaining page length */
3184 				page_buf[3] = SATA_ID_SERIAL_LEN;
3185 
3186 				/*
3187 				 * Copy serial number from Identify Device data
3188 				 * words into the inquiry page and swap bytes
3189 				 * when necessary.
3190 				 */
3191 				p = (uint8_t *)(sdinfo->satadrv_id.ai_drvser);
3192 #ifdef	_LITTLE_ENDIAN
3193 				swab(p, &page_buf[4], SATA_ID_SERIAL_LEN);
3194 #else
3195 				bcopy(p, &page_buf[4], SATA_ID_SERIAL_LEN);
3196 #endif
3197 				/*
3198 				 * Least significant character of the serial
3199 				 * number shall appear as the last byte,
3200 				 * according to SBC-3 spec.
3201 				 * Count trailing spaces to determine the
3202 				 * necessary shift length.
3203 				 */
3204 				p = &page_buf[SATA_ID_SERIAL_LEN + 4 - 1];
3205 				for (j = 0; j < SATA_ID_SERIAL_LEN; j++) {
3206 					if (*(p - j) != '\0' &&
3207 					    *(p - j) != '\040')
3208 						break;
3209 				}
3210 
3211 				/*
3212 				 * Shift SN string right, so that the last
3213 				 * non-blank character would appear in last
3214 				 * byte of SN field in the page.
3215 				 * 'j' is the shift length.
3216 				 */
3217 				for (i = 0;
3218 				    i < (SATA_ID_SERIAL_LEN - j) && j != 0;
3219 				    i++, p--)
3220 					*p = *(p - j);
3221 
3222 				/*
3223 				 * Add leading spaces - same number as the
3224 				 * shift size
3225 				 */
3226 				for (; j > 0; j--)
3227 					page_buf[4 + j - 1] = '\040';
3228 
3229 				count = MIN(bp->b_bcount,
3230 				    SATA_ID_SERIAL_LEN + 4);
3231 				bcopy(page_buf, bp->b_un.b_addr, count);
3232 				break;
3233 
3234 			case INQUIRY_DEV_IDENTIFICATION_PAGE:
3235 				/*
3236 				 * We may want to implement this page, when
3237 				 * identifiers are common for SATA devices
3238 				 * But not now.
3239 				 */
3240 				/*FALLTHROUGH*/
3241 
3242 			default:
3243 				/* Request for unsupported VPD page */
3244 				*scsipkt->pkt_scbp = STATUS_CHECK;
3245 				sense = sata_arq_sense(spx);
3246 				sense->es_key = KEY_ILLEGAL_REQUEST;
3247 				sense->es_add_code =
3248 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
3249 				goto done;
3250 			}
3251 		}
3252 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
3253 		scsipkt->pkt_resid = scsipkt->pkt_cdbp[4] > count ?
3254 		    scsipkt->pkt_cdbp[4] - count : 0;
3255 	}
3256 done:
3257 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3258 
3259 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3260 	    "Scsi_pkt completion reason %x\n",
3261 	    scsipkt->pkt_reason);
3262 
3263 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3264 	    scsipkt->pkt_comp != NULL) {
3265 		/* scsi callback required */
3266 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3267 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
3268 		    TQ_SLEEP) == NULL)
3269 			/* Scheduling the callback failed */
3270 			return (TRAN_BUSY);
3271 	}
3272 	return (TRAN_ACCEPT);
3273 }
3274 
3275 /*
3276  * SATA translate command: Request Sense.
3277  * Emulated command (ATA version for SATA hard disks)
3278  * Always NO SENSE, because any sense data should be reported by ARQ sense.
3279  *
3280  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3281  *
3282  * Note: There is a mismatch between already implemented Informational
3283  * Exception Mode Select page 0x1C and this function.
3284  * When MRIE bit is set in page 0x1C, Request Sense is supposed to return
3285  * NO SENSE and set additional sense code to the exception code - this is not
3286  * implemented here.
3287  */
3288 static int
3289 sata_txlt_request_sense(sata_pkt_txlate_t *spx)
3290 {
3291 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3292 	struct scsi_extended_sense sense;
3293 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
3294 	int rval, reason;
3295 
3296 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3297 
3298 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
3299 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3300 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3301 		return (rval);
3302 	}
3303 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3304 
3305 
3306 	scsipkt->pkt_reason = CMD_CMPLT;
3307 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3308 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3309 	*scsipkt->pkt_scbp = STATUS_GOOD;
3310 
3311 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
3312 		/*
3313 		 * Because it is fully emulated command storing data
3314 		 * programatically in the specified buffer, release
3315 		 * preallocated DMA resources before storing data in the buffer,
3316 		 * so no unwanted DMA sync would take place.
3317 		 */
3318 		int count = MIN(bp->b_bcount,
3319 		    sizeof (struct scsi_extended_sense));
3320 		sata_scsi_dmafree(NULL, scsipkt);
3321 		bzero(&sense, sizeof (struct scsi_extended_sense));
3322 		sense.es_valid = 0;	/* Valid LBA */
3323 		sense.es_class = 7;	/* Response code 0x70 - current err */
3324 		sense.es_key = KEY_NO_SENSE;
3325 		sense.es_add_len = 6;	/* Additional length */
3326 		/* Copy no more than requested */
3327 		bcopy(&sense, bp->b_un.b_addr, count);
3328 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
3329 		scsipkt->pkt_resid = 0;
3330 	}
3331 
3332 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3333 	    "Scsi_pkt completion reason %x\n",
3334 	    scsipkt->pkt_reason);
3335 
3336 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3337 	    scsipkt->pkt_comp != NULL)
3338 		/* scsi callback required */
3339 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3340 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
3341 		    TQ_SLEEP) == NULL)
3342 			/* Scheduling the callback failed */
3343 			return (TRAN_BUSY);
3344 	return (TRAN_ACCEPT);
3345 }
3346 
3347 /*
3348  * SATA translate command: Test Unit Ready
3349  * At the moment this is an emulated command (ATA version for SATA hard disks).
3350  * May be translated into Check Power Mode command in the future
3351  *
3352  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3353  */
3354 static int
3355 sata_txlt_test_unit_ready(sata_pkt_txlate_t *spx)
3356 {
3357 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3358 	struct scsi_extended_sense *sense;
3359 	int power_state;
3360 	int rval, reason;
3361 
3362 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3363 
3364 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
3365 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3366 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3367 		return (rval);
3368 	}
3369 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3370 
3371 	/* At this moment, emulate it rather than execute anything */
3372 	power_state = SATA_PWRMODE_ACTIVE;
3373 
3374 	scsipkt->pkt_reason = CMD_CMPLT;
3375 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3376 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3377 
3378 	switch (power_state) {
3379 	case SATA_PWRMODE_ACTIVE:
3380 	case SATA_PWRMODE_IDLE:
3381 		*scsipkt->pkt_scbp = STATUS_GOOD;
3382 		break;
3383 	default:
3384 		/* PWR mode standby */
3385 		*scsipkt->pkt_scbp = STATUS_CHECK;
3386 		sense = sata_arq_sense(spx);
3387 		sense->es_key = KEY_NOT_READY;
3388 		sense->es_add_code = SD_SCSI_ASC_LU_NOT_READY;
3389 		break;
3390 	}
3391 
3392 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3393 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
3394 
3395 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3396 	    scsipkt->pkt_comp != NULL)
3397 		/* scsi callback required */
3398 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3399 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
3400 		    TQ_SLEEP) == NULL)
3401 			/* Scheduling the callback failed */
3402 			return (TRAN_BUSY);
3403 
3404 	return (TRAN_ACCEPT);
3405 }
3406 
3407 
3408 /*
3409  * SATA translate command: Start Stop Unit
3410  * Translation depends on a command:
3411  *	Start Unit translated into Idle Immediate
3412  *	Stop Unit translated into Standby Immediate
3413  *	Unload Media / NOT SUPPORTED YET
3414  *	Load Media / NOT SUPPROTED YET
3415  * Power condition bits are ignored, so is Immediate bit
3416  * Requesting synchronous execution.
3417  *
3418  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
3419  * appropriate values in scsi_pkt fields.
3420  */
3421 static int
3422 sata_txlt_start_stop_unit(sata_pkt_txlate_t *spx)
3423 {
3424 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3425 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
3426 	struct scsi_extended_sense *sense;
3427 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
3428 	int cport = SATA_TXLT_CPORT(spx);
3429 	int rval, reason;
3430 	int synch;
3431 
3432 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3433 	    "sata_txlt_start_stop_unit: %d\n", scsipkt->pkt_scbp[4] & 1);
3434 
3435 	mutex_enter(&SATA_CPORT_MUTEX(shi, cport));
3436 
3437 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
3438 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3439 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3440 		return (rval);
3441 	}
3442 
3443 	if (scsipkt->pkt_cdbp[4] & 2) {
3444 		/* Load/Unload Media - invalid request */
3445 		*scsipkt->pkt_scbp = STATUS_CHECK;
3446 		sense = sata_arq_sense(spx);
3447 		sense->es_key = KEY_ILLEGAL_REQUEST;
3448 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
3449 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3450 
3451 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3452 		    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
3453 
3454 		if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3455 		    scsipkt->pkt_comp != NULL)
3456 			/* scsi callback required */
3457 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3458 			    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
3459 			    TQ_SLEEP) == NULL)
3460 				/* Scheduling the callback failed */
3461 				return (TRAN_BUSY);
3462 
3463 		return (TRAN_ACCEPT);
3464 	}
3465 	scmd->satacmd_addr_type = 0;
3466 	scmd->satacmd_sec_count_lsb = 0;
3467 	scmd->satacmd_lba_low_lsb = 0;
3468 	scmd->satacmd_lba_mid_lsb = 0;
3469 	scmd->satacmd_lba_high_lsb = 0;
3470 	scmd->satacmd_features_reg = 0;
3471 	scmd->satacmd_device_reg = 0;
3472 	scmd->satacmd_status_reg = 0;
3473 	if (scsipkt->pkt_cdbp[4] & 1) {
3474 		/* Start Unit */
3475 		scmd->satacmd_cmd_reg = SATAC_IDLE_IM;
3476 	} else {
3477 		/* Stop Unit */
3478 		scmd->satacmd_cmd_reg = SATAC_STANDBY_IM;
3479 	}
3480 
3481 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
3482 		/* Need to set-up a callback function */
3483 		spx->txlt_sata_pkt->satapkt_comp =
3484 		    sata_txlt_nodata_cmd_completion;
3485 		synch = FALSE;
3486 	} else {
3487 		spx->txlt_sata_pkt->satapkt_op_mode = SATA_OPMODE_SYNCH;
3488 		synch = TRUE;
3489 	}
3490 
3491 	/* Transfer command to HBA */
3492 	if (sata_hba_start(spx, &rval) != 0) {
3493 		/* Pkt not accepted for execution */
3494 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
3495 		return (rval);
3496 	}
3497 
3498 	/*
3499 	 * If execution is non-synchronous,
3500 	 * a callback function will handle potential errors, translate
3501 	 * the response and will do a callback to a target driver.
3502 	 * If it was synchronous, check execution status using the same
3503 	 * framework callback.
3504 	 */
3505 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
3506 	if (synch) {
3507 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3508 		    "synchronous execution status %x\n",
3509 		    spx->txlt_sata_pkt->satapkt_reason);
3510 
3511 		sata_txlt_nodata_cmd_completion(spx->txlt_sata_pkt);
3512 	}
3513 	return (TRAN_ACCEPT);
3514 
3515 }
3516 
3517 
3518 /*
3519  * SATA translate command:  Read Capacity.
3520  * Emulated command for SATA disks.
3521  * Capacity is retrieved from cached Idenifty Device data.
3522  * Identify Device data shows effective disk capacity, not the native
3523  * capacity, which may be limitted by Set Max Address command.
3524  * This is ATA version for SATA hard disks.
3525  *
3526  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3527  */
3528 static int
3529 sata_txlt_read_capacity(sata_pkt_txlate_t *spx)
3530 {
3531 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3532 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
3533 	sata_drive_info_t *sdinfo;
3534 	uint64_t val;
3535 	uchar_t *rbuf;
3536 	int rval, reason;
3537 
3538 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3539 	    "sata_txlt_read_capacity: ", NULL);
3540 
3541 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3542 
3543 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
3544 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3545 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3546 		return (rval);
3547 	}
3548 
3549 	scsipkt->pkt_reason = CMD_CMPLT;
3550 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3551 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3552 	*scsipkt->pkt_scbp = STATUS_GOOD;
3553 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
3554 		/*
3555 		 * Because it is fully emulated command storing data
3556 		 * programatically in the specified buffer, release
3557 		 * preallocated DMA resources before storing data in the buffer,
3558 		 * so no unwanted DMA sync would take place.
3559 		 */
3560 		sata_scsi_dmafree(NULL, scsipkt);
3561 
3562 		sdinfo = sata_get_device_info(
3563 		    spx->txlt_sata_hba_inst,
3564 		    &spx->txlt_sata_pkt->satapkt_device);
3565 		/* Last logical block address */
3566 		val = sdinfo->satadrv_capacity - 1;
3567 		rbuf = (uchar_t *)bp->b_un.b_addr;
3568 		/* Need to swap endians to match scsi format */
3569 		rbuf[0] = (val >> 24) & 0xff;
3570 		rbuf[1] = (val >> 16) & 0xff;
3571 		rbuf[2] = (val >> 8) & 0xff;
3572 		rbuf[3] = val & 0xff;
3573 		/* block size - always 512 bytes, for now */
3574 		rbuf[4] = 0;
3575 		rbuf[5] = 0;
3576 		rbuf[6] = 0x02;
3577 		rbuf[7] = 0;
3578 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
3579 		scsipkt->pkt_resid = 0;
3580 
3581 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst, "%d\n",
3582 		    sdinfo->satadrv_capacity -1);
3583 	}
3584 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3585 	/*
3586 	 * If a callback was requested, do it now.
3587 	 */
3588 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3589 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
3590 
3591 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3592 	    scsipkt->pkt_comp != NULL)
3593 		/* scsi callback required */
3594 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3595 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
3596 		    TQ_SLEEP) == NULL)
3597 			/* Scheduling the callback failed */
3598 			return (TRAN_BUSY);
3599 
3600 	return (TRAN_ACCEPT);
3601 }
3602 
3603 /*
3604  * SATA translate command: Mode Sense.
3605  * Translated into appropriate SATA command or emulated.
3606  * Saved Values Page Control (03) are not supported.
3607  *
3608  * NOTE: only caching mode sense page is currently implemented.
3609  *
3610  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3611  */
3612 
3613 static int
3614 sata_txlt_mode_sense(sata_pkt_txlate_t *spx)
3615 {
3616 	struct scsi_pkt	*scsipkt = spx->txlt_scsi_pkt;
3617 	struct buf	*bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
3618 	sata_drive_info_t *sdinfo;
3619 	sata_id_t *sata_id;
3620 	struct scsi_extended_sense *sense;
3621 	int 		len, bdlen, count, alc_len;
3622 	int		pc;	/* Page Control code */
3623 	uint8_t		*buf;	/* mode sense buffer */
3624 	int		rval, reason;
3625 
3626 	SATADBG2(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3627 	    "sata_txlt_mode_sense, pc %x page code 0x%02x\n",
3628 	    spx->txlt_scsi_pkt->pkt_cdbp[2] >> 6,
3629 	    spx->txlt_scsi_pkt->pkt_cdbp[2] & 0x3f);
3630 
3631 	buf = kmem_zalloc(1024, KM_SLEEP);
3632 
3633 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3634 
3635 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
3636 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3637 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3638 		kmem_free(buf, 1024);
3639 		return (rval);
3640 	}
3641 
3642 	scsipkt->pkt_reason = CMD_CMPLT;
3643 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3644 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3645 
3646 	pc = scsipkt->pkt_cdbp[2] >> 6;
3647 
3648 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
3649 		/*
3650 		 * Because it is fully emulated command storing data
3651 		 * programatically in the specified buffer, release
3652 		 * preallocated DMA resources before storing data in the buffer,
3653 		 * so no unwanted DMA sync would take place.
3654 		 */
3655 		sata_scsi_dmafree(NULL, scsipkt);
3656 
3657 		len = 0;
3658 		bdlen = 0;
3659 		if (!(scsipkt->pkt_cdbp[1] & 8)) {
3660 			if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SENSE_G1 &&
3661 			    (scsipkt->pkt_cdbp[0] & 0x10))
3662 				bdlen = 16;
3663 			else
3664 				bdlen = 8;
3665 		}
3666 		/* Build mode parameter header */
3667 		if (spx->txlt_scsi_pkt->pkt_cdbp[0] == SCMD_MODE_SENSE) {
3668 			/* 4-byte mode parameter header */
3669 			buf[len++] = 0;   	/* mode data length */
3670 			buf[len++] = 0;		/* medium type */
3671 			buf[len++] = 0;		/* dev-specific param */
3672 			buf[len++] = bdlen;	/* Block Descriptor length */
3673 		} else {
3674 			/* 8-byte mode parameter header */
3675 			buf[len++] = 0;		/* mode data length */
3676 			buf[len++] = 0;
3677 			buf[len++] = 0;		/* medium type */
3678 			buf[len++] = 0;		/* dev-specific param */
3679 			if (bdlen == 16)
3680 				buf[len++] = 1;	/* long lba descriptor */
3681 			else
3682 				buf[len++] = 0;
3683 			buf[len++] = 0;
3684 			buf[len++] = 0;		/* Block Descriptor length */
3685 			buf[len++] = bdlen;
3686 		}
3687 
3688 		sdinfo = sata_get_device_info(
3689 		    spx->txlt_sata_hba_inst,
3690 		    &spx->txlt_sata_pkt->satapkt_device);
3691 
3692 		/* Build block descriptor only if not disabled (DBD) */
3693 		if ((scsipkt->pkt_cdbp[1] & 0x08) == 0) {
3694 			/* Block descriptor - direct-access device format */
3695 			if (bdlen == 8) {
3696 				/* build regular block descriptor */
3697 				buf[len++] =
3698 				    (sdinfo->satadrv_capacity >> 24) & 0xff;
3699 				buf[len++] =
3700 				    (sdinfo->satadrv_capacity >> 16) & 0xff;
3701 				buf[len++] =
3702 				    (sdinfo->satadrv_capacity >> 8) & 0xff;
3703 				buf[len++] = sdinfo->satadrv_capacity & 0xff;
3704 				buf[len++] = 0; /* density code */
3705 				buf[len++] = 0;
3706 				if (sdinfo->satadrv_type ==
3707 				    SATA_DTYPE_ATADISK)
3708 					buf[len++] = 2;
3709 				else
3710 					/* ATAPI */
3711 					buf[len++] = 8;
3712 				buf[len++] = 0;
3713 			} else if (bdlen == 16) {
3714 				/* Long LBA Accepted */
3715 				/* build long lba block descriptor */
3716 #ifndef __lock_lint
3717 				buf[len++] =
3718 				    (sdinfo->satadrv_capacity >> 56) & 0xff;
3719 				buf[len++] =
3720 				    (sdinfo->satadrv_capacity >> 48) & 0xff;
3721 				buf[len++] =
3722 				    (sdinfo->satadrv_capacity >> 40) & 0xff;
3723 				buf[len++] =
3724 				    (sdinfo->satadrv_capacity >> 32) & 0xff;
3725 #endif
3726 				buf[len++] =
3727 				    (sdinfo->satadrv_capacity >> 24) & 0xff;
3728 				buf[len++] =
3729 				    (sdinfo->satadrv_capacity >> 16) & 0xff;
3730 				buf[len++] =
3731 				    (sdinfo->satadrv_capacity >> 8) & 0xff;
3732 				buf[len++] = sdinfo->satadrv_capacity & 0xff;
3733 				buf[len++] = 0;
3734 				buf[len++] = 0; /* density code */
3735 				buf[len++] = 0;
3736 				buf[len++] = 0;
3737 				if (sdinfo->satadrv_type ==
3738 				    SATA_DTYPE_ATADISK)
3739 					buf[len++] = 2;
3740 				else
3741 					/* ATAPI */
3742 					buf[len++] = 8;
3743 				buf[len++] = 0;
3744 			}
3745 		}
3746 
3747 		sata_id = &sdinfo->satadrv_id;
3748 
3749 		/*
3750 		 * Add requested pages.
3751 		 * Page 3 and 4 are obsolete and we are not supporting them.
3752 		 * We deal now with:
3753 		 * caching (read/write cache control).
3754 		 * We should eventually deal with following mode pages:
3755 		 * error recovery  (0x01),
3756 		 * power condition (0x1a),
3757 		 * exception control page (enables SMART) (0x1c),
3758 		 * enclosure management (ses),
3759 		 * protocol-specific port mode (port control).
3760 		 */
3761 		switch (scsipkt->pkt_cdbp[2] & 0x3f) {
3762 		case MODEPAGE_RW_ERRRECOV:
3763 			/* DAD_MODE_ERR_RECOV */
3764 			/* R/W recovery */
3765 			len += sata_build_msense_page_1(sdinfo, pc, buf+len);
3766 			break;
3767 		case MODEPAGE_CACHING:
3768 			/* DAD_MODE_CACHE */
3769 			/* Reject not supported request for saved parameters */
3770 			if (pc == 3) {
3771 				*scsipkt->pkt_scbp = STATUS_CHECK;
3772 				sense = sata_arq_sense(spx);
3773 				sense->es_key = KEY_ILLEGAL_REQUEST;
3774 				sense->es_add_code =
3775 				    SD_SCSI_ASC_SAVING_PARAMS_NOT_SUPPORTED;
3776 				goto done;
3777 			}
3778 
3779 			/* caching */
3780 			len += sata_build_msense_page_8(sdinfo, pc, buf+len);
3781 			break;
3782 		case MODEPAGE_INFO_EXCPT:
3783 			/* exception cntrl */
3784 			if (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED) {
3785 				len += sata_build_msense_page_1c(sdinfo, pc,
3786 				    buf+len);
3787 			}
3788 			else
3789 				goto err;
3790 			break;
3791 		case MODEPAGE_POWER_COND:
3792 			/* DAD_MODE_POWER_COND */
3793 			/* power condition */
3794 			len += sata_build_msense_page_1a(sdinfo, pc, buf+len);
3795 			break;
3796 
3797 		case MODEPAGE_ACOUSTIC_MANAG:
3798 			/* acoustic management */
3799 			len += sata_build_msense_page_30(sdinfo, pc, buf+len);
3800 			break;
3801 		case MODEPAGE_ALLPAGES:
3802 			/* all pages */
3803 			len += sata_build_msense_page_1(sdinfo, pc, buf+len);
3804 			len += sata_build_msense_page_8(sdinfo, pc, buf+len);
3805 			len += sata_build_msense_page_1a(sdinfo, pc, buf+len);
3806 			if (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED) {
3807 				len += sata_build_msense_page_1c(sdinfo, pc,
3808 				    buf+len);
3809 			}
3810 			len += sata_build_msense_page_30(sdinfo, pc, buf+len);
3811 			break;
3812 		default:
3813 		err:
3814 			/* Invalid request */
3815 			*scsipkt->pkt_scbp = STATUS_CHECK;
3816 			sense = sata_arq_sense(spx);
3817 			sense->es_key = KEY_ILLEGAL_REQUEST;
3818 			sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
3819 			goto done;
3820 		}
3821 
3822 		/* fix total mode data length */
3823 		if (spx->txlt_scsi_pkt->pkt_cdbp[0] == SCMD_MODE_SENSE) {
3824 			/* 4-byte mode parameter header */
3825 			buf[0] = len - 1;   	/* mode data length */
3826 		} else {
3827 			buf[0] = (len -2) >> 8;
3828 			buf[1] = (len -2) & 0xff;
3829 		}
3830 
3831 
3832 		/* Check allocation length */
3833 		if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SENSE) {
3834 			alc_len = scsipkt->pkt_cdbp[4];
3835 		} else {
3836 			alc_len = scsipkt->pkt_cdbp[7];
3837 			alc_len = (len << 8) | scsipkt->pkt_cdbp[8];
3838 		}
3839 		/*
3840 		 * We do not check for possible parameters truncation
3841 		 * (alc_len < len) assuming that the target driver works
3842 		 * correctly. Just avoiding overrun.
3843 		 * Copy no more than requested and possible, buffer-wise.
3844 		 */
3845 		count = MIN(alc_len, len);
3846 		count = MIN(bp->b_bcount, count);
3847 		bcopy(buf, bp->b_un.b_addr, count);
3848 
3849 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
3850 		scsipkt->pkt_resid = alc_len > count ? alc_len - count : 0;
3851 	}
3852 	*scsipkt->pkt_scbp = STATUS_GOOD;
3853 done:
3854 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3855 	(void) kmem_free(buf, 1024);
3856 
3857 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3858 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
3859 
3860 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3861 	    scsipkt->pkt_comp != NULL)
3862 		/* scsi callback required */
3863 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3864 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
3865 		    TQ_SLEEP) == NULL)
3866 			/* Scheduling the callback failed */
3867 			return (TRAN_BUSY);
3868 
3869 	return (TRAN_ACCEPT);
3870 }
3871 
3872 
3873 /*
3874  * SATA translate command: Mode Select.
3875  * Translated into appropriate SATA command or emulated.
3876  * Saving parameters is not supported.
3877  * Changing device capacity is not supported (although theoretically
3878  * possible by executing SET FEATURES/SET MAX ADDRESS)
3879  *
3880  * Assumption is that the target driver is working correctly.
3881  *
3882  * More than one SATA command may be executed to perform operations specified
3883  * by mode select pages. The first error terminates further execution.
3884  * Operations performed successully are not backed-up in such case.
3885  *
3886  * NOTE: Implemented pages:
3887  * - caching page
3888  * - informational exception page
3889  * - acoustic management page
3890  * Caching setup is remembered so it could be re-stored in case of
3891  * an unexpected device reset.
3892  *
3893  * Returns TRAN_XXXX.
3894  * If TRAN_ACCEPT is returned, appropriate values are set in scsi_pkt fields.
3895  */
3896 
3897 static int
3898 sata_txlt_mode_select(sata_pkt_txlate_t *spx)
3899 {
3900 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3901 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
3902 	struct scsi_extended_sense *sense;
3903 	int len, pagelen, count, pllen;
3904 	uint8_t *buf;	/* mode select buffer */
3905 	int rval, stat, reason;
3906 	uint_t nointr_flag;
3907 	int dmod = 0;
3908 
3909 	SATADBG2(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3910 	    "sata_txlt_mode_select, pc %x page code 0x%02x\n",
3911 	    spx->txlt_scsi_pkt->pkt_cdbp[2] >> 6,
3912 	    spx->txlt_scsi_pkt->pkt_cdbp[2] & 0x3f);
3913 
3914 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3915 
3916 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
3917 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3918 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3919 		return (rval);
3920 	}
3921 	/*
3922 	 * If in interrupt context, reject this packet because it may result
3923 	 * in issuing a synchronous command to HBA.
3924 	 */
3925 	if (servicing_interrupt()) {
3926 		SATADBG1(SATA_DBG_INTR_CTX, spx->txlt_sata_hba_inst,
3927 		    "sata_txlt_mode_select: rejecting command because "
3928 		    "of interrupt context\n", NULL);
3929 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3930 		return (TRAN_BUSY);
3931 	}
3932 
3933 	rval = TRAN_ACCEPT;
3934 
3935 	scsipkt->pkt_reason = CMD_CMPLT;
3936 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3937 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3938 	nointr_flag = scsipkt->pkt_flags & FLAG_NOINTR;
3939 
3940 	/* Reject not supported request */
3941 	if (! (scsipkt->pkt_cdbp[1] & 0x10)) { /* No support for PF bit = 0 */
3942 		*scsipkt->pkt_scbp = STATUS_CHECK;
3943 		sense = sata_arq_sense(spx);
3944 		sense->es_key = KEY_ILLEGAL_REQUEST;
3945 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
3946 		goto done;
3947 	}
3948 
3949 	if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SELECT) {
3950 		pllen = scsipkt->pkt_cdbp[4];
3951 	} else {
3952 		pllen = scsipkt->pkt_cdbp[7];
3953 		pllen = (pllen << 8) | scsipkt->pkt_cdbp[7];
3954 	}
3955 
3956 	*scsipkt->pkt_scbp = STATUS_GOOD;	/* Presumed outcome */
3957 
3958 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount && pllen != 0) {
3959 		buf = (uint8_t *)bp->b_un.b_addr;
3960 		count = MIN(bp->b_bcount, pllen);
3961 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
3962 		scsipkt->pkt_resid = 0;
3963 		pllen = count;
3964 
3965 		/*
3966 		 * Check the header to skip the block descriptor(s) - we
3967 		 * do not support setting device capacity.
3968 		 * Existing macros do not recognize long LBA dscriptor,
3969 		 * hence manual calculation.
3970 		 */
3971 		if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SELECT) {
3972 			/* 6-bytes CMD, 4 bytes header */
3973 			if (count <= 4)
3974 				goto done;		/* header only */
3975 			len = buf[3] + 4;
3976 		} else {
3977 			/* 10-bytes CMD, 8 bytes header */
3978 			if (count <= 8)
3979 				goto done;		/* header only */
3980 			len = buf[6];
3981 			len = (len << 8) + buf[7] + 8;
3982 		}
3983 		if (len >= count)
3984 			goto done;	/* header + descriptor(s) only */
3985 
3986 		pllen -= len;		/* remaining data length */
3987 
3988 		/*
3989 		 * We may be executing SATA command and want to execute it
3990 		 * in SYNCH mode, regardless of scsi_pkt setting.
3991 		 * Save scsi_pkt setting and indicate SYNCH mode
3992 		 */
3993 		if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3994 		    scsipkt->pkt_comp != NULL) {
3995 			scsipkt->pkt_flags |= FLAG_NOINTR;
3996 		}
3997 		spx->txlt_sata_pkt->satapkt_op_mode = SATA_OPMODE_SYNCH;
3998 
3999 		/*
4000 		 * len is now the offset to a first mode select page
4001 		 * Process all pages
4002 		 */
4003 		while (pllen > 0) {
4004 			switch ((int)buf[len]) {
4005 			case MODEPAGE_CACHING:
4006 				/* No support for SP (saving) */
4007 				if (scsipkt->pkt_cdbp[1] & 0x01) {
4008 					*scsipkt->pkt_scbp = STATUS_CHECK;
4009 					sense = sata_arq_sense(spx);
4010 					sense->es_key = KEY_ILLEGAL_REQUEST;
4011 					sense->es_add_code =
4012 					    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
4013 					goto done;
4014 				}
4015 				stat = sata_mode_select_page_8(spx,
4016 				    (struct mode_cache_scsi3 *)&buf[len],
4017 				    pllen, &pagelen, &rval, &dmod);
4018 				/*
4019 				 * The pagelen value indicates the number of
4020 				 * parameter bytes already processed.
4021 				 * The rval is the return value from
4022 				 * sata_tran_start().
4023 				 * The stat indicates the overall status of
4024 				 * the operation(s).
4025 				 */
4026 				if (stat != SATA_SUCCESS)
4027 					/*
4028 					 * Page processing did not succeed -
4029 					 * all error info is already set-up,
4030 					 * just return
4031 					 */
4032 					pllen = 0; /* this breaks the loop */
4033 				else {
4034 					len += pagelen;
4035 					pllen -= pagelen;
4036 				}
4037 				break;
4038 
4039 			case MODEPAGE_INFO_EXCPT:
4040 				stat = sata_mode_select_page_1c(spx,
4041 				    (struct mode_info_excpt_page *)&buf[len],
4042 				    pllen, &pagelen, &rval, &dmod);
4043 				/*
4044 				 * The pagelen value indicates the number of
4045 				 * parameter bytes already processed.
4046 				 * The rval is the return value from
4047 				 * sata_tran_start().
4048 				 * The stat indicates the overall status of
4049 				 * the operation(s).
4050 				 */
4051 				if (stat != SATA_SUCCESS)
4052 					/*
4053 					 * Page processing did not succeed -
4054 					 * all error info is already set-up,
4055 					 * just return
4056 					 */
4057 					pllen = 0; /* this breaks the loop */
4058 				else {
4059 					len += pagelen;
4060 					pllen -= pagelen;
4061 				}
4062 				break;
4063 
4064 			case MODEPAGE_ACOUSTIC_MANAG:
4065 				stat = sata_mode_select_page_30(spx,
4066 				    (struct mode_acoustic_management *)
4067 				    &buf[len], pllen, &pagelen, &rval, &dmod);
4068 				/*
4069 				 * The pagelen value indicates the number of
4070 				 * parameter bytes already processed.
4071 				 * The rval is the return value from
4072 				 * sata_tran_start().
4073 				 * The stat indicates the overall status of
4074 				 * the operation(s).
4075 				 */
4076 				if (stat != SATA_SUCCESS)
4077 					/*
4078 					 * Page processing did not succeed -
4079 					 * all error info is already set-up,
4080 					 * just return
4081 					 */
4082 					pllen = 0; /* this breaks the loop */
4083 				else {
4084 					len += pagelen;
4085 					pllen -= pagelen;
4086 				}
4087 
4088 				break;
4089 			default:
4090 				*scsipkt->pkt_scbp = STATUS_CHECK;
4091 				sense = sata_arq_sense(spx);
4092 				sense->es_key = KEY_ILLEGAL_REQUEST;
4093 				sense->es_add_code =
4094 				    SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
4095 				goto done;
4096 			}
4097 		}
4098 	}
4099 done:
4100 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4101 	/*
4102 	 * If device parameters were modified, fetch and store the new
4103 	 * Identify Device data. Since port mutex could have been released
4104 	 * for accessing HBA driver, we need to re-check device existence.
4105 	 */
4106 	if (dmod != 0) {
4107 		sata_drive_info_t new_sdinfo, *sdinfo;
4108 		int rv = 0;
4109 
4110 		/*
4111 		 * Following statement has to be changed if this function is
4112 		 * used for devices other than SATA hard disks.
4113 		 */
4114 		new_sdinfo.satadrv_type = SATA_DTYPE_ATADISK;
4115 
4116 		new_sdinfo.satadrv_addr =
4117 		    spx->txlt_sata_pkt->satapkt_device.satadev_addr;
4118 		rv = sata_fetch_device_identify_data(spx->txlt_sata_hba_inst,
4119 		    &new_sdinfo);
4120 
4121 		mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4122 		/*
4123 		 * Since port mutex could have been released when
4124 		 * accessing HBA driver, we need to re-check that the
4125 		 * framework still holds the device info structure.
4126 		 */
4127 		sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
4128 		    &spx->txlt_sata_pkt->satapkt_device);
4129 		if (sdinfo != NULL) {
4130 			/*
4131 			 * Device still has info structure in the
4132 			 * sata framework. Copy newly fetched info
4133 			 */
4134 			if (rv == 0) {
4135 				sdinfo->satadrv_id = new_sdinfo.satadrv_id;
4136 				sata_save_drive_settings(sdinfo);
4137 			} else {
4138 				/*
4139 				 * Could not fetch new data - invalidate
4140 				 * sata_drive_info. That makes device
4141 				 * unusable.
4142 				 */
4143 				sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
4144 				sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
4145 			}
4146 		}
4147 		if (rv != 0 || sdinfo == NULL) {
4148 			/*
4149 			 * This changes the overall mode select completion
4150 			 * reason to a failed one !!!!!
4151 			 */
4152 			*scsipkt->pkt_scbp = STATUS_CHECK;
4153 			sense = sata_arq_sense(spx);
4154 			scsipkt->pkt_reason = CMD_INCOMPLETE;
4155 			rval = TRAN_ACCEPT;
4156 		}
4157 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4158 	}
4159 	/* Restore the scsi pkt flags */
4160 	scsipkt->pkt_flags &= ~FLAG_NOINTR;
4161 	scsipkt->pkt_flags |= nointr_flag;
4162 
4163 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4164 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
4165 
4166 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4167 	    scsipkt->pkt_comp != NULL)
4168 		/* scsi callback required */
4169 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4170 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
4171 		    TQ_SLEEP) == NULL)
4172 			/* Scheduling the callback failed */
4173 			return (TRAN_BUSY);
4174 
4175 	return (rval);
4176 }
4177 
4178 
4179 
4180 /*
4181  * Translate command: Log Sense
4182  */
4183 static 	int
4184 sata_txlt_log_sense(sata_pkt_txlate_t *spx)
4185 {
4186 	struct scsi_pkt	*scsipkt = spx->txlt_scsi_pkt;
4187 	struct buf	*bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
4188 	sata_drive_info_t *sdinfo;
4189 	struct scsi_extended_sense *sense;
4190 	int 		len, count, alc_len;
4191 	int		pc;	/* Page Control code */
4192 	int		page_code;	/* Page code */
4193 	uint8_t		*buf;	/* log sense buffer */
4194 	int		rval, reason;
4195 #define	MAX_LOG_SENSE_PAGE_SIZE	512
4196 
4197 	SATADBG2(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4198 	    "sata_txlt_log_sense, pc 0x%x, page code 0x%x\n",
4199 	    spx->txlt_scsi_pkt->pkt_cdbp[2] >> 6,
4200 	    spx->txlt_scsi_pkt->pkt_cdbp[2] & 0x3f);
4201 
4202 	buf = kmem_zalloc(MAX_LOG_SENSE_PAGE_SIZE, KM_SLEEP);
4203 
4204 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4205 
4206 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
4207 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
4208 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4209 		kmem_free(buf, MAX_LOG_SENSE_PAGE_SIZE);
4210 		return (rval);
4211 	}
4212 	/*
4213 	 * If in interrupt context, reject this packet because it may result
4214 	 * in issuing a synchronous command to HBA.
4215 	 */
4216 	if (servicing_interrupt()) {
4217 		SATADBG1(SATA_DBG_INTR_CTX, spx->txlt_sata_hba_inst,
4218 		    "sata_log_sense: rejecting command because "
4219 		    "of interrupt context\n", NULL);
4220 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4221 		kmem_free(buf, MAX_LOG_SENSE_PAGE_SIZE);
4222 		return (TRAN_BUSY);
4223 	}
4224 
4225 	scsipkt->pkt_reason = CMD_CMPLT;
4226 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
4227 	    STATE_SENT_CMD | STATE_GOT_STATUS;
4228 
4229 	pc = scsipkt->pkt_cdbp[2] >> 6;
4230 	page_code = scsipkt->pkt_cdbp[2] & 0x3f;
4231 
4232 	/* Reject not supported request for all but cumulative values */
4233 	switch (pc) {
4234 	case PC_CUMULATIVE_VALUES:
4235 		break;
4236 	default:
4237 		*scsipkt->pkt_scbp = STATUS_CHECK;
4238 		sense = sata_arq_sense(spx);
4239 		sense->es_key = KEY_ILLEGAL_REQUEST;
4240 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
4241 		goto done;
4242 	}
4243 
4244 	switch (page_code) {
4245 	case PAGE_CODE_GET_SUPPORTED_LOG_PAGES:
4246 	case PAGE_CODE_SELF_TEST_RESULTS:
4247 	case PAGE_CODE_INFORMATION_EXCEPTIONS:
4248 	case PAGE_CODE_SMART_READ_DATA:
4249 		break;
4250 	default:
4251 		*scsipkt->pkt_scbp = STATUS_CHECK;
4252 		sense = sata_arq_sense(spx);
4253 		sense->es_key = KEY_ILLEGAL_REQUEST;
4254 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
4255 		goto done;
4256 	}
4257 
4258 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
4259 		/*
4260 		 * Because log sense uses local buffers for data retrieval from
4261 		 * the devices and sets the data programatically in the
4262 		 * original specified buffer, release preallocated DMA
4263 		 * resources before storing data in the original buffer,
4264 		 * so no unwanted DMA sync would take place.
4265 		 */
4266 		sata_id_t *sata_id;
4267 
4268 		sata_scsi_dmafree(NULL, scsipkt);
4269 
4270 		len = 0;
4271 
4272 		/* Build log parameter header */
4273 		buf[len++] = page_code;	/* page code as in the CDB */
4274 		buf[len++] = 0;		/* reserved */
4275 		buf[len++] = 0;		/* Zero out page length for now (MSB) */
4276 		buf[len++] = 0;		/* (LSB) */
4277 
4278 		sdinfo = sata_get_device_info(
4279 		    spx->txlt_sata_hba_inst,
4280 		    &spx->txlt_sata_pkt->satapkt_device);
4281 
4282 		/*
4283 		 * Add requested pages.
4284 		 */
4285 		switch (page_code) {
4286 		case PAGE_CODE_GET_SUPPORTED_LOG_PAGES:
4287 			len = sata_build_lsense_page_0(sdinfo, buf + len);
4288 			break;
4289 		case PAGE_CODE_SELF_TEST_RESULTS:
4290 			sata_id = &sdinfo->satadrv_id;
4291 			if ((! (sata_id->ai_cmdset84 &
4292 			    SATA_SMART_SELF_TEST_SUPPORTED)) ||
4293 			    (! (sata_id->ai_features87 &
4294 			    SATA_SMART_SELF_TEST_SUPPORTED))) {
4295 				*scsipkt->pkt_scbp = STATUS_CHECK;
4296 				sense = sata_arq_sense(spx);
4297 				sense->es_key = KEY_ILLEGAL_REQUEST;
4298 				sense->es_add_code =
4299 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
4300 
4301 				goto done;
4302 			}
4303 			len = sata_build_lsense_page_10(sdinfo, buf + len,
4304 			    spx->txlt_sata_hba_inst);
4305 			break;
4306 		case PAGE_CODE_INFORMATION_EXCEPTIONS:
4307 			sata_id = &sdinfo->satadrv_id;
4308 			if (! (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED)) {
4309 				*scsipkt->pkt_scbp = STATUS_CHECK;
4310 				sense = sata_arq_sense(spx);
4311 				sense->es_key = KEY_ILLEGAL_REQUEST;
4312 				sense->es_add_code =
4313 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
4314 
4315 				goto done;
4316 			}
4317 			if (! (sata_id->ai_features85 & SATA_SMART_ENABLED)) {
4318 				*scsipkt->pkt_scbp = STATUS_CHECK;
4319 				sense = sata_arq_sense(spx);
4320 				sense->es_key = KEY_ABORTED_COMMAND;
4321 				sense->es_add_code =
4322 				    SCSI_ASC_ATA_DEV_FEAT_NOT_ENABLED;
4323 				sense->es_qual_code =
4324 				    SCSI_ASCQ_ATA_DEV_FEAT_NOT_ENABLED;
4325 
4326 				goto done;
4327 			}
4328 
4329 			len = sata_build_lsense_page_2f(sdinfo, buf + len,
4330 			    spx->txlt_sata_hba_inst);
4331 			break;
4332 		case PAGE_CODE_SMART_READ_DATA:
4333 			sata_id = &sdinfo->satadrv_id;
4334 			if (! (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED)) {
4335 				*scsipkt->pkt_scbp = STATUS_CHECK;
4336 				sense = sata_arq_sense(spx);
4337 				sense->es_key = KEY_ILLEGAL_REQUEST;
4338 				sense->es_add_code =
4339 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
4340 
4341 				goto done;
4342 			}
4343 			if (! (sata_id->ai_features85 & SATA_SMART_ENABLED)) {
4344 				*scsipkt->pkt_scbp = STATUS_CHECK;
4345 				sense = sata_arq_sense(spx);
4346 				sense->es_key = KEY_ABORTED_COMMAND;
4347 				sense->es_add_code =
4348 				    SCSI_ASC_ATA_DEV_FEAT_NOT_ENABLED;
4349 				sense->es_qual_code =
4350 				    SCSI_ASCQ_ATA_DEV_FEAT_NOT_ENABLED;
4351 
4352 				goto done;
4353 			}
4354 
4355 			/* This page doesn't include a page header */
4356 			len = sata_build_lsense_page_30(sdinfo, buf,
4357 			    spx->txlt_sata_hba_inst);
4358 			goto no_header;
4359 		default:
4360 			/* Invalid request */
4361 			*scsipkt->pkt_scbp = STATUS_CHECK;
4362 			sense = sata_arq_sense(spx);
4363 			sense->es_key = KEY_ILLEGAL_REQUEST;
4364 			sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
4365 			goto done;
4366 		}
4367 
4368 		/* set parameter log sense data length */
4369 		buf[2] = len >> 8;	/* log sense length (MSB) */
4370 		buf[3] = len & 0xff;	/* log sense length (LSB) */
4371 
4372 		len += SCSI_LOG_PAGE_HDR_LEN;
4373 		ASSERT(len <= MAX_LOG_SENSE_PAGE_SIZE);
4374 
4375 no_header:
4376 		/* Check allocation length */
4377 		alc_len = scsipkt->pkt_cdbp[7];
4378 		alc_len = (len << 8) | scsipkt->pkt_cdbp[8];
4379 
4380 		/*
4381 		 * We do not check for possible parameters truncation
4382 		 * (alc_len < len) assuming that the target driver works
4383 		 * correctly. Just avoiding overrun.
4384 		 * Copy no more than requested and possible, buffer-wise.
4385 		 */
4386 		count = MIN(alc_len, len);
4387 		count = MIN(bp->b_bcount, count);
4388 		bcopy(buf, bp->b_un.b_addr, count);
4389 
4390 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
4391 		scsipkt->pkt_resid = alc_len > count ? alc_len - count : 0;
4392 	}
4393 	*scsipkt->pkt_scbp = STATUS_GOOD;
4394 done:
4395 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4396 	(void) kmem_free(buf, MAX_LOG_SENSE_PAGE_SIZE);
4397 
4398 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4399 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
4400 
4401 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4402 	    scsipkt->pkt_comp != NULL)
4403 		/* scsi callback required */
4404 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4405 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
4406 		    TQ_SLEEP) == NULL)
4407 			/* Scheduling the callback failed */
4408 			return (TRAN_BUSY);
4409 
4410 	return (TRAN_ACCEPT);
4411 }
4412 
4413 /*
4414  * Translate command: Log Select
4415  * Not implemented at this time - returns invalid command response.
4416  */
4417 static 	int
4418 sata_txlt_log_select(sata_pkt_txlate_t *spx)
4419 {
4420 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4421 	    "sata_txlt_log_select\n", NULL);
4422 
4423 	return (sata_txlt_invalid_command(spx));
4424 }
4425 
4426 
4427 /*
4428  * Translate command: Read (various types).
4429  * Translated into appropriate type of ATA READ command
4430  * for SATA hard disks.
4431  * Both the device capabilities and requested operation mode are
4432  * considered.
4433  *
4434  * Following scsi cdb fields are ignored:
4435  * rdprotect, dpo, fua, fua_nv, group_number.
4436  *
4437  * If SATA_ENABLE_QUEUING flag is set (in the global SATA HBA framework
4438  * enable variable sata_func_enable), the capability of the controller and
4439  * capability of a device are checked and if both support queueing, read
4440  * request will be translated to READ_DMA_QUEUEING or READ_DMA_QUEUEING_EXT
4441  * command rather than plain READ_XXX command.
4442  * If SATA_ENABLE_NCQ flag is set in addition to SATA_ENABLE_QUEUING flag and
4443  * both the controller and device suport such functionality, the read
4444  * request will be translated to READ_FPDMA_QUEUED command.
4445  * In both cases the maximum queue depth is derived as minimum of:
4446  * HBA capability,device capability and sata_max_queue_depth variable setting.
4447  * The value passed to HBA driver is decremented by 1, because only 5 bits are
4448  * used to pass max queue depth value, and the maximum possible queue depth
4449  * is 32.
4450  *
4451  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
4452  * appropriate values in scsi_pkt fields.
4453  */
4454 static int
4455 sata_txlt_read(sata_pkt_txlate_t *spx)
4456 {
4457 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
4458 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
4459 	sata_drive_info_t *sdinfo;
4460 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
4461 	int cport = SATA_TXLT_CPORT(spx);
4462 	uint16_t sec_count;
4463 	uint64_t lba;
4464 	int rval, reason;
4465 	int synch;
4466 
4467 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4468 
4469 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
4470 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
4471 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4472 		return (rval);
4473 	}
4474 
4475 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
4476 	    &spx->txlt_sata_pkt->satapkt_device);
4477 
4478 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
4479 	/*
4480 	 * Extract LBA and sector count from scsi CDB.
4481 	 */
4482 	switch ((uint_t)scsipkt->pkt_cdbp[0]) {
4483 	case SCMD_READ:
4484 		/* 6-byte scsi read cmd : 0x08 */
4485 		lba = (scsipkt->pkt_cdbp[1] & 0x1f);
4486 		lba = (lba << 8) | scsipkt->pkt_cdbp[2];
4487 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
4488 		sec_count = scsipkt->pkt_cdbp[4];
4489 		/* sec_count 0 will be interpreted as 256 by a device */
4490 		break;
4491 	case SCMD_READ_G1:
4492 		/* 10-bytes scsi read command : 0x28 */
4493 		lba = scsipkt->pkt_cdbp[2];
4494 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
4495 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
4496 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
4497 		sec_count = scsipkt->pkt_cdbp[7];
4498 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
4499 		break;
4500 	case SCMD_READ_G5:
4501 		/* 12-bytes scsi read command : 0xA8 */
4502 		lba = scsipkt->pkt_cdbp[2];
4503 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
4504 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
4505 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
4506 		sec_count = scsipkt->pkt_cdbp[6];
4507 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[7];
4508 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
4509 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[9];
4510 		break;
4511 	case SCMD_READ_G4:
4512 		/* 16-bytes scsi read command : 0x88 */
4513 		lba = scsipkt->pkt_cdbp[2];
4514 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
4515 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
4516 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
4517 		lba = (lba << 8) | scsipkt->pkt_cdbp[6];
4518 		lba = (lba << 8) | scsipkt->pkt_cdbp[7];
4519 		lba = (lba << 8) | scsipkt->pkt_cdbp[8];
4520 		lba = (lba << 8) | scsipkt->pkt_cdbp[9];
4521 		sec_count = scsipkt->pkt_cdbp[10];
4522 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[11];
4523 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[12];
4524 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[13];
4525 		break;
4526 	default:
4527 		/* Unsupported command */
4528 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4529 		return (sata_txlt_invalid_command(spx));
4530 	}
4531 
4532 	/*
4533 	 * Check if specified address exceeds device capacity
4534 	 */
4535 	if ((lba >= sdinfo->satadrv_capacity) ||
4536 	    ((lba + sec_count) > sdinfo->satadrv_capacity)) {
4537 		/* LBA out of range */
4538 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4539 		return (sata_txlt_lba_out_of_range(spx));
4540 	}
4541 
4542 	/*
4543 	 * For zero-length transfer, emulate good completion of the command
4544 	 * (reasons for rejecting the command were already checked).
4545 	 * No DMA resources were allocated.
4546 	 */
4547 	if (spx->txlt_dma_cookie_list == NULL) {
4548 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4549 		return (sata_emul_rw_completion(spx));
4550 	}
4551 
4552 	/*
4553 	 * Build cmd block depending on the device capability and
4554 	 * requested operation mode.
4555 	 * Do not bother with non-dma mode - we are working only with
4556 	 * devices supporting DMA.
4557 	 */
4558 	scmd->satacmd_addr_type = ATA_ADDR_LBA;
4559 	scmd->satacmd_device_reg = SATA_ADH_LBA;
4560 	scmd->satacmd_cmd_reg = SATAC_READ_DMA;
4561 	if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48) {
4562 		scmd->satacmd_addr_type = ATA_ADDR_LBA48;
4563 		scmd->satacmd_cmd_reg = SATAC_READ_DMA_EXT;
4564 		scmd->satacmd_sec_count_msb = sec_count >> 8;
4565 #ifndef __lock_lint
4566 		scmd->satacmd_lba_low_msb = (lba >> 24) & 0xff;
4567 		scmd->satacmd_lba_mid_msb = (lba >> 32) & 0xff;
4568 		scmd->satacmd_lba_high_msb = lba >> 40;
4569 #endif
4570 	} else if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA28) {
4571 		scmd->satacmd_addr_type = ATA_ADDR_LBA28;
4572 		scmd->satacmd_device_reg = SATA_ADH_LBA | ((lba >> 24) & 0xf);
4573 	}
4574 	scmd->satacmd_sec_count_lsb = sec_count & 0xff;
4575 	scmd->satacmd_lba_low_lsb = lba & 0xff;
4576 	scmd->satacmd_lba_mid_lsb = (lba >> 8) & 0xff;
4577 	scmd->satacmd_lba_high_lsb = (lba >> 16) & 0xff;
4578 	scmd->satacmd_features_reg = 0;
4579 	scmd->satacmd_status_reg = 0;
4580 	scmd->satacmd_error_reg = 0;
4581 
4582 	/*
4583 	 * Check if queueing commands should be used and switch
4584 	 * to appropriate command if possible
4585 	 */
4586 	if (sata_func_enable & SATA_ENABLE_QUEUING) {
4587 		boolean_t using_queuing;
4588 
4589 		/* Queuing supported by controller and device? */
4590 		if ((sata_func_enable & SATA_ENABLE_NCQ) &&
4591 		    (sdinfo->satadrv_features_support &
4592 		    SATA_DEV_F_NCQ) &&
4593 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
4594 		    SATA_CTLF_NCQ)) {
4595 			using_queuing = B_TRUE;
4596 
4597 			/* NCQ supported - use FPDMA READ */
4598 			scmd->satacmd_cmd_reg =
4599 			    SATAC_READ_FPDMA_QUEUED;
4600 			scmd->satacmd_features_reg_ext =
4601 			    scmd->satacmd_sec_count_msb;
4602 			scmd->satacmd_sec_count_msb = 0;
4603 		} else if ((sdinfo->satadrv_features_support &
4604 		    SATA_DEV_F_TCQ) &&
4605 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
4606 		    SATA_CTLF_QCMD)) {
4607 			using_queuing = B_TRUE;
4608 
4609 			/* Legacy queueing */
4610 			if (sdinfo->satadrv_features_support &
4611 			    SATA_DEV_F_LBA48) {
4612 				scmd->satacmd_cmd_reg =
4613 				    SATAC_READ_DMA_QUEUED_EXT;
4614 				scmd->satacmd_features_reg_ext =
4615 				    scmd->satacmd_sec_count_msb;
4616 				scmd->satacmd_sec_count_msb = 0;
4617 			} else {
4618 				scmd->satacmd_cmd_reg =
4619 				    SATAC_READ_DMA_QUEUED;
4620 			}
4621 		} else	/* NCQ nor legacy queuing not supported */
4622 			using_queuing = B_FALSE;
4623 
4624 		/*
4625 		 * If queuing, the sector count goes in the features register
4626 		 * and the secount count will contain the tag.
4627 		 */
4628 		if (using_queuing) {
4629 			scmd->satacmd_features_reg =
4630 			    scmd->satacmd_sec_count_lsb;
4631 			scmd->satacmd_sec_count_lsb = 0;
4632 			scmd->satacmd_flags.sata_queued = B_TRUE;
4633 
4634 			/* Set-up maximum queue depth */
4635 			scmd->satacmd_flags.sata_max_queue_depth =
4636 			    sdinfo->satadrv_max_queue_depth - 1;
4637 		} else if (sdinfo->satadrv_features_enabled &
4638 		    SATA_DEV_F_E_UNTAGGED_QING) {
4639 			/*
4640 			 * Although NCQ/TCQ is not enabled, untagged queuing
4641 			 * may be still used.
4642 			 * Set-up the maximum untagged queue depth.
4643 			 * Use controller's queue depth from sata_hba_tran.
4644 			 * SATA HBA drivers may ignore this value and rely on
4645 			 * the internal limits.For drivers that do not
4646 			 * ignore untaged queue depth, limit the value to
4647 			 * SATA_MAX_QUEUE_DEPTH (32), as this is the
4648 			 * largest value that can be passed via
4649 			 * satacmd_flags.sata_max_queue_depth.
4650 			 */
4651 			scmd->satacmd_flags.sata_max_queue_depth =
4652 			    SATA_QDEPTH(shi) <= SATA_MAX_QUEUE_DEPTH ?
4653 			    SATA_QDEPTH(shi) - 1: SATA_MAX_QUEUE_DEPTH - 1;
4654 
4655 		} else {
4656 			scmd->satacmd_flags.sata_max_queue_depth = 0;
4657 		}
4658 	} else
4659 		scmd->satacmd_flags.sata_max_queue_depth = 0;
4660 
4661 	SATADBG3(SATA_DBG_HBA_IF, spx->txlt_sata_hba_inst,
4662 	    "sata_txlt_read cmd 0x%2x, lba %llx, sec count %x\n",
4663 	    scmd->satacmd_cmd_reg, lba, sec_count);
4664 
4665 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
4666 		/* Need callback function */
4667 		spx->txlt_sata_pkt->satapkt_comp = sata_txlt_rw_completion;
4668 		synch = FALSE;
4669 	} else
4670 		synch = TRUE;
4671 
4672 	/* Transfer command to HBA */
4673 	if (sata_hba_start(spx, &rval) != 0) {
4674 		/* Pkt not accepted for execution */
4675 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4676 		return (rval);
4677 	}
4678 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4679 	/*
4680 	 * If execution is non-synchronous,
4681 	 * a callback function will handle potential errors, translate
4682 	 * the response and will do a callback to a target driver.
4683 	 * If it was synchronous, check execution status using the same
4684 	 * framework callback.
4685 	 */
4686 	if (synch) {
4687 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4688 		    "synchronous execution status %x\n",
4689 		    spx->txlt_sata_pkt->satapkt_reason);
4690 		sata_txlt_rw_completion(spx->txlt_sata_pkt);
4691 	}
4692 	return (TRAN_ACCEPT);
4693 }
4694 
4695 
4696 /*
4697  * SATA translate command: Write (various types)
4698  * Translated into appropriate type of ATA WRITE command
4699  * for SATA hard disks.
4700  * Both the device capabilities and requested operation mode are
4701  * considered.
4702  *
4703  * Following scsi cdb fields are ignored:
4704  * rwprotect, dpo, fua, fua_nv, group_number.
4705  *
4706  * If SATA_ENABLE_QUEUING flag is set (in the global SATA HBA framework
4707  * enable variable sata_func_enable), the capability of the controller and
4708  * capability of a device are checked and if both support queueing, write
4709  * request will be translated to WRITE_DMA_QUEUEING or WRITE_DMA_QUEUEING_EXT
4710  * command rather than plain WRITE_XXX command.
4711  * If SATA_ENABLE_NCQ flag is set in addition to SATA_ENABLE_QUEUING flag and
4712  * both the controller and device suport such functionality, the write
4713  * request will be translated to WRITE_FPDMA_QUEUED command.
4714  * In both cases the maximum queue depth is derived as minimum of:
4715  * HBA capability,device capability and sata_max_queue_depth variable setting.
4716  * The value passed to HBA driver is decremented by 1, because only 5 bits are
4717  * used to pass max queue depth value, and the maximum possible queue depth
4718  * is 32.
4719  *
4720  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
4721  * appropriate values in scsi_pkt fields.
4722  */
4723 static int
4724 sata_txlt_write(sata_pkt_txlate_t *spx)
4725 {
4726 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
4727 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
4728 	sata_drive_info_t *sdinfo;
4729 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
4730 	int cport = SATA_TXLT_CPORT(spx);
4731 	uint16_t sec_count;
4732 	uint64_t lba;
4733 	int rval, reason;
4734 	int synch;
4735 
4736 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4737 
4738 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
4739 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
4740 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4741 		return (rval);
4742 	}
4743 
4744 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
4745 	    &spx->txlt_sata_pkt->satapkt_device);
4746 
4747 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_WRITE;
4748 	/*
4749 	 * Extract LBA and sector count from scsi CDB
4750 	 */
4751 	switch ((uint_t)scsipkt->pkt_cdbp[0]) {
4752 	case SCMD_WRITE:
4753 		/* 6-byte scsi read cmd : 0x0A */
4754 		lba = (scsipkt->pkt_cdbp[1] & 0x1f);
4755 		lba = (lba << 8) | scsipkt->pkt_cdbp[2];
4756 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
4757 		sec_count = scsipkt->pkt_cdbp[4];
4758 		/* sec_count 0 will be interpreted as 256 by a device */
4759 		break;
4760 	case SCMD_WRITE_G1:
4761 		/* 10-bytes scsi write command : 0x2A */
4762 		lba = scsipkt->pkt_cdbp[2];
4763 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
4764 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
4765 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
4766 		sec_count = scsipkt->pkt_cdbp[7];
4767 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
4768 		break;
4769 	case SCMD_WRITE_G5:
4770 		/* 12-bytes scsi read command : 0xAA */
4771 		lba = scsipkt->pkt_cdbp[2];
4772 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
4773 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
4774 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
4775 		sec_count = scsipkt->pkt_cdbp[6];
4776 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[7];
4777 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
4778 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[9];
4779 		break;
4780 	case SCMD_WRITE_G4:
4781 		/* 16-bytes scsi write command : 0x8A */
4782 		lba = scsipkt->pkt_cdbp[2];
4783 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
4784 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
4785 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
4786 		lba = (lba << 8) | scsipkt->pkt_cdbp[6];
4787 		lba = (lba << 8) | scsipkt->pkt_cdbp[7];
4788 		lba = (lba << 8) | scsipkt->pkt_cdbp[8];
4789 		lba = (lba << 8) | scsipkt->pkt_cdbp[9];
4790 		sec_count = scsipkt->pkt_cdbp[10];
4791 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[11];
4792 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[12];
4793 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[13];
4794 		break;
4795 	default:
4796 		/* Unsupported command */
4797 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4798 		return (sata_txlt_invalid_command(spx));
4799 	}
4800 
4801 	/*
4802 	 * Check if specified address and length exceeds device capacity
4803 	 */
4804 	if ((lba >= sdinfo->satadrv_capacity) ||
4805 	    ((lba + sec_count) > sdinfo->satadrv_capacity)) {
4806 		/* LBA out of range */
4807 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4808 		return (sata_txlt_lba_out_of_range(spx));
4809 	}
4810 
4811 	/*
4812 	 * For zero-length transfer, emulate good completion of the command
4813 	 * (reasons for rejecting the command were already checked).
4814 	 * No DMA resources were allocated.
4815 	 */
4816 	if (spx->txlt_dma_cookie_list == NULL) {
4817 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4818 		return (sata_emul_rw_completion(spx));
4819 	}
4820 
4821 	/*
4822 	 * Build cmd block depending on the device capability and
4823 	 * requested operation mode.
4824 	 * Do not bother with non-dma mode- we are working only with
4825 	 * devices supporting DMA.
4826 	 */
4827 	scmd->satacmd_addr_type = ATA_ADDR_LBA;
4828 	scmd->satacmd_device_reg = SATA_ADH_LBA;
4829 	scmd->satacmd_cmd_reg = SATAC_WRITE_DMA;
4830 	if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48) {
4831 		scmd->satacmd_addr_type = ATA_ADDR_LBA48;
4832 		scmd->satacmd_cmd_reg = SATAC_WRITE_DMA_EXT;
4833 		scmd->satacmd_sec_count_msb = sec_count >> 8;
4834 		scmd->satacmd_lba_low_msb = (lba >> 24) & 0xff;
4835 #ifndef __lock_lint
4836 		scmd->satacmd_lba_mid_msb = (lba >> 32) & 0xff;
4837 		scmd->satacmd_lba_high_msb = lba >> 40;
4838 #endif
4839 	} else if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA28) {
4840 		scmd->satacmd_addr_type = ATA_ADDR_LBA28;
4841 		scmd->satacmd_device_reg = SATA_ADH_LBA | ((lba >> 24) & 0xf);
4842 	}
4843 	scmd->satacmd_sec_count_lsb = sec_count & 0xff;
4844 	scmd->satacmd_lba_low_lsb = lba & 0xff;
4845 	scmd->satacmd_lba_mid_lsb = (lba >> 8) & 0xff;
4846 	scmd->satacmd_lba_high_lsb = (lba >> 16) & 0xff;
4847 	scmd->satacmd_features_reg = 0;
4848 	scmd->satacmd_status_reg = 0;
4849 	scmd->satacmd_error_reg = 0;
4850 
4851 	/*
4852 	 * Check if queueing commands should be used and switch
4853 	 * to appropriate command if possible
4854 	 */
4855 	if (sata_func_enable & SATA_ENABLE_QUEUING) {
4856 		boolean_t using_queuing;
4857 
4858 		/* Queuing supported by controller and device? */
4859 		if ((sata_func_enable & SATA_ENABLE_NCQ) &&
4860 		    (sdinfo->satadrv_features_support &
4861 		    SATA_DEV_F_NCQ) &&
4862 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
4863 		    SATA_CTLF_NCQ)) {
4864 			using_queuing = B_TRUE;
4865 
4866 			/* NCQ supported - use FPDMA WRITE */
4867 			scmd->satacmd_cmd_reg =
4868 			    SATAC_WRITE_FPDMA_QUEUED;
4869 			scmd->satacmd_features_reg_ext =
4870 			    scmd->satacmd_sec_count_msb;
4871 			scmd->satacmd_sec_count_msb = 0;
4872 		} else if ((sdinfo->satadrv_features_support &
4873 		    SATA_DEV_F_TCQ) &&
4874 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
4875 		    SATA_CTLF_QCMD)) {
4876 			using_queuing = B_TRUE;
4877 
4878 			/* Legacy queueing */
4879 			if (sdinfo->satadrv_features_support &
4880 			    SATA_DEV_F_LBA48) {
4881 				scmd->satacmd_cmd_reg =
4882 				    SATAC_WRITE_DMA_QUEUED_EXT;
4883 				scmd->satacmd_features_reg_ext =
4884 				    scmd->satacmd_sec_count_msb;
4885 				scmd->satacmd_sec_count_msb = 0;
4886 			} else {
4887 				scmd->satacmd_cmd_reg =
4888 				    SATAC_WRITE_DMA_QUEUED;
4889 			}
4890 		} else	/*  NCQ nor legacy queuing not supported */
4891 			using_queuing = B_FALSE;
4892 
4893 		if (using_queuing) {
4894 			scmd->satacmd_features_reg =
4895 			    scmd->satacmd_sec_count_lsb;
4896 			scmd->satacmd_sec_count_lsb = 0;
4897 			scmd->satacmd_flags.sata_queued = B_TRUE;
4898 			/* Set-up maximum queue depth */
4899 			scmd->satacmd_flags.sata_max_queue_depth =
4900 			    sdinfo->satadrv_max_queue_depth - 1;
4901 		} else if (sdinfo->satadrv_features_enabled &
4902 		    SATA_DEV_F_E_UNTAGGED_QING) {
4903 			/*
4904 			 * Although NCQ/TCQ is not enabled, untagged queuing
4905 			 * may be still used.
4906 			 * Set-up the maximum untagged queue depth.
4907 			 * Use controller's queue depth from sata_hba_tran.
4908 			 * SATA HBA drivers may ignore this value and rely on
4909 			 * the internal limits. For drivera that do not
4910 			 * ignore untaged queue depth, limit the value to
4911 			 * SATA_MAX_QUEUE_DEPTH (32), as this is the
4912 			 * largest value that can be passed via
4913 			 * satacmd_flags.sata_max_queue_depth.
4914 			 */
4915 			scmd->satacmd_flags.sata_max_queue_depth =
4916 			    SATA_QDEPTH(shi) <= SATA_MAX_QUEUE_DEPTH ?
4917 			    SATA_QDEPTH(shi) - 1: SATA_MAX_QUEUE_DEPTH - 1;
4918 
4919 		} else {
4920 			scmd->satacmd_flags.sata_max_queue_depth = 0;
4921 		}
4922 	} else
4923 		scmd->satacmd_flags.sata_max_queue_depth = 0;
4924 
4925 	SATADBG3(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4926 	    "sata_txlt_write cmd 0x%2x, lba %llx, sec count %x\n",
4927 	    scmd->satacmd_cmd_reg, lba, sec_count);
4928 
4929 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
4930 		/* Need callback function */
4931 		spx->txlt_sata_pkt->satapkt_comp = sata_txlt_rw_completion;
4932 		synch = FALSE;
4933 	} else
4934 		synch = TRUE;
4935 
4936 	/* Transfer command to HBA */
4937 	if (sata_hba_start(spx, &rval) != 0) {
4938 		/* Pkt not accepted for execution */
4939 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4940 		return (rval);
4941 	}
4942 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4943 
4944 	/*
4945 	 * If execution is non-synchronous,
4946 	 * a callback function will handle potential errors, translate
4947 	 * the response and will do a callback to a target driver.
4948 	 * If it was synchronous, check execution status using the same
4949 	 * framework callback.
4950 	 */
4951 	if (synch) {
4952 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4953 		    "synchronous execution status %x\n",
4954 		    spx->txlt_sata_pkt->satapkt_reason);
4955 		sata_txlt_rw_completion(spx->txlt_sata_pkt);
4956 	}
4957 	return (TRAN_ACCEPT);
4958 }
4959 
4960 
4961 /*
4962  * Implements SCSI SBC WRITE BUFFER command download microcode option
4963  */
4964 static int
4965 sata_txlt_write_buffer(sata_pkt_txlate_t *spx)
4966 {
4967 #define	WB_DOWNLOAD_MICROCODE_AND_REVERT_MODE			4
4968 #define	WB_DOWNLOAD_MICROCODE_AND_SAVE_MODE			5
4969 
4970 	sata_hba_inst_t *sata_hba_inst = SATA_TXLT_HBA_INST(spx);
4971 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
4972 	struct sata_pkt *sata_pkt = spx->txlt_sata_pkt;
4973 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
4974 
4975 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
4976 	struct scsi_extended_sense *sense;
4977 	int rval, mode, sector_count, reason;
4978 	int cport = SATA_TXLT_CPORT(spx);
4979 
4980 	mode = scsipkt->pkt_cdbp[1] & 0x1f;
4981 
4982 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4983 	    "sata_txlt_write_buffer, mode 0x%x\n", mode);
4984 
4985 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4986 
4987 	if ((rval = sata_txlt_generic_pkt_info(spx, &reason)) != TRAN_ACCEPT) {
4988 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4989 		return (rval);
4990 	}
4991 	/*
4992 	 * If in interrupt context, reject this packet because it would issue
4993 	 * a synchronous command to HBA.
4994 	 */
4995 	if (servicing_interrupt()) {
4996 		SATADBG1(SATA_DBG_INTR_CTX, spx->txlt_sata_hba_inst,
4997 		    "sata_txlt_write_buffer: rejecting command because "
4998 		    "of interrupt context\n", NULL);
4999 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5000 		return (TRAN_BUSY);
5001 	}
5002 
5003 	/* Use synchronous mode */
5004 	spx->txlt_sata_pkt->satapkt_op_mode
5005 	    |= SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
5006 
5007 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_WRITE;
5008 
5009 	scsipkt->pkt_reason = CMD_CMPLT;
5010 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
5011 	    STATE_SENT_CMD | STATE_GOT_STATUS;
5012 
5013 	/*
5014 	 * The SCSI to ATA translation specification only calls
5015 	 * for WB_DOWNLOAD_MICROCODE_AND_SAVE_MODE.
5016 	 * WB_DOWNLOAD_MICROC_AND_REVERT_MODE is implemented, but
5017 	 * ATA 8 (draft) got rid of download microcode for temp
5018 	 * and it is even optional for ATA 7, so it may be aborted.
5019 	 * WB_DOWNLOAD_MICROCODE_WITH_OFFSET is not implemented as
5020 	 * it is not specified and the buffer offset for SCSI is a 16-bit
5021 	 * value in bytes, but for ATA it is a 16-bit offset in 512 byte
5022 	 * sectors.  Thus the offset really doesn't buy us anything.
5023 	 * If and when ATA 8 is stabilized and the SCSI to ATA specification
5024 	 * is revised, this can be revisisted.
5025 	 */
5026 	/* Reject not supported request */
5027 	switch (mode) {
5028 	case WB_DOWNLOAD_MICROCODE_AND_REVERT_MODE:
5029 		scmd->satacmd_features_reg = SATA_DOWNLOAD_MCODE_TEMP;
5030 		break;
5031 	case WB_DOWNLOAD_MICROCODE_AND_SAVE_MODE:
5032 		scmd->satacmd_features_reg = SATA_DOWNLOAD_MCODE_SAVE;
5033 		break;
5034 	default:
5035 		goto bad_param;
5036 	}
5037 
5038 	*scsipkt->pkt_scbp = STATUS_GOOD;	/* Presumed outcome */
5039 
5040 	scmd->satacmd_cmd_reg = SATAC_DOWNLOAD_MICROCODE;
5041 	if ((bp->b_bcount % SATA_DISK_SECTOR_SIZE) != 0)
5042 		goto bad_param;
5043 	sector_count = bp->b_bcount / SATA_DISK_SECTOR_SIZE;
5044 	scmd->satacmd_sec_count_lsb = (uint8_t)sector_count;
5045 	scmd->satacmd_lba_low_lsb = ((uint16_t)sector_count) >> 8;
5046 	scmd->satacmd_lba_mid_lsb = 0;
5047 	scmd->satacmd_lba_high_lsb = 0;
5048 	scmd->satacmd_device_reg = 0;
5049 	spx->txlt_sata_pkt->satapkt_comp = NULL;
5050 	scmd->satacmd_addr_type = 0;
5051 
5052 	/* Transfer command to HBA */
5053 	if (sata_hba_start(spx, &rval) != 0) {
5054 		/* Pkt not accepted for execution */
5055 		mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
5056 		return (rval);
5057 	}
5058 
5059 	mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
5060 
5061 	/* Then we need synchronous check the status of the disk */
5062 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
5063 	    STATE_SENT_CMD | STATE_XFERRED_DATA | STATE_GOT_STATUS;
5064 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
5065 		scsipkt->pkt_reason = CMD_CMPLT;
5066 
5067 		/* Download commmand succeed, so probe and identify device */
5068 		sata_reidentify_device(spx);
5069 	} else {
5070 		/* Something went wrong, microcode download command failed */
5071 		scsipkt->pkt_reason = CMD_INCOMPLETE;
5072 		*scsipkt->pkt_scbp = STATUS_CHECK;
5073 		sense = sata_arq_sense(spx);
5074 		switch (sata_pkt->satapkt_reason) {
5075 		case SATA_PKT_PORT_ERROR:
5076 			/*
5077 			 * We have no device data. Assume no data transfered.
5078 			 */
5079 			sense->es_key = KEY_HARDWARE_ERROR;
5080 			break;
5081 
5082 		case SATA_PKT_DEV_ERROR:
5083 			if (sata_pkt->satapkt_cmd.satacmd_status_reg &
5084 			    SATA_STATUS_ERR) {
5085 				/*
5086 				 * determine dev error reason from error
5087 				 * reg content
5088 				 */
5089 				sata_decode_device_error(spx, sense);
5090 				break;
5091 			}
5092 			/* No extended sense key - no info available */
5093 			break;
5094 
5095 		case SATA_PKT_TIMEOUT:
5096 			scsipkt->pkt_reason = CMD_TIMEOUT;
5097 			scsipkt->pkt_statistics |=
5098 			    STAT_TIMEOUT | STAT_DEV_RESET;
5099 			/* No extended sense key ? */
5100 			break;
5101 
5102 		case SATA_PKT_ABORTED:
5103 			scsipkt->pkt_reason = CMD_ABORTED;
5104 			scsipkt->pkt_statistics |= STAT_ABORTED;
5105 			/* No extended sense key ? */
5106 			break;
5107 
5108 		case SATA_PKT_RESET:
5109 			/* pkt aborted by an explicit reset from a host */
5110 			scsipkt->pkt_reason = CMD_RESET;
5111 			scsipkt->pkt_statistics |= STAT_DEV_RESET;
5112 			break;
5113 
5114 		default:
5115 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
5116 			    "sata_txlt_nodata_cmd_completion: "
5117 			    "invalid packet completion reason %d",
5118 			    sata_pkt->satapkt_reason));
5119 			scsipkt->pkt_reason = CMD_TRAN_ERR;
5120 			break;
5121 		}
5122 
5123 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5124 		    "scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
5125 
5126 		if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
5127 			/* scsi callback required */
5128 			scsi_hba_pkt_comp(scsipkt);
5129 	}
5130 	return (TRAN_ACCEPT);
5131 
5132 bad_param:
5133 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5134 	*scsipkt->pkt_scbp = STATUS_CHECK;
5135 	sense = sata_arq_sense(spx);
5136 	sense->es_key = KEY_ILLEGAL_REQUEST;
5137 	sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5138 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
5139 	    scsipkt->pkt_comp != NULL) {
5140 		/* scsi callback required */
5141 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
5142 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
5143 		    TQ_SLEEP) == 0) {
5144 			/* Scheduling the callback failed */
5145 			rval = TRAN_BUSY;
5146 		}
5147 	}
5148 	return (rval);
5149 }
5150 
5151 /*
5152  * Re-identify device after doing a firmware download.
5153  */
5154 static void
5155 sata_reidentify_device(sata_pkt_txlate_t *spx)
5156 {
5157 #define	DOWNLOAD_WAIT_TIME_SECS	60
5158 #define	DOWNLOAD_WAIT_INTERVAL_SECS	1
5159 	int rval;
5160 	int retry_cnt;
5161 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5162 	sata_hba_inst_t *sata_hba_inst = spx->txlt_sata_hba_inst;
5163 	sata_device_t sata_device = spx->txlt_sata_pkt->satapkt_device;
5164 	sata_drive_info_t *sdinfo;
5165 
5166 	/*
5167 	 * Before returning good status, probe device.
5168 	 * Device probing will get IDENTIFY DEVICE data, if possible.
5169 	 * The assumption is that the new microcode is applied by the
5170 	 * device. It is a caller responsibility to verify this.
5171 	 */
5172 	for (retry_cnt = 0;
5173 	    retry_cnt < DOWNLOAD_WAIT_TIME_SECS / DOWNLOAD_WAIT_INTERVAL_SECS;
5174 	    retry_cnt++) {
5175 		rval = sata_probe_device(sata_hba_inst, &sata_device);
5176 
5177 		if (rval == SATA_SUCCESS) { /* Set default features */
5178 			sdinfo = sata_get_device_info(sata_hba_inst,
5179 			    &sata_device);
5180 			if (sata_initialize_device(sata_hba_inst, sdinfo) !=
5181 			    SATA_SUCCESS) {
5182 				/* retry */
5183 				rval = sata_initialize_device(sata_hba_inst,
5184 				    sdinfo);
5185 				if (rval == SATA_RETRY)
5186 					sata_log(sata_hba_inst, CE_WARN,
5187 					    "SATA device at port %d pmport %d -"
5188 					    " default device features could not"
5189 					    " be set. Device may not operate "
5190 					    "as expected.",
5191 					    sata_device.satadev_addr.cport,
5192 					    sata_device.satadev_addr.pmport);
5193 			}
5194 			if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
5195 				scsi_hba_pkt_comp(scsipkt);
5196 			return;
5197 		} else if (rval == SATA_RETRY) {
5198 			delay(drv_usectohz(1000000 *
5199 			    DOWNLOAD_WAIT_INTERVAL_SECS));
5200 			continue;
5201 		} else	/* failed - no reason to retry */
5202 			break;
5203 	}
5204 
5205 	/*
5206 	 * Something went wrong, device probing failed.
5207 	 */
5208 	SATA_LOG_D((sata_hba_inst, CE_WARN,
5209 	    "Cannot probe device after downloading microcode\n"));
5210 
5211 	/* Reset device to force retrying the probe. */
5212 	(void) (*SATA_RESET_DPORT_FUNC(sata_hba_inst))
5213 	    (SATA_DIP(sata_hba_inst), &sata_device);
5214 
5215 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
5216 		scsi_hba_pkt_comp(scsipkt);
5217 }
5218 
5219 
5220 /*
5221  * Translate command: Synchronize Cache.
5222  * Translates into Flush Cache command for SATA hard disks.
5223  *
5224  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
5225  * appropriate values in scsi_pkt fields.
5226  */
5227 static 	int
5228 sata_txlt_synchronize_cache(sata_pkt_txlate_t *spx)
5229 {
5230 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
5231 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
5232 	int cport = SATA_TXLT_CPORT(spx);
5233 	int rval, reason;
5234 	int synch;
5235 
5236 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
5237 
5238 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
5239 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
5240 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5241 		return (rval);
5242 	}
5243 
5244 	scmd->satacmd_addr_type = 0;
5245 	scmd->satacmd_cmd_reg = SATAC_FLUSH_CACHE;
5246 	scmd->satacmd_device_reg = 0;
5247 	scmd->satacmd_sec_count_lsb = 0;
5248 	scmd->satacmd_lba_low_lsb = 0;
5249 	scmd->satacmd_lba_mid_lsb = 0;
5250 	scmd->satacmd_lba_high_lsb = 0;
5251 	scmd->satacmd_features_reg = 0;
5252 	scmd->satacmd_status_reg = 0;
5253 	scmd->satacmd_error_reg = 0;
5254 
5255 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5256 	    "sata_txlt_synchronize_cache\n", NULL);
5257 
5258 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
5259 		/* Need to set-up a callback function */
5260 		spx->txlt_sata_pkt->satapkt_comp =
5261 		    sata_txlt_nodata_cmd_completion;
5262 		synch = FALSE;
5263 	} else
5264 		synch = TRUE;
5265 
5266 	/* Transfer command to HBA */
5267 	if (sata_hba_start(spx, &rval) != 0) {
5268 		/* Pkt not accepted for execution */
5269 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
5270 		return (rval);
5271 	}
5272 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
5273 
5274 	/*
5275 	 * If execution non-synchronous, it had to be completed
5276 	 * a callback function will handle potential errors, translate
5277 	 * the response and will do a callback to a target driver.
5278 	 * If it was synchronous, check status, using the same
5279 	 * framework callback.
5280 	 */
5281 	if (synch) {
5282 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5283 		    "synchronous execution status %x\n",
5284 		    spx->txlt_sata_pkt->satapkt_reason);
5285 		sata_txlt_nodata_cmd_completion(spx->txlt_sata_pkt);
5286 	}
5287 	return (TRAN_ACCEPT);
5288 }
5289 
5290 
5291 /*
5292  * Send pkt to SATA HBA driver
5293  *
5294  * This function may be called only if the operation is requested by scsi_pkt,
5295  * i.e. scsi_pkt is not NULL.
5296  *
5297  * This function has to be called with cport mutex held. It does release
5298  * the mutex when it calls HBA driver sata_tran_start function and
5299  * re-acquires it afterwards.
5300  *
5301  * If return value is 0, pkt was accepted, -1 otherwise
5302  * rval is set to appropriate sata_scsi_start return value.
5303  *
5304  * Note 1:If HBA driver returns value other than TRAN_ACCEPT, it should not
5305  * have called the sata_pkt callback function for this packet.
5306  *
5307  * The scsi callback has to be performed by the caller of this routine.
5308  *
5309  * Note 2: No port multiplier support for now.
5310  */
5311 static int
5312 sata_hba_start(sata_pkt_txlate_t *spx, int *rval)
5313 {
5314 	int stat, cport;
5315 	sata_hba_inst_t *sata_hba_inst = spx->txlt_sata_hba_inst;
5316 	sata_drive_info_t *sdinfo;
5317 	sata_device_t *sata_device;
5318 	uint8_t cmd;
5319 	struct sata_cmd_flags cmd_flags;
5320 
5321 	ASSERT(spx->txlt_sata_pkt != NULL);
5322 
5323 	cport = SATA_TXLT_CPORT(spx);
5324 	ASSERT(mutex_owned(&SATA_CPORT_MUTEX(sata_hba_inst, cport)));
5325 
5326 	sdinfo = sata_get_device_info(sata_hba_inst,
5327 	    &spx->txlt_sata_pkt->satapkt_device);
5328 	ASSERT(sdinfo != NULL);
5329 
5330 	/* Clear device reset state? */
5331 	if (sdinfo->satadrv_event_flags & SATA_EVNT_CLEAR_DEVICE_RESET) {
5332 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.
5333 		    sata_clear_dev_reset = B_TRUE;
5334 		sdinfo->satadrv_event_flags &= ~SATA_EVNT_CLEAR_DEVICE_RESET;
5335 		SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
5336 		    "sata_hba_start: clearing device reset state\n", NULL);
5337 	}
5338 	cmd = spx->txlt_sata_pkt->satapkt_cmd.satacmd_cmd_reg;
5339 	cmd_flags = spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags;
5340 	sata_device = &spx->txlt_sata_pkt->satapkt_device;
5341 
5342 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
5343 
5344 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5345 	    "Sata cmd 0x%2x\n", cmd);
5346 
5347 	stat = (*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst),
5348 	    spx->txlt_sata_pkt);
5349 
5350 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
5351 	/*
5352 	 * If sata pkt was accepted and executed in asynchronous mode, i.e.
5353 	 * with the sata callback, the sata_pkt could be already destroyed
5354 	 * by the time we check ther return status from the hba_start()
5355 	 * function, because sata_scsi_destroy_pkt() could have been already
5356 	 * called (perhaps in the interrupt context). So, in such case, there
5357 	 * should be no references to it. In other cases, sata_pkt still
5358 	 * exists.
5359 	 */
5360 	if (stat == SATA_TRAN_ACCEPTED) {
5361 		/*
5362 		 * pkt accepted for execution.
5363 		 * If it was executed synchronously, it is already completed
5364 		 * and pkt completion_reason indicates completion status.
5365 		 */
5366 		*rval = TRAN_ACCEPT;
5367 		return (0);
5368 	}
5369 
5370 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
5371 	switch (stat) {
5372 	case SATA_TRAN_QUEUE_FULL:
5373 		/*
5374 		 * Controller detected queue full condition.
5375 		 */
5376 		SATADBG1(SATA_DBG_HBA_IF, sata_hba_inst,
5377 		    "sata_hba_start: queue full\n", NULL);
5378 
5379 		spx->txlt_scsi_pkt->pkt_reason = CMD_INCOMPLETE;
5380 		*spx->txlt_scsi_pkt->pkt_scbp = STATUS_QFULL;
5381 
5382 		*rval = TRAN_BUSY;
5383 		break;
5384 
5385 	case SATA_TRAN_PORT_ERROR:
5386 		/*
5387 		 * Communication/link with device or general port error
5388 		 * detected before pkt execution begun.
5389 		 */
5390 		if (spx->txlt_sata_pkt->satapkt_device.satadev_addr.qual ==
5391 		    SATA_ADDR_CPORT ||
5392 		    spx->txlt_sata_pkt->satapkt_device.satadev_addr.qual ==
5393 		    SATA_ADDR_DCPORT)
5394 			sata_log(sata_hba_inst, CE_CONT,
5395 			    "SATA port %d error",
5396 			    sata_device->satadev_addr.cport);
5397 		else
5398 			sata_log(sata_hba_inst, CE_CONT,
5399 			    "SATA port %d pmport %d error\n",
5400 			    sata_device->satadev_addr.cport,
5401 			    sata_device->satadev_addr.pmport);
5402 
5403 		/*
5404 		 * Update the port/device structure.
5405 		 * sata_pkt should be still valid. Since port error is
5406 		 * returned, sata_device content should reflect port
5407 		 * state - it means, that sata address have been changed,
5408 		 * because original packet's sata address refered to a device
5409 		 * attached to some port.
5410 		 */
5411 		sata_update_port_info(sata_hba_inst, sata_device);
5412 		spx->txlt_scsi_pkt->pkt_reason = CMD_TRAN_ERR;
5413 		*rval = TRAN_FATAL_ERROR;
5414 		break;
5415 
5416 	case SATA_TRAN_CMD_UNSUPPORTED:
5417 		/*
5418 		 * Command rejected by HBA as unsupported. It was HBA driver
5419 		 * that rejected the command, command was not sent to
5420 		 * an attached device.
5421 		 */
5422 		if ((sdinfo != NULL) &&
5423 		    (sdinfo->satadrv_state & SATA_DSTATE_RESET))
5424 			SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
5425 			    "sat_hba_start: cmd 0x%2x rejected "
5426 			    "with SATA_TRAN_CMD_UNSUPPORTED status\n", cmd);
5427 
5428 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
5429 		(void) sata_txlt_invalid_command(spx);
5430 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
5431 
5432 		*rval = TRAN_ACCEPT;
5433 		break;
5434 
5435 	case SATA_TRAN_BUSY:
5436 		/*
5437 		 * Command rejected by HBA because other operation prevents
5438 		 * accepting the packet, or device is in RESET condition.
5439 		 */
5440 		if (sdinfo != NULL) {
5441 			sdinfo->satadrv_state =
5442 			    spx->txlt_sata_pkt->satapkt_device.satadev_state;
5443 
5444 			if (sdinfo->satadrv_state & SATA_DSTATE_RESET) {
5445 				SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
5446 				    "sata_hba_start: cmd 0x%2x rejected "
5447 				    "because of device reset condition\n",
5448 				    cmd);
5449 			} else {
5450 				SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
5451 				    "sata_hba_start: cmd 0x%2x rejected "
5452 				    "with SATA_TRAN_BUSY status\n",
5453 				    cmd);
5454 			}
5455 		}
5456 		spx->txlt_scsi_pkt->pkt_reason = CMD_INCOMPLETE;
5457 		*rval = TRAN_BUSY;
5458 		break;
5459 
5460 	default:
5461 		/* Unrecognized HBA response */
5462 		SATA_LOG_D((sata_hba_inst, CE_WARN,
5463 		    "sata_hba_start: unrecognized HBA response "
5464 		    "to cmd : 0x%2x resp 0x%x", cmd, rval));
5465 		spx->txlt_scsi_pkt->pkt_reason = CMD_TRAN_ERR;
5466 		*rval = TRAN_FATAL_ERROR;
5467 		break;
5468 	}
5469 
5470 	/*
5471 	 * If we got here, the packet was rejected.
5472 	 * Check if we need to remember reset state clearing request
5473 	 */
5474 	if (cmd_flags.sata_clear_dev_reset) {
5475 		/*
5476 		 * Check if device is still configured - it may have
5477 		 * disapeared from the configuration
5478 		 */
5479 		sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
5480 		if (sdinfo != NULL) {
5481 			/*
5482 			 * Restore the flag that requests clearing of
5483 			 * the device reset state,
5484 			 * so the next sata packet may carry it to HBA.
5485 			 */
5486 			sdinfo->satadrv_event_flags |=
5487 			    SATA_EVNT_CLEAR_DEVICE_RESET;
5488 		}
5489 	}
5490 	return (-1);
5491 }
5492 
5493 /*
5494  * Scsi response setup for invalid LBA
5495  *
5496  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
5497  */
5498 static int
5499 sata_txlt_lba_out_of_range(sata_pkt_txlate_t *spx)
5500 {
5501 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5502 	struct scsi_extended_sense *sense;
5503 
5504 	scsipkt->pkt_reason = CMD_CMPLT;
5505 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
5506 	    STATE_SENT_CMD | STATE_GOT_STATUS;
5507 	*scsipkt->pkt_scbp = STATUS_CHECK;
5508 
5509 	*scsipkt->pkt_scbp = STATUS_CHECK;
5510 	sense = sata_arq_sense(spx);
5511 	sense->es_key = KEY_ILLEGAL_REQUEST;
5512 	sense->es_add_code = SD_SCSI_ASC_LBA_OUT_OF_RANGE;
5513 
5514 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5515 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
5516 
5517 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
5518 	    scsipkt->pkt_comp != NULL)
5519 		/* scsi callback required */
5520 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
5521 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
5522 		    TQ_SLEEP) == NULL)
5523 			/* Scheduling the callback failed */
5524 			return (TRAN_BUSY);
5525 	return (TRAN_ACCEPT);
5526 }
5527 
5528 
5529 /*
5530  * Analyze device status and error registers and translate them into
5531  * appropriate scsi sense codes.
5532  * NOTE: non-packet commands only for now
5533  */
5534 static void
5535 sata_decode_device_error(sata_pkt_txlate_t *spx,
5536     struct scsi_extended_sense *sense)
5537 {
5538 	uint8_t err_reg = spx->txlt_sata_pkt->satapkt_cmd.satacmd_error_reg;
5539 
5540 	ASSERT(sense != NULL);
5541 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_status_reg &
5542 	    SATA_STATUS_ERR);
5543 
5544 
5545 	if (err_reg & SATA_ERROR_ICRC) {
5546 		sense->es_key = KEY_ABORTED_COMMAND;
5547 		sense->es_add_code = 0x08; /* Communication failure */
5548 		return;
5549 	}
5550 
5551 	if (err_reg & SATA_ERROR_UNC) {
5552 		sense->es_key = KEY_MEDIUM_ERROR;
5553 		/* Information bytes (LBA) need to be set by a caller */
5554 		return;
5555 	}
5556 
5557 	/* ADD HERE: MC error bit handling for ATAPI CD/DVD */
5558 	if (err_reg & (SATA_ERROR_MCR | SATA_ERROR_NM)) {
5559 		sense->es_key = KEY_UNIT_ATTENTION;
5560 		sense->es_add_code = 0x3a; /* No media present */
5561 		return;
5562 	}
5563 
5564 	if (err_reg & SATA_ERROR_IDNF) {
5565 		if (err_reg & SATA_ERROR_ABORT) {
5566 			sense->es_key = KEY_ABORTED_COMMAND;
5567 		} else {
5568 			sense->es_key = KEY_ILLEGAL_REQUEST;
5569 			sense->es_add_code = 0x21; /* LBA out of range */
5570 		}
5571 		return;
5572 	}
5573 
5574 	if (err_reg & SATA_ERROR_ABORT) {
5575 		ASSERT(spx->txlt_sata_pkt != NULL);
5576 		sense->es_key = KEY_ABORTED_COMMAND;
5577 		return;
5578 	}
5579 }
5580 
5581 /*
5582  * Extract error LBA from sata_pkt.satapkt_cmd register fields
5583  */
5584 static void
5585 sata_extract_error_lba(sata_pkt_txlate_t *spx, uint64_t *lba)
5586 {
5587 	sata_cmd_t *sata_cmd = &spx->txlt_sata_pkt->satapkt_cmd;
5588 
5589 	*lba = 0;
5590 	if (sata_cmd->satacmd_addr_type == ATA_ADDR_LBA48) {
5591 		*lba = sata_cmd->satacmd_lba_high_msb;
5592 		*lba = (*lba << 8) | sata_cmd->satacmd_lba_mid_msb;
5593 		*lba = (*lba << 8) | sata_cmd->satacmd_lba_low_msb;
5594 	} else if (sata_cmd->satacmd_addr_type == ATA_ADDR_LBA28) {
5595 		*lba = sata_cmd->satacmd_device_reg & 0xf;
5596 	}
5597 	*lba = (*lba << 8) | sata_cmd->satacmd_lba_high_lsb;
5598 	*lba = (*lba << 8) | sata_cmd->satacmd_lba_mid_lsb;
5599 	*lba = (*lba << 8) | sata_cmd->satacmd_lba_low_lsb;
5600 }
5601 
5602 /*
5603  * This is fixed sense format - if LBA exceeds the info field size,
5604  * no valid info will be returned (valid bit in extended sense will
5605  * be set to 0).
5606  */
5607 static struct scsi_extended_sense *
5608 sata_arq_sense(sata_pkt_txlate_t *spx)
5609 {
5610 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5611 	struct scsi_arq_status *arqs;
5612 	struct scsi_extended_sense *sense;
5613 
5614 	/* Fill ARQ sense data */
5615 	scsipkt->pkt_state |= STATE_ARQ_DONE;
5616 	arqs = (struct scsi_arq_status *)scsipkt->pkt_scbp;
5617 	*(uchar_t *)&arqs->sts_status = STATUS_CHECK;
5618 	*(uchar_t *)&arqs->sts_rqpkt_status = STATUS_GOOD;
5619 	arqs->sts_rqpkt_reason = CMD_CMPLT;
5620 	arqs->sts_rqpkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
5621 	    STATE_XFERRED_DATA | STATE_SENT_CMD | STATE_GOT_STATUS;
5622 	arqs->sts_rqpkt_resid = 0;
5623 	sense = &arqs->sts_sensedata;
5624 	bzero(sense, sizeof (struct scsi_extended_sense));
5625 	sata_fixed_sense_data_preset(sense);
5626 	return (sense);
5627 }
5628 
5629 
5630 /*
5631  * Emulated SATA Read/Write command completion for zero-length requests.
5632  * This request always succedes, so in synchronous mode it always returns
5633  * TRAN_ACCEPT, and in non-synchronous mode it may return TRAN_BUSY if the
5634  * callback cannot be scheduled.
5635  */
5636 static int
5637 sata_emul_rw_completion(sata_pkt_txlate_t *spx)
5638 {
5639 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5640 
5641 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
5642 	    STATE_SENT_CMD | STATE_GOT_STATUS;
5643 	scsipkt->pkt_reason = CMD_CMPLT;
5644 	*scsipkt->pkt_scbp = STATUS_GOOD;
5645 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
5646 		/* scsi callback required - have to schedule it */
5647 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
5648 		    (task_func_t *)scsipkt->pkt_comp,
5649 		    (void *)scsipkt, TQ_SLEEP) == NULL)
5650 			/* Scheduling the callback failed */
5651 			return (TRAN_BUSY);
5652 	}
5653 	return (TRAN_ACCEPT);
5654 }
5655 
5656 
5657 /*
5658  * Translate completion status of SATA read/write commands into scsi response.
5659  * pkt completion_reason is checked to determine the completion status.
5660  * Do scsi callback if necessary.
5661  *
5662  * Note: this function may be called also for synchronously executed
5663  * commands.
5664  * This function may be used only if scsi_pkt is non-NULL.
5665  */
5666 static void
5667 sata_txlt_rw_completion(sata_pkt_t *sata_pkt)
5668 {
5669 	sata_pkt_txlate_t *spx =
5670 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
5671 	sata_cmd_t *scmd = &sata_pkt->satapkt_cmd;
5672 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5673 	struct scsi_extended_sense *sense;
5674 	uint64_t lba;
5675 	struct buf *bp;
5676 	int rval;
5677 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
5678 		/* Normal completion */
5679 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
5680 		    STATE_SENT_CMD | STATE_XFERRED_DATA | STATE_GOT_STATUS;
5681 		scsipkt->pkt_reason = CMD_CMPLT;
5682 		*scsipkt->pkt_scbp = STATUS_GOOD;
5683 		if (spx->txlt_tmp_buf != NULL) {
5684 			/* Temporary buffer was used */
5685 			bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
5686 			if (bp->b_flags & B_READ) {
5687 				rval = ddi_dma_sync(
5688 				    spx->txlt_buf_dma_handle, 0, 0,
5689 				    DDI_DMA_SYNC_FORCPU);
5690 				ASSERT(rval == DDI_SUCCESS);
5691 				bcopy(spx->txlt_tmp_buf, bp->b_un.b_addr,
5692 				    bp->b_bcount);
5693 			}
5694 		}
5695 	} else {
5696 		/*
5697 		 * Something went wrong - analyze return
5698 		 */
5699 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
5700 		    STATE_SENT_CMD | STATE_GOT_STATUS;
5701 		scsipkt->pkt_reason = CMD_INCOMPLETE;
5702 		*scsipkt->pkt_scbp = STATUS_CHECK;
5703 		sense = sata_arq_sense(spx);
5704 		ASSERT(sense != NULL);
5705 
5706 		/*
5707 		 * SATA_PKT_DEV_ERROR is the only case where we may be able to
5708 		 * extract from device registers the failing LBA.
5709 		 */
5710 		if (sata_pkt->satapkt_reason == SATA_PKT_DEV_ERROR) {
5711 			if ((scmd->satacmd_addr_type == ATA_ADDR_LBA48) &&
5712 			    (scmd->satacmd_lba_mid_msb != 0 ||
5713 			    scmd->satacmd_lba_high_msb != 0)) {
5714 				/*
5715 				 * We have problem reporting this cmd LBA
5716 				 * in fixed sense data format, because of
5717 				 * the size of the scsi LBA fields.
5718 				 */
5719 				sense->es_valid = 0;
5720 			} else {
5721 				sata_extract_error_lba(spx, &lba);
5722 				sense->es_info_1 = (lba & 0xFF000000) >> 24;
5723 				sense->es_info_2 = (lba & 0xFF0000) >> 16;
5724 				sense->es_info_3 = (lba & 0xFF00) >> 8;
5725 				sense->es_info_4 = lba & 0xFF;
5726 			}
5727 		} else {
5728 			/* Invalid extended sense info */
5729 			sense->es_valid = 0;
5730 		}
5731 
5732 		switch (sata_pkt->satapkt_reason) {
5733 		case SATA_PKT_PORT_ERROR:
5734 			/* We may want to handle DEV GONE state as well */
5735 			/*
5736 			 * We have no device data. Assume no data transfered.
5737 			 */
5738 			sense->es_key = KEY_HARDWARE_ERROR;
5739 			break;
5740 
5741 		case SATA_PKT_DEV_ERROR:
5742 			if (sata_pkt->satapkt_cmd.satacmd_status_reg &
5743 			    SATA_STATUS_ERR) {
5744 				/*
5745 				 * determine dev error reason from error
5746 				 * reg content
5747 				 */
5748 				sata_decode_device_error(spx, sense);
5749 				if (sense->es_key == KEY_MEDIUM_ERROR) {
5750 					switch (scmd->satacmd_cmd_reg) {
5751 					case SATAC_READ_DMA:
5752 					case SATAC_READ_DMA_EXT:
5753 					case SATAC_READ_DMA_QUEUED:
5754 					case SATAC_READ_DMA_QUEUED_EXT:
5755 					case SATAC_READ_FPDMA_QUEUED:
5756 						/* Unrecovered read error */
5757 						sense->es_add_code =
5758 						    SD_SCSI_ASC_UNREC_READ_ERR;
5759 						break;
5760 					case SATAC_WRITE_DMA:
5761 					case SATAC_WRITE_DMA_EXT:
5762 					case SATAC_WRITE_DMA_QUEUED:
5763 					case SATAC_WRITE_DMA_QUEUED_EXT:
5764 					case SATAC_WRITE_FPDMA_QUEUED:
5765 						/* Write error */
5766 						sense->es_add_code =
5767 						    SD_SCSI_ASC_WRITE_ERR;
5768 						break;
5769 					default:
5770 						/* Internal error */
5771 						SATA_LOG_D((
5772 						    spx->txlt_sata_hba_inst,
5773 						    CE_WARN,
5774 						    "sata_txlt_rw_completion :"
5775 						    "internal error - invalid "
5776 						    "command 0x%2x",
5777 						    scmd->satacmd_cmd_reg));
5778 						break;
5779 					}
5780 				}
5781 				break;
5782 			}
5783 			/* No extended sense key - no info available */
5784 			scsipkt->pkt_reason = CMD_INCOMPLETE;
5785 			break;
5786 
5787 		case SATA_PKT_TIMEOUT:
5788 			scsipkt->pkt_reason = CMD_TIMEOUT;
5789 			scsipkt->pkt_statistics |=
5790 			    STAT_TIMEOUT | STAT_DEV_RESET;
5791 			sense->es_key = KEY_ABORTED_COMMAND;
5792 			break;
5793 
5794 		case SATA_PKT_ABORTED:
5795 			scsipkt->pkt_reason = CMD_ABORTED;
5796 			scsipkt->pkt_statistics |= STAT_ABORTED;
5797 			sense->es_key = KEY_ABORTED_COMMAND;
5798 			break;
5799 
5800 		case SATA_PKT_RESET:
5801 			scsipkt->pkt_reason = CMD_RESET;
5802 			scsipkt->pkt_statistics |= STAT_DEV_RESET;
5803 			sense->es_key = KEY_ABORTED_COMMAND;
5804 			break;
5805 
5806 		default:
5807 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
5808 			    "sata_txlt_rw_completion: "
5809 			    "invalid packet completion reason"));
5810 			scsipkt->pkt_reason = CMD_TRAN_ERR;
5811 			break;
5812 		}
5813 	}
5814 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5815 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
5816 
5817 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
5818 		/* scsi callback required */
5819 		scsi_hba_pkt_comp(scsipkt);
5820 }
5821 
5822 
5823 /*
5824  * Translate completion status of non-data commands (i.e. commands returning
5825  * no data).
5826  * pkt completion_reason is checked to determine the completion status.
5827  * Do scsi callback if necessary (FLAG_NOINTR == 0)
5828  *
5829  * Note: this function may be called also for synchronously executed
5830  * commands.
5831  * This function may be used only if scsi_pkt is non-NULL.
5832  */
5833 
5834 static 	void
5835 sata_txlt_nodata_cmd_completion(sata_pkt_t *sata_pkt)
5836 {
5837 	sata_pkt_txlate_t *spx =
5838 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
5839 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5840 	struct scsi_extended_sense *sense;
5841 
5842 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
5843 	    STATE_SENT_CMD | STATE_GOT_STATUS;
5844 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
5845 		/* Normal completion */
5846 		scsipkt->pkt_reason = CMD_CMPLT;
5847 		*scsipkt->pkt_scbp = STATUS_GOOD;
5848 	} else {
5849 		/* Something went wrong */
5850 		scsipkt->pkt_reason = CMD_INCOMPLETE;
5851 		*scsipkt->pkt_scbp = STATUS_CHECK;
5852 		sense = sata_arq_sense(spx);
5853 		switch (sata_pkt->satapkt_reason) {
5854 		case SATA_PKT_PORT_ERROR:
5855 			/*
5856 			 * We have no device data. Assume no data transfered.
5857 			 */
5858 			sense->es_key = KEY_HARDWARE_ERROR;
5859 			break;
5860 
5861 		case SATA_PKT_DEV_ERROR:
5862 			if (sata_pkt->satapkt_cmd.satacmd_status_reg &
5863 			    SATA_STATUS_ERR) {
5864 				/*
5865 				 * determine dev error reason from error
5866 				 * reg content
5867 				 */
5868 				sata_decode_device_error(spx, sense);
5869 				break;
5870 			}
5871 			/* No extended sense key - no info available */
5872 			break;
5873 
5874 		case SATA_PKT_TIMEOUT:
5875 			scsipkt->pkt_reason = CMD_TIMEOUT;
5876 			scsipkt->pkt_statistics |=
5877 			    STAT_TIMEOUT | STAT_DEV_RESET;
5878 			/* No extended sense key ? */
5879 			break;
5880 
5881 		case SATA_PKT_ABORTED:
5882 			scsipkt->pkt_reason = CMD_ABORTED;
5883 			scsipkt->pkt_statistics |= STAT_ABORTED;
5884 			/* No extended sense key ? */
5885 			break;
5886 
5887 		case SATA_PKT_RESET:
5888 			/* pkt aborted by an explicit reset from a host */
5889 			scsipkt->pkt_reason = CMD_RESET;
5890 			scsipkt->pkt_statistics |= STAT_DEV_RESET;
5891 			break;
5892 
5893 		default:
5894 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
5895 			    "sata_txlt_nodata_cmd_completion: "
5896 			    "invalid packet completion reason %d",
5897 			    sata_pkt->satapkt_reason));
5898 			scsipkt->pkt_reason = CMD_TRAN_ERR;
5899 			break;
5900 		}
5901 
5902 	}
5903 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5904 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
5905 
5906 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
5907 		/* scsi callback required */
5908 		scsi_hba_pkt_comp(scsipkt);
5909 }
5910 
5911 
5912 /*
5913  * Build Mode sense R/W recovery page
5914  * NOT IMPLEMENTED
5915  */
5916 
5917 static int
5918 sata_build_msense_page_1(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
5919 {
5920 #ifndef __lock_lint
5921 	_NOTE(ARGUNUSED(sdinfo))
5922 	_NOTE(ARGUNUSED(pcntrl))
5923 	_NOTE(ARGUNUSED(buf))
5924 #endif
5925 	return (0);
5926 }
5927 
5928 /*
5929  * Build Mode sense caching page  -  scsi-3 implementation.
5930  * Page length distinguishes previous format from scsi-3 format.
5931  * buf must have space for 0x12 bytes.
5932  * Only DRA (disable read ahead ) and WCE (write cache enable) are changeable.
5933  *
5934  */
5935 static int
5936 sata_build_msense_page_8(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
5937 {
5938 	struct mode_cache_scsi3 *page = (struct mode_cache_scsi3 *)buf;
5939 	sata_id_t *sata_id = &sdinfo->satadrv_id;
5940 
5941 	/*
5942 	 * Most of the fields are set to 0, being not supported and/or disabled
5943 	 */
5944 	bzero(buf, PAGELENGTH_DAD_MODE_CACHE_SCSI3);
5945 
5946 	/* Saved paramters not supported */
5947 	if (pcntrl == 3)
5948 		return (0);
5949 	if (pcntrl == 0 || pcntrl == 2) {
5950 		/*
5951 		 * For now treat current and default parameters as same
5952 		 * That may have to change, if target driver will complain
5953 		 */
5954 		page->mode_page.code = MODEPAGE_CACHING;	/* PS = 0 */
5955 		page->mode_page.length = PAGELENGTH_DAD_MODE_CACHE_SCSI3;
5956 
5957 		if (SATA_READ_AHEAD_SUPPORTED(*sata_id) &&
5958 		    !SATA_READ_AHEAD_ENABLED(*sata_id)) {
5959 			page->dra = 1;		/* Read Ahead disabled */
5960 			page->rcd = 1;		/* Read Cache disabled */
5961 		}
5962 		if (SATA_WRITE_CACHE_SUPPORTED(*sata_id) &&
5963 		    SATA_WRITE_CACHE_ENABLED(*sata_id))
5964 			page->wce = 1;		/* Write Cache enabled */
5965 	} else {
5966 		/* Changeable parameters */
5967 		page->mode_page.code = MODEPAGE_CACHING;
5968 		page->mode_page.length = PAGELENGTH_DAD_MODE_CACHE_SCSI3;
5969 		if (SATA_READ_AHEAD_SUPPORTED(*sata_id)) {
5970 			page->dra = 1;
5971 			page->rcd = 1;
5972 		}
5973 		if (SATA_WRITE_CACHE_SUPPORTED(*sata_id))
5974 			page->wce = 1;
5975 	}
5976 	return (PAGELENGTH_DAD_MODE_CACHE_SCSI3 +
5977 	    sizeof (struct mode_page));
5978 }
5979 
5980 /*
5981  * Build Mode sense exception cntrl page
5982  */
5983 static int
5984 sata_build_msense_page_1c(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
5985 {
5986 	struct mode_info_excpt_page *page = (struct mode_info_excpt_page *)buf;
5987 	sata_id_t *sata_id = &sdinfo->satadrv_id;
5988 
5989 	/*
5990 	 * Most of the fields are set to 0, being not supported and/or disabled
5991 	 */
5992 	bzero(buf, PAGELENGTH_INFO_EXCPT);
5993 
5994 	page->mode_page.code = MODEPAGE_INFO_EXCPT;
5995 	page->mode_page.length = PAGELENGTH_INFO_EXCPT;
5996 
5997 	/* Indicate that this is page is saveable */
5998 	page->mode_page.ps = 1;
5999 
6000 	/*
6001 	 * We will return the same data for default, current and saved page.
6002 	 * The only changeable bit is dexcpt and that bit is required
6003 	 * by the ATA specification to be preserved across power cycles.
6004 	 */
6005 	if (pcntrl != 1) {
6006 		page->dexcpt = !(sata_id->ai_features85 & SATA_SMART_SUPPORTED);
6007 		page->mrie = MRIE_ONLY_ON_REQUEST;
6008 	}
6009 	else
6010 		page->dexcpt = 1;	/* Only changeable parameter */
6011 
6012 	return (PAGELENGTH_INFO_EXCPT + sizeof (struct mode_info_excpt_page));
6013 }
6014 
6015 
6016 static int
6017 sata_build_msense_page_30(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
6018 {
6019 	struct mode_acoustic_management *page =
6020 	    (struct mode_acoustic_management *)buf;
6021 	sata_id_t *sata_id = &sdinfo->satadrv_id;
6022 
6023 	/*
6024 	 * Most of the fields are set to 0, being not supported and/or disabled
6025 	 */
6026 	bzero(buf, PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT);
6027 
6028 	switch (pcntrl) {
6029 	case P_CNTRL_DEFAULT:
6030 		/*  default paramters not supported */
6031 		return (0);
6032 
6033 	case P_CNTRL_CURRENT:
6034 	case P_CNTRL_SAVED:
6035 		/* Saved and current are supported and are identical */
6036 		page->mode_page.code = MODEPAGE_ACOUSTIC_MANAG;
6037 		page->mode_page.length =
6038 		    PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT;
6039 		page->mode_page.ps = 1;
6040 
6041 		/* Word 83 indicates if feature is supported */
6042 		/* If feature is not supported */
6043 		if (!(sata_id->ai_cmdset83 & SATA_ACOUSTIC_MGMT)) {
6044 			page->acoustic_manag_enable =
6045 			    ACOUSTIC_DISABLED;
6046 		} else {
6047 			page->acoustic_manag_enable =
6048 			    ((sata_id->ai_features86 & SATA_ACOUSTIC_MGMT)
6049 			    != 0);
6050 			/* Word 94 inidicates the value */
6051 #ifdef	_LITTLE_ENDIAN
6052 			page->acoustic_manag_level =
6053 			    (uchar_t)sata_id->ai_acoustic;
6054 			page->vendor_recommended_value =
6055 			    sata_id->ai_acoustic >> 8;
6056 #else
6057 			page->acoustic_manag_level =
6058 			    sata_id->ai_acoustic >> 8;
6059 			page->vendor_recommended_value =
6060 			    (uchar_t)sata_id->ai_acoustic;
6061 #endif
6062 		}
6063 		break;
6064 
6065 	case P_CNTRL_CHANGEABLE:
6066 		page->mode_page.code = MODEPAGE_ACOUSTIC_MANAG;
6067 		page->mode_page.length =
6068 		    PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT;
6069 		page->mode_page.ps = 1;
6070 
6071 		/* Word 83 indicates if the feature is supported */
6072 		if (sata_id->ai_cmdset83 & SATA_ACOUSTIC_MGMT) {
6073 			page->acoustic_manag_enable =
6074 			    ACOUSTIC_ENABLED;
6075 			page->acoustic_manag_level = 0xff;
6076 		}
6077 		break;
6078 	}
6079 	return (PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT +
6080 	    sizeof (struct mode_page));
6081 }
6082 
6083 
6084 /*
6085  * Build Mode sense power condition page
6086  * NOT IMPLEMENTED.
6087  */
6088 static int
6089 sata_build_msense_page_1a(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
6090 {
6091 #ifndef __lock_lint
6092 	_NOTE(ARGUNUSED(sdinfo))
6093 	_NOTE(ARGUNUSED(pcntrl))
6094 	_NOTE(ARGUNUSED(buf))
6095 #endif
6096 	return (0);
6097 }
6098 
6099 
6100 /*
6101  * Process mode select caching page 8 (scsi3 format only).
6102  * Read Ahead (same as read cache) and Write Cache may be turned on and off
6103  * if these features are supported by the device. If these features are not
6104  * supported, quietly ignore them.
6105  * This function fails only if the SET FEATURE command sent to
6106  * the device fails. The page format is not varified, assuming that the
6107  * target driver operates correctly - if parameters length is too short,
6108  * we just drop the page.
6109  * Two command may be sent if both Read Cache/Read Ahead and Write Cache
6110  * setting have to be changed.
6111  * SET FEATURE command is executed synchronously, i.e. we wait here until
6112  * it is completed, regardless of the scsi pkt directives.
6113  *
6114  * Note: Mode Select Caching page RCD and DRA bits are tied together, i.e.
6115  * changing DRA will change RCD.
6116  *
6117  * More than one SATA command may be executed to perform operations specified
6118  * by mode select pages. The first error terminates further execution.
6119  * Operations performed successully are not backed-up in such case.
6120  *
6121  * Return SATA_SUCCESS if operation succeeded, SATA_FAILURE otherwise.
6122  * If operation resulted in changing device setup, dmod flag should be set to
6123  * one (1). If parameters were not changed, dmod flag should be set to 0.
6124  * Upon return, if operation required sending command to the device, the rval
6125  * should be set to the value returned by sata_hba_start. If operation
6126  * did not require device access, rval should be set to TRAN_ACCEPT.
6127  * The pagelen should be set to the length of the page.
6128  *
6129  * This function has to be called with a port mutex held.
6130  *
6131  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
6132  */
6133 int
6134 sata_mode_select_page_8(sata_pkt_txlate_t *spx, struct mode_cache_scsi3 *page,
6135     int parmlen, int *pagelen, int *rval, int *dmod)
6136 {
6137 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6138 	sata_drive_info_t *sdinfo;
6139 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
6140 	sata_id_t *sata_id;
6141 	struct scsi_extended_sense *sense;
6142 	int wce, dra;	/* Current settings */
6143 
6144 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
6145 	    &spx->txlt_sata_pkt->satapkt_device);
6146 	sata_id = &sdinfo->satadrv_id;
6147 	*dmod = 0;
6148 
6149 	/* Verify parameters length. If too short, drop it */
6150 	if (PAGELENGTH_DAD_MODE_CACHE_SCSI3 +
6151 	    sizeof (struct mode_page) < parmlen) {
6152 		*scsipkt->pkt_scbp = STATUS_CHECK;
6153 		sense = sata_arq_sense(spx);
6154 		sense->es_key = KEY_ILLEGAL_REQUEST;
6155 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
6156 		*pagelen = parmlen;
6157 		*rval = TRAN_ACCEPT;
6158 		return (SATA_FAILURE);
6159 	}
6160 
6161 	*pagelen = PAGELENGTH_DAD_MODE_CACHE_SCSI3 + sizeof (struct mode_page);
6162 
6163 	/*
6164 	 * We can manipulate only write cache and read ahead
6165 	 * (read cache) setting.
6166 	 */
6167 	if (!SATA_READ_AHEAD_SUPPORTED(*sata_id) &&
6168 	    !SATA_WRITE_CACHE_SUPPORTED(*sata_id)) {
6169 		/*
6170 		 * None of the features is supported - ignore
6171 		 */
6172 		*rval = TRAN_ACCEPT;
6173 		return (SATA_SUCCESS);
6174 	}
6175 
6176 	/* Current setting of Read Ahead (and Read Cache) */
6177 	if (SATA_READ_AHEAD_ENABLED(*sata_id))
6178 		dra = 0;	/* 0 == not disabled */
6179 	else
6180 		dra = 1;
6181 	/* Current setting of Write Cache */
6182 	if (SATA_WRITE_CACHE_ENABLED(*sata_id))
6183 		wce = 1;
6184 	else
6185 		wce = 0;
6186 
6187 	if (page->dra == dra && page->wce == wce && page->rcd == dra) {
6188 		/* nothing to do */
6189 		*rval = TRAN_ACCEPT;
6190 		return (SATA_SUCCESS);
6191 	}
6192 
6193 	/*
6194 	 * Need to flip some setting
6195 	 * Set-up Internal SET FEATURES command(s)
6196 	 */
6197 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
6198 	scmd->satacmd_addr_type = 0;
6199 	scmd->satacmd_device_reg = 0;
6200 	scmd->satacmd_status_reg = 0;
6201 	scmd->satacmd_error_reg = 0;
6202 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
6203 	if (page->dra != dra || page->rcd != dra) {
6204 		/* Need to flip read ahead setting */
6205 		if (dra == 0)
6206 			/* Disable read ahead / read cache */
6207 			scmd->satacmd_features_reg =
6208 			    SATAC_SF_DISABLE_READ_AHEAD;
6209 		else
6210 			/* Enable read ahead  / read cache */
6211 			scmd->satacmd_features_reg =
6212 			    SATAC_SF_ENABLE_READ_AHEAD;
6213 
6214 		/* Transfer command to HBA */
6215 		if (sata_hba_start(spx, rval) != 0)
6216 			/*
6217 			 * Pkt not accepted for execution.
6218 			 */
6219 			return (SATA_FAILURE);
6220 
6221 		*dmod = 1;
6222 
6223 		/* Now process return */
6224 		if (spx->txlt_sata_pkt->satapkt_reason !=
6225 		    SATA_PKT_COMPLETED) {
6226 			goto failure;	/* Terminate */
6227 		}
6228 	}
6229 
6230 	/* Note that the packet is not removed, so it could be re-used */
6231 	if (page->wce != wce) {
6232 		/* Need to flip Write Cache setting */
6233 		if (page->wce == 1)
6234 			/* Enable write cache */
6235 			scmd->satacmd_features_reg =
6236 			    SATAC_SF_ENABLE_WRITE_CACHE;
6237 		else
6238 			/* Disable write cache */
6239 			scmd->satacmd_features_reg =
6240 			    SATAC_SF_DISABLE_WRITE_CACHE;
6241 
6242 		/* Transfer command to HBA */
6243 		if (sata_hba_start(spx, rval) != 0)
6244 			/*
6245 			 * Pkt not accepted for execution.
6246 			 */
6247 			return (SATA_FAILURE);
6248 
6249 		*dmod = 1;
6250 
6251 		/* Now process return */
6252 		if (spx->txlt_sata_pkt->satapkt_reason !=
6253 		    SATA_PKT_COMPLETED) {
6254 			goto failure;
6255 		}
6256 	}
6257 	return (SATA_SUCCESS);
6258 
6259 failure:
6260 	sata_xlate_errors(spx);
6261 
6262 	return (SATA_FAILURE);
6263 }
6264 
6265 /*
6266  * Process mode select informational exceptions control page 0x1c
6267  *
6268  * The only changeable bit is dexcpt (disable exceptions).
6269  * MRIE (method of reporting informational exceptions) must be
6270  * "only on request".
6271  * This page applies to informational exceptions that report
6272  * additional sense codes with the ADDITIONAL SENSE CODE field set to 5Dh
6273  * (e.g.,FAILURE PREDICTION THRESHOLD EXCEEDED) or 0Bh (e.g., WARNING_).
6274  * Informational exception conditions occur as the result of background scan
6275  * errors, background self-test errors, or vendor specific events within a
6276  * logical unit. An informational exception condition may occur asynchronous
6277  * to any commands.
6278  *
6279  * Returns: SATA_SUCCESS if operation succeeded, SATA_FAILURE otherwise.
6280  * If operation resulted in changing device setup, dmod flag should be set to
6281  * one (1). If parameters were not changed, dmod flag should be set to 0.
6282  * Upon return, if operation required sending command to the device, the rval
6283  * should be set to the value returned by sata_hba_start. If operation
6284  * did not require device access, rval should be set to TRAN_ACCEPT.
6285  * The pagelen should be set to the length of the page.
6286  *
6287  * This function has to be called with a port mutex held.
6288  *
6289  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
6290  *
6291  * Cannot be called in the interrupt context.
6292  */
6293 static	int
6294 sata_mode_select_page_1c(
6295 	sata_pkt_txlate_t *spx,
6296 	struct mode_info_excpt_page *page,
6297 	int parmlen,
6298 	int *pagelen,
6299 	int *rval,
6300 	int *dmod)
6301 {
6302 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6303 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
6304 	sata_drive_info_t *sdinfo;
6305 	sata_id_t *sata_id;
6306 	struct scsi_extended_sense *sense;
6307 
6308 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
6309 	    &spx->txlt_sata_pkt->satapkt_device);
6310 	sata_id = &sdinfo->satadrv_id;
6311 
6312 	*dmod = 0;
6313 
6314 	/* Verify parameters length. If too short, drop it */
6315 	if (((PAGELENGTH_INFO_EXCPT + sizeof (struct mode_page)) < parmlen) ||
6316 	    page->perf || page->test || (page->mrie != MRIE_ONLY_ON_REQUEST)) {
6317 		*scsipkt->pkt_scbp = STATUS_CHECK;
6318 		sense = sata_arq_sense(spx);
6319 		sense->es_key = KEY_ILLEGAL_REQUEST;
6320 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
6321 		*pagelen = parmlen;
6322 		*rval = TRAN_ACCEPT;
6323 		return (SATA_FAILURE);
6324 	}
6325 
6326 	*pagelen = PAGELENGTH_INFO_EXCPT + sizeof (struct mode_page);
6327 
6328 	if (! (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED)) {
6329 		*scsipkt->pkt_scbp = STATUS_CHECK;
6330 		sense = sata_arq_sense(spx);
6331 		sense->es_key = KEY_ILLEGAL_REQUEST;
6332 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
6333 		*pagelen = parmlen;
6334 		*rval = TRAN_ACCEPT;
6335 		return (SATA_FAILURE);
6336 	}
6337 
6338 	/* If already in the state requested, we are done */
6339 	if (page->dexcpt == ! (sata_id->ai_features85 & SATA_SMART_ENABLED)) {
6340 		/* nothing to do */
6341 		*rval = TRAN_ACCEPT;
6342 		return (SATA_SUCCESS);
6343 	}
6344 
6345 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
6346 
6347 	/* Build SMART_ENABLE or SMART_DISABLE command */
6348 	scmd->satacmd_addr_type = 0;		/* N/A */
6349 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
6350 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
6351 	scmd->satacmd_features_reg = page->dexcpt ?
6352 	    SATA_SMART_DISABLE_OPS : SATA_SMART_ENABLE_OPS;
6353 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
6354 	scmd->satacmd_cmd_reg = SATAC_SMART;
6355 
6356 	/* Transfer command to HBA */
6357 	if (sata_hba_start(spx, rval) != 0)
6358 		/*
6359 		 * Pkt not accepted for execution.
6360 		 */
6361 		return (SATA_FAILURE);
6362 
6363 	*dmod = 1;	/* At least may have been modified */
6364 
6365 	/* Now process return */
6366 	if (spx->txlt_sata_pkt->satapkt_reason == SATA_PKT_COMPLETED)
6367 		return (SATA_SUCCESS);
6368 
6369 	/* Packet did not complete successfully */
6370 	sata_xlate_errors(spx);
6371 
6372 	return (SATA_FAILURE);
6373 }
6374 
6375 /*
6376  * Process mode select acoustic management control page 0x30
6377  *
6378  *
6379  * This function has to be called with a port mutex held.
6380  *
6381  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
6382  *
6383  * Cannot be called in the interrupt context.
6384  */
6385 int
6386 sata_mode_select_page_30(sata_pkt_txlate_t *spx, struct
6387     mode_acoustic_management *page, int parmlen, int *pagelen,
6388     int *rval, int *dmod)
6389 {
6390 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6391 	sata_drive_info_t *sdinfo;
6392 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
6393 	sata_id_t *sata_id;
6394 	struct scsi_extended_sense *sense;
6395 
6396 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
6397 	    &spx->txlt_sata_pkt->satapkt_device);
6398 	sata_id = &sdinfo->satadrv_id;
6399 	*dmod = 0;
6400 
6401 	/* If parmlen is too short or the feature is not supported, drop it */
6402 	if (((PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT +
6403 	    sizeof (struct mode_page)) < parmlen) ||
6404 	    (! (sata_id->ai_cmdset83 & SATA_ACOUSTIC_MGMT))) {
6405 		*scsipkt->pkt_scbp = STATUS_CHECK;
6406 		sense = sata_arq_sense(spx);
6407 		sense->es_key = KEY_ILLEGAL_REQUEST;
6408 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
6409 		*pagelen = parmlen;
6410 		*rval = TRAN_ACCEPT;
6411 		return (SATA_FAILURE);
6412 	}
6413 
6414 	*pagelen = PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT +
6415 	    sizeof (struct mode_page);
6416 
6417 	/*
6418 	 * We can enable and disable acoustice management and
6419 	 * set the acoustic management level.
6420 	 */
6421 
6422 	/*
6423 	 * Set-up Internal SET FEATURES command(s)
6424 	 */
6425 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
6426 	scmd->satacmd_addr_type = 0;
6427 	scmd->satacmd_device_reg = 0;
6428 	scmd->satacmd_status_reg = 0;
6429 	scmd->satacmd_error_reg = 0;
6430 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
6431 	if (page->acoustic_manag_enable) {
6432 		scmd->satacmd_features_reg = SATAC_SF_ENABLE_ACOUSTIC;
6433 		scmd->satacmd_sec_count_lsb = page->acoustic_manag_level;
6434 	} else {	/* disabling acoustic management */
6435 		scmd->satacmd_features_reg = SATAC_SF_DISABLE_ACOUSTIC;
6436 	}
6437 
6438 	/* Transfer command to HBA */
6439 	if (sata_hba_start(spx, rval) != 0)
6440 		/*
6441 		 * Pkt not accepted for execution.
6442 		 */
6443 		return (SATA_FAILURE);
6444 
6445 	/* Now process return */
6446 	if (spx->txlt_sata_pkt->satapkt_reason != SATA_PKT_COMPLETED) {
6447 		sata_xlate_errors(spx);
6448 		return (SATA_FAILURE);
6449 	}
6450 
6451 	*dmod = 1;
6452 
6453 	return (SATA_SUCCESS);
6454 }
6455 
6456 
6457 
6458 
6459 /*
6460  * sata_build_lsense_page0() is used to create the
6461  * SCSI LOG SENSE page 0 (supported log pages)
6462  *
6463  * Currently supported pages are 0, 0x10, 0x2f and 0x30
6464  * (supported log pages, self-test results, informational exceptions
6465  *  and Sun vendor specific ATA SMART data).
6466  *
6467  * Takes a sata_drive_info t * and the address of a buffer
6468  * in which to create the page information.
6469  *
6470  * Returns the number of bytes valid in the buffer.
6471  */
6472 static	int
6473 sata_build_lsense_page_0(sata_drive_info_t *sdinfo, uint8_t *buf)
6474 {
6475 	struct log_parameter *lpp = (struct log_parameter *)buf;
6476 	uint8_t *page_ptr = (uint8_t *)lpp->param_values;
6477 	int num_pages_supported = 1; /* Always have GET_SUPPORTED_LOG_PAGES */
6478 	sata_id_t *sata_id = &sdinfo->satadrv_id;
6479 
6480 	lpp->param_code[0] = 0;
6481 	lpp->param_code[1] = 0;
6482 	lpp->param_ctrl_flags = LOG_CTRL_LP | LOG_CTRL_LBIN;
6483 	*page_ptr++ = PAGE_CODE_GET_SUPPORTED_LOG_PAGES;
6484 
6485 	if (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED) {
6486 		if (sata_id->ai_cmdset84 & SATA_SMART_SELF_TEST_SUPPORTED) {
6487 			*page_ptr++ = PAGE_CODE_SELF_TEST_RESULTS;
6488 			++num_pages_supported;
6489 		}
6490 		*page_ptr++ = PAGE_CODE_INFORMATION_EXCEPTIONS;
6491 		++num_pages_supported;
6492 		*page_ptr++ = PAGE_CODE_SMART_READ_DATA;
6493 		++num_pages_supported;
6494 	}
6495 
6496 	lpp->param_len = num_pages_supported;
6497 
6498 	return ((&lpp->param_values[0] - (uint8_t *)lpp) +
6499 	    num_pages_supported);
6500 }
6501 
6502 /*
6503  * sata_build_lsense_page_10() is used to create the
6504  * SCSI LOG SENSE page 0x10 (self-test results)
6505  *
6506  * Takes a sata_drive_info t * and the address of a buffer
6507  * in which to create the page information as well as a sata_hba_inst_t *.
6508  *
6509  * Returns the number of bytes valid in the buffer.
6510  *
6511  * Note: Self test and SMART data is accessible in device log pages.
6512  * The log pages can be accessed by SMART READ/WRITE LOG (up to 255 sectors
6513  * of data can be transferred by a single command), or by the General Purpose
6514  * Logging commands (GPL) READ LOG EXT and WRITE LOG EXT (up to 65,535 sectors
6515  * - approximately 33MB - can be transferred by a single command.
6516  * The SCT Command response (either error or command) is the same for both
6517  * the SMART and GPL methods of issuing commands.
6518  * This function uses READ LOG EXT command when drive supports LBA48, and
6519  * SMART READ command otherwise.
6520  *
6521  * Since above commands are executed in a synchronous mode, this function
6522  * should not be called in an interrupt context.
6523  */
6524 static	int
6525 sata_build_lsense_page_10(
6526 	sata_drive_info_t *sdinfo,
6527 	uint8_t *buf,
6528 	sata_hba_inst_t *sata_hba_inst)
6529 {
6530 	struct log_parameter *lpp = (struct log_parameter *)buf;
6531 	int rval;
6532 
6533 	if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48) {
6534 		struct smart_ext_selftest_log *ext_selftest_log;
6535 
6536 		ext_selftest_log = kmem_zalloc(
6537 		    sizeof (struct smart_ext_selftest_log), KM_SLEEP);
6538 
6539 		rval = sata_ext_smart_selftest_read_log(sata_hba_inst, sdinfo,
6540 		    ext_selftest_log, 0);
6541 		if (rval == 0) {
6542 			int index, start_index;
6543 			struct smart_ext_selftest_log_entry *entry;
6544 			static const struct smart_ext_selftest_log_entry empty =
6545 			    {0};
6546 			uint16_t block_num;
6547 			int count;
6548 			boolean_t only_one_block = B_FALSE;
6549 
6550 			index = ext_selftest_log->
6551 			    smart_ext_selftest_log_index[0];
6552 			index |= ext_selftest_log->
6553 			    smart_ext_selftest_log_index[1] << 8;
6554 			if (index == 0)
6555 				goto out;
6556 
6557 			--index;	/* Correct for 0 origin */
6558 			start_index = index;	/* remember where we started */
6559 			block_num = index / ENTRIES_PER_EXT_SELFTEST_LOG_BLK;
6560 			if (block_num != 0) {
6561 				rval = sata_ext_smart_selftest_read_log(
6562 				    sata_hba_inst, sdinfo, ext_selftest_log,
6563 				    block_num);
6564 				if (rval != 0)
6565 					goto out;
6566 			}
6567 			index %= ENTRIES_PER_EXT_SELFTEST_LOG_BLK;
6568 			entry =
6569 			    &ext_selftest_log->
6570 			    smart_ext_selftest_log_entries[index];
6571 
6572 			for (count = 1;
6573 			    count <= SCSI_ENTRIES_IN_LOG_SENSE_SELFTEST_RESULTS;
6574 			    ++count) {
6575 				uint8_t status;
6576 				uint8_t code;
6577 				uint8_t sense_key;
6578 				uint8_t add_sense_code;
6579 				uint8_t add_sense_code_qual;
6580 
6581 				/* If this is an unused entry, we are done */
6582 				if (bcmp(entry, &empty, sizeof (empty)) == 0) {
6583 					/* Broken firmware on some disks */
6584 					if (index + 1 ==
6585 					    ENTRIES_PER_EXT_SELFTEST_LOG_BLK) {
6586 						--entry;
6587 						--index;
6588 						if (bcmp(entry, &empty,
6589 						    sizeof (empty)) == 0)
6590 							goto out;
6591 					} else
6592 						goto out;
6593 				}
6594 
6595 				if (only_one_block &&
6596 				    start_index == index)
6597 					goto out;
6598 
6599 				lpp->param_code[0] = 0;
6600 				lpp->param_code[1] = count;
6601 				lpp->param_ctrl_flags =
6602 				    LOG_CTRL_LP | LOG_CTRL_LBIN;
6603 				lpp->param_len =
6604 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN;
6605 
6606 				status = entry->smart_ext_selftest_log_status;
6607 				status >>= 4;
6608 				switch (status) {
6609 				case 0:
6610 				default:
6611 					sense_key = KEY_NO_SENSE;
6612 					add_sense_code =
6613 					    SD_SCSI_ASC_NO_ADD_SENSE;
6614 					add_sense_code_qual = 0;
6615 					break;
6616 				case 1:
6617 					sense_key = KEY_ABORTED_COMMAND;
6618 					add_sense_code =
6619 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6620 					add_sense_code_qual = SCSI_COMPONENT_81;
6621 					break;
6622 				case 2:
6623 					sense_key = KEY_ABORTED_COMMAND;
6624 					add_sense_code =
6625 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6626 					add_sense_code_qual = SCSI_COMPONENT_82;
6627 					break;
6628 				case 3:
6629 					sense_key = KEY_ABORTED_COMMAND;
6630 					add_sense_code =
6631 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6632 					add_sense_code_qual = SCSI_COMPONENT_83;
6633 					break;
6634 				case 4:
6635 					sense_key = KEY_HARDWARE_ERROR;
6636 					add_sense_code =
6637 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6638 					add_sense_code_qual = SCSI_COMPONENT_84;
6639 					break;
6640 				case 5:
6641 					sense_key = KEY_HARDWARE_ERROR;
6642 					add_sense_code =
6643 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6644 					add_sense_code_qual = SCSI_COMPONENT_85;
6645 					break;
6646 				case 6:
6647 					sense_key = KEY_HARDWARE_ERROR;
6648 					add_sense_code =
6649 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6650 					add_sense_code_qual = SCSI_COMPONENT_86;
6651 					break;
6652 				case 7:
6653 					sense_key = KEY_MEDIUM_ERROR;
6654 					add_sense_code =
6655 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6656 					add_sense_code_qual = SCSI_COMPONENT_87;
6657 					break;
6658 				case 8:
6659 					sense_key = KEY_HARDWARE_ERROR;
6660 					add_sense_code =
6661 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6662 					add_sense_code_qual = SCSI_COMPONENT_88;
6663 					break;
6664 				}
6665 				code = 0;	/* unspecified */
6666 				status |= (code << 4);
6667 				lpp->param_values[0] = status;
6668 				lpp->param_values[1] = 0; /* unspecified */
6669 				lpp->param_values[2] = entry->
6670 				    smart_ext_selftest_log_timestamp[1];
6671 				lpp->param_values[3] = entry->
6672 				    smart_ext_selftest_log_timestamp[0];
6673 				if (status != 0) {
6674 					lpp->param_values[4] = 0;
6675 					lpp->param_values[5] = 0;
6676 					lpp->param_values[6] = entry->
6677 					    smart_ext_selftest_log_failing_lba
6678 					    [5];
6679 					lpp->param_values[7] = entry->
6680 					    smart_ext_selftest_log_failing_lba
6681 					    [4];
6682 					lpp->param_values[8] = entry->
6683 					    smart_ext_selftest_log_failing_lba
6684 					    [3];
6685 					lpp->param_values[9] = entry->
6686 					    smart_ext_selftest_log_failing_lba
6687 					    [2];
6688 					lpp->param_values[10] = entry->
6689 					    smart_ext_selftest_log_failing_lba
6690 					    [1];
6691 					lpp->param_values[11] = entry->
6692 					    smart_ext_selftest_log_failing_lba
6693 					    [0];
6694 				} else {	/* No bad block address */
6695 					lpp->param_values[4] = 0xff;
6696 					lpp->param_values[5] = 0xff;
6697 					lpp->param_values[6] = 0xff;
6698 					lpp->param_values[7] = 0xff;
6699 					lpp->param_values[8] = 0xff;
6700 					lpp->param_values[9] = 0xff;
6701 					lpp->param_values[10] = 0xff;
6702 					lpp->param_values[11] = 0xff;
6703 				}
6704 
6705 				lpp->param_values[12] = sense_key;
6706 				lpp->param_values[13] = add_sense_code;
6707 				lpp->param_values[14] = add_sense_code_qual;
6708 				lpp->param_values[15] = 0; /* undefined */
6709 
6710 				lpp = (struct log_parameter *)
6711 				    (((uint8_t *)lpp) +
6712 				    SCSI_LOG_PARAM_HDR_LEN +
6713 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN);
6714 
6715 				--index;	/* Back up to previous entry */
6716 				if (index < 0) {
6717 					if (block_num > 0) {
6718 						--block_num;
6719 					} else {
6720 						struct read_log_ext_directory
6721 						    logdir;
6722 
6723 						rval =
6724 						    sata_read_log_ext_directory(
6725 						    sata_hba_inst, sdinfo,
6726 						    &logdir);
6727 						if (rval == -1)
6728 							goto out;
6729 						if ((logdir.read_log_ext_vers
6730 						    [0] == 0) &&
6731 						    (logdir.read_log_ext_vers
6732 						    [1] == 0))
6733 							goto out;
6734 						block_num =
6735 						    logdir.read_log_ext_nblks
6736 						    [EXT_SMART_SELFTEST_LOG_PAGE
6737 						    - 1][0];
6738 						block_num |= logdir.
6739 						    read_log_ext_nblks
6740 						    [EXT_SMART_SELFTEST_LOG_PAGE
6741 						    - 1][1] << 8;
6742 						--block_num;
6743 						only_one_block =
6744 						    (block_num == 0);
6745 					}
6746 					rval = sata_ext_smart_selftest_read_log(
6747 					    sata_hba_inst, sdinfo,
6748 					    ext_selftest_log, block_num);
6749 					if (rval != 0)
6750 						goto out;
6751 
6752 					index =
6753 					    ENTRIES_PER_EXT_SELFTEST_LOG_BLK -
6754 					    1;
6755 				}
6756 				index %= ENTRIES_PER_EXT_SELFTEST_LOG_BLK;
6757 				entry = &ext_selftest_log->
6758 				    smart_ext_selftest_log_entries[index];
6759 			}
6760 		}
6761 out:
6762 		kmem_free(ext_selftest_log,
6763 		    sizeof (struct smart_ext_selftest_log));
6764 	} else {
6765 		struct smart_selftest_log *selftest_log;
6766 
6767 		selftest_log = kmem_zalloc(sizeof (struct smart_selftest_log),
6768 		    KM_SLEEP);
6769 
6770 		rval = sata_smart_selftest_log(sata_hba_inst, sdinfo,
6771 		    selftest_log);
6772 
6773 		if (rval == 0) {
6774 			int index;
6775 			int count;
6776 			struct smart_selftest_log_entry *entry;
6777 			static const struct smart_selftest_log_entry empty =
6778 			    { 0 };
6779 
6780 			index = selftest_log->smart_selftest_log_index;
6781 			if (index == 0)
6782 				goto done;
6783 			--index;	/* Correct for 0 origin */
6784 			entry = &selftest_log->
6785 			    smart_selftest_log_entries[index];
6786 			for (count = 1;
6787 			    count <= SCSI_ENTRIES_IN_LOG_SENSE_SELFTEST_RESULTS;
6788 			    ++count) {
6789 				uint8_t status;
6790 				uint8_t code;
6791 				uint8_t sense_key;
6792 				uint8_t add_sense_code;
6793 				uint8_t add_sense_code_qual;
6794 
6795 				if (bcmp(entry, &empty, sizeof (empty)) == 0)
6796 					goto done;
6797 
6798 				lpp->param_code[0] = 0;
6799 				lpp->param_code[1] = count;
6800 				lpp->param_ctrl_flags =
6801 				    LOG_CTRL_LP | LOG_CTRL_LBIN;
6802 				lpp->param_len =
6803 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN;
6804 
6805 				status = entry->smart_selftest_log_status;
6806 				status >>= 4;
6807 				switch (status) {
6808 				case 0:
6809 				default:
6810 					sense_key = KEY_NO_SENSE;
6811 					add_sense_code =
6812 					    SD_SCSI_ASC_NO_ADD_SENSE;
6813 					break;
6814 				case 1:
6815 					sense_key = KEY_ABORTED_COMMAND;
6816 					add_sense_code =
6817 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6818 					add_sense_code_qual = SCSI_COMPONENT_81;
6819 					break;
6820 				case 2:
6821 					sense_key = KEY_ABORTED_COMMAND;
6822 					add_sense_code =
6823 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6824 					add_sense_code_qual = SCSI_COMPONENT_82;
6825 					break;
6826 				case 3:
6827 					sense_key = KEY_ABORTED_COMMAND;
6828 					add_sense_code =
6829 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6830 					add_sense_code_qual = SCSI_COMPONENT_83;
6831 					break;
6832 				case 4:
6833 					sense_key = KEY_HARDWARE_ERROR;
6834 					add_sense_code =
6835 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6836 					add_sense_code_qual = SCSI_COMPONENT_84;
6837 					break;
6838 				case 5:
6839 					sense_key = KEY_HARDWARE_ERROR;
6840 					add_sense_code =
6841 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6842 					add_sense_code_qual = SCSI_COMPONENT_85;
6843 					break;
6844 				case 6:
6845 					sense_key = KEY_HARDWARE_ERROR;
6846 					add_sense_code =
6847 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6848 					add_sense_code_qual = SCSI_COMPONENT_86;
6849 					break;
6850 				case 7:
6851 					sense_key = KEY_MEDIUM_ERROR;
6852 					add_sense_code =
6853 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6854 					add_sense_code_qual = SCSI_COMPONENT_87;
6855 					break;
6856 				case 8:
6857 					sense_key = KEY_HARDWARE_ERROR;
6858 					add_sense_code =
6859 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6860 					add_sense_code_qual = SCSI_COMPONENT_88;
6861 					break;
6862 				}
6863 				code = 0;	/* unspecified */
6864 				status |= (code << 4);
6865 				lpp->param_values[0] = status;
6866 				lpp->param_values[1] = 0; /* unspecified */
6867 				lpp->param_values[2] = entry->
6868 				    smart_selftest_log_timestamp[1];
6869 				lpp->param_values[3] = entry->
6870 				    smart_selftest_log_timestamp[0];
6871 				if (status != 0) {
6872 					lpp->param_values[4] = 0;
6873 					lpp->param_values[5] = 0;
6874 					lpp->param_values[6] = 0;
6875 					lpp->param_values[7] = 0;
6876 					lpp->param_values[8] = entry->
6877 					    smart_selftest_log_failing_lba[3];
6878 					lpp->param_values[9] = entry->
6879 					    smart_selftest_log_failing_lba[2];
6880 					lpp->param_values[10] = entry->
6881 					    smart_selftest_log_failing_lba[1];
6882 					lpp->param_values[11] = entry->
6883 					    smart_selftest_log_failing_lba[0];
6884 				} else {	/* No block address */
6885 					lpp->param_values[4] = 0xff;
6886 					lpp->param_values[5] = 0xff;
6887 					lpp->param_values[6] = 0xff;
6888 					lpp->param_values[7] = 0xff;
6889 					lpp->param_values[8] = 0xff;
6890 					lpp->param_values[9] = 0xff;
6891 					lpp->param_values[10] = 0xff;
6892 					lpp->param_values[11] = 0xff;
6893 				}
6894 				lpp->param_values[12] = sense_key;
6895 				lpp->param_values[13] = add_sense_code;
6896 				lpp->param_values[14] = add_sense_code_qual;
6897 				lpp->param_values[15] = 0; /* undefined */
6898 
6899 				lpp = (struct log_parameter *)
6900 				    (((uint8_t *)lpp) +
6901 				    SCSI_LOG_PARAM_HDR_LEN +
6902 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN);
6903 				--index;	/* back up to previous entry */
6904 				if (index < 0) {
6905 					index =
6906 					    NUM_SMART_SELFTEST_LOG_ENTRIES - 1;
6907 				}
6908 				entry = &selftest_log->
6909 				    smart_selftest_log_entries[index];
6910 			}
6911 		}
6912 done:
6913 		kmem_free(selftest_log, sizeof (struct smart_selftest_log));
6914 	}
6915 
6916 	return ((SCSI_LOG_PARAM_HDR_LEN + SCSI_LOG_SENSE_SELFTEST_PARAM_LEN) *
6917 	    SCSI_ENTRIES_IN_LOG_SENSE_SELFTEST_RESULTS);
6918 }
6919 
6920 /*
6921  * sata_build_lsense_page_2f() is used to create the
6922  * SCSI LOG SENSE page 0x2f (informational exceptions)
6923  *
6924  * Takes a sata_drive_info t * and the address of a buffer
6925  * in which to create the page information as well as a sata_hba_inst_t *.
6926  *
6927  * Returns the number of bytes valid in the buffer.
6928  *
6929  * Because it invokes function(s) that send synchronously executed command
6930  * to the HBA, it cannot be called in the interrupt context.
6931  */
6932 static	int
6933 sata_build_lsense_page_2f(
6934 	sata_drive_info_t *sdinfo,
6935 	uint8_t *buf,
6936 	sata_hba_inst_t *sata_hba_inst)
6937 {
6938 	struct log_parameter *lpp = (struct log_parameter *)buf;
6939 	int rval;
6940 	uint8_t *smart_data;
6941 	uint8_t temp;
6942 	sata_id_t *sata_id;
6943 #define	SMART_NO_TEMP	0xff
6944 
6945 	lpp->param_code[0] = 0;
6946 	lpp->param_code[1] = 0;
6947 	lpp->param_ctrl_flags = LOG_CTRL_LP | LOG_CTRL_LBIN;
6948 
6949 	/* Now get the SMART status w.r.t. threshold exceeded */
6950 	rval = sata_fetch_smart_return_status(sata_hba_inst, sdinfo);
6951 	switch (rval) {
6952 	case 1:
6953 		lpp->param_values[0] = SCSI_PREDICTED_FAILURE;
6954 		lpp->param_values[1] = SCSI_GENERAL_HD_FAILURE;
6955 		break;
6956 	case 0:
6957 	case -1:	/* failed to get data */
6958 		lpp->param_values[0] = 0;	/* No failure predicted */
6959 		lpp->param_values[1] = 0;
6960 		break;
6961 #if defined(SATA_DEBUG)
6962 	default:
6963 		cmn_err(CE_PANIC, "sata_build_lsense_page_2f bad return value");
6964 		/* NOTREACHED */
6965 #endif
6966 	}
6967 
6968 	sata_id = &sdinfo->satadrv_id;
6969 	if (! (sata_id->ai_sctsupport & SATA_SCT_CMD_TRANS_SUP))
6970 		temp = SMART_NO_TEMP;
6971 	else {
6972 		/* Now get the temperature */
6973 		smart_data = kmem_zalloc(512, KM_SLEEP);
6974 		rval = sata_smart_read_log(sata_hba_inst, sdinfo, smart_data,
6975 		    SCT_STATUS_LOG_PAGE, 1);
6976 		if (rval == -1)
6977 			temp = SMART_NO_TEMP;
6978 		else {
6979 			temp = smart_data[200];
6980 			if (temp & 0x80) {
6981 				if (temp & 0x7f)
6982 					temp = 0;
6983 				else
6984 					temp = SMART_NO_TEMP;
6985 			}
6986 		}
6987 		kmem_free(smart_data, 512);
6988 	}
6989 
6990 	lpp->param_values[2] = temp;	/* most recent temperature */
6991 	lpp->param_values[3] = 0;	/* required vendor specific byte */
6992 
6993 	lpp->param_len = SCSI_INFO_EXCEPTIONS_PARAM_LEN;
6994 
6995 
6996 	return (SCSI_INFO_EXCEPTIONS_PARAM_LEN + SCSI_LOG_PARAM_HDR_LEN);
6997 }
6998 
6999 /*
7000  * sata_build_lsense_page_30() is used to create the
7001  * SCSI LOG SENSE page 0x30 (Sun's vendor specific page for ATA SMART data).
7002  *
7003  * Takes a sata_drive_info t * and the address of a buffer
7004  * in which to create the page information as well as a sata_hba_inst_t *.
7005  *
7006  * Returns the number of bytes valid in the buffer.
7007  */
7008 static int
7009 sata_build_lsense_page_30(
7010 	sata_drive_info_t *sdinfo,
7011 	uint8_t *buf,
7012 	sata_hba_inst_t *sata_hba_inst)
7013 {
7014 	struct smart_data *smart_data = (struct smart_data *)buf;
7015 	int rval;
7016 
7017 	/* Now do the SMART READ DATA */
7018 	rval = sata_fetch_smart_data(sata_hba_inst, sdinfo, smart_data);
7019 	if (rval == -1)
7020 		return (0);
7021 
7022 	return (sizeof (struct smart_data));
7023 }
7024 
7025 /* ************************** ATAPI-SPECIFIC FUNCTIONS ********************** */
7026 
7027 /*
7028  * Start command for ATAPI device.
7029  * This function processes scsi_pkt requests.
7030  * Now CD/DVD, tape and ATAPI disk devices are supported.
7031  * Most commands are packet without any translation into Packet Command.
7032  * Some may be trapped and executed as SATA commands (not clear which one).
7033  *
7034  * Returns TRAN_ACCEPT if command is accepted for execution (or completed
7035  * execution).
7036  * Returns other TRAN_XXXX codes if command is not accepted or completed
7037  * (see return values for sata_hba_start()).
7038  *
7039  * Note:
7040  * Inquiry cdb format differs between transport version 2 and 3.
7041  * However, the transport version 3 devices that were checked did not adhere
7042  * to the specification (ignored MSB of the allocation length). Therefore,
7043  * the transport version is not checked, but Inquiry allocation length is
7044  * truncated to 255 bytes if the original allocation length set-up by the
7045  * target driver is greater than 255 bytes.
7046  */
7047 static int
7048 sata_txlt_atapi(sata_pkt_txlate_t *spx)
7049 {
7050 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7051 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
7052 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
7053 	sata_hba_inst_t *sata_hba = SATA_TXLT_HBA_INST(spx);
7054 	sata_drive_info_t *sdinfo = sata_get_device_info(sata_hba,
7055 	    &spx->txlt_sata_pkt->satapkt_device);
7056 	int cport = SATA_TXLT_CPORT(spx);
7057 	int cdblen;
7058 	int rval, reason;
7059 	int synch;
7060 	union scsi_cdb *cdbp = (union scsi_cdb *)scsipkt->pkt_cdbp;
7061 
7062 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
7063 
7064 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
7065 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
7066 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
7067 		return (rval);
7068 	}
7069 
7070 	/*
7071 	 * ATAPI device executes some ATA commands in addition to those
7072 	 * commands sent via PACKET command. These ATA commands may be
7073 	 * executed by the regular SATA translation functions. None needs
7074 	 * to be captured now.
7075 	 *
7076 	 * Commands sent via PACKET command include:
7077 	 *	MMC command set for ATAPI CD/DVD device
7078 	 *	SSC command set for ATAPI TAPE device
7079 	 *	SBC command set for ATAPI disk device
7080 	 *
7081 	 */
7082 
7083 	/* Check the size of cdb */
7084 	cdblen = scsi_cdb_size[GETGROUP(cdbp)];
7085 	if (cdblen > sdinfo->satadrv_atapi_cdb_len) {
7086 		sata_log(NULL, CE_WARN,
7087 		    "sata: invalid ATAPI cdb length %d",
7088 		    scsipkt->pkt_cdblen);
7089 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
7090 		return (TRAN_BADPKT);
7091 	}
7092 
7093 	SATAATAPITRACE(spx, cdblen);
7094 
7095 	/*
7096 	 * For non-read/write commands we need to
7097 	 * map buffer
7098 	 */
7099 	switch ((uint_t)scsipkt->pkt_cdbp[0]) {
7100 	case SCMD_READ:
7101 	case SCMD_READ_G1:
7102 	case SCMD_READ_G5:
7103 	case SCMD_READ_G4:
7104 	case SCMD_WRITE:
7105 	case SCMD_WRITE_G1:
7106 	case SCMD_WRITE_G5:
7107 	case SCMD_WRITE_G4:
7108 		break;
7109 	default:
7110 		if (bp != NULL) {
7111 			if (bp->b_flags & (B_PHYS | B_PAGEIO))
7112 				bp_mapin(bp);
7113 		}
7114 		break;
7115 	}
7116 	/*
7117 	 * scmd->satacmd_flags.sata_data_direction default -
7118 	 * SATA_DIR_NODATA_XFER - is set by
7119 	 * sata_txlt_generic_pkt_info().
7120 	 */
7121 	if (scmd->satacmd_bp) {
7122 		if (scmd->satacmd_bp->b_flags & B_READ) {
7123 			scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
7124 		} else {
7125 			scmd->satacmd_flags.sata_data_direction =
7126 			    SATA_DIR_WRITE;
7127 		}
7128 	}
7129 
7130 	/*
7131 	 * Set up ATAPI packet command.
7132 	 */
7133 
7134 	sata_atapi_packet_cmd_setup(scmd, sdinfo);
7135 
7136 	/* Copy cdb into sata_cmd */
7137 	scmd->satacmd_acdb_len = sdinfo->satadrv_atapi_cdb_len;
7138 	bzero(scmd->satacmd_acdb, SATA_ATAPI_MAX_CDB_LEN);
7139 	bcopy(cdbp, scmd->satacmd_acdb, cdblen);
7140 
7141 	/* See note in the command header */
7142 	if (scmd->satacmd_acdb[0] == SCMD_INQUIRY) {
7143 		if (scmd->satacmd_acdb[3] != 0)
7144 			scmd->satacmd_acdb[4] = 255;
7145 	}
7146 
7147 #ifdef SATA_DEBUG
7148 	if (sata_debug_flags & SATA_DBG_ATAPI) {
7149 		uint8_t *p = scmd->satacmd_acdb;
7150 		char buf[3 * SATA_ATAPI_MAX_CDB_LEN];
7151 
7152 		(void) snprintf(buf, SATA_ATAPI_MAX_CDB_LEN,
7153 		    "%02x %02x %02x %02x %02x %02x %02x %02x "
7154 		    "%2x %02x %02x %02x %02x %02x %02x %02x",
7155 		    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
7156 		    p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
7157 		buf[(3 * SATA_ATAPI_MAX_CDB_LEN) - 1] = '\0';
7158 		cmn_err(CE_NOTE, "ATAPI cdb: %s\n", buf);
7159 	}
7160 #endif
7161 
7162 	/*
7163 	 * Preset request sense data to NO SENSE.
7164 	 * If there is no way to get error information via Request Sense,
7165 	 * the packet request sense data would not have to be modified by HBA,
7166 	 * but it could be returned as is.
7167 	 */
7168 	bzero(scmd->satacmd_rqsense, SATA_ATAPI_RQSENSE_LEN);
7169 	sata_fixed_sense_data_preset(
7170 	    (struct scsi_extended_sense *)scmd->satacmd_rqsense);
7171 
7172 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
7173 		/* Need callback function */
7174 		spx->txlt_sata_pkt->satapkt_comp = sata_txlt_atapi_completion;
7175 		synch = FALSE;
7176 	} else
7177 		synch = TRUE;
7178 
7179 	/* Transfer command to HBA */
7180 	if (sata_hba_start(spx, &rval) != 0) {
7181 		/* Pkt not accepted for execution */
7182 		mutex_exit(&SATA_CPORT_MUTEX(sata_hba, cport));
7183 		return (rval);
7184 	}
7185 	mutex_exit(&SATA_CPORT_MUTEX(sata_hba, cport));
7186 	/*
7187 	 * If execution is non-synchronous,
7188 	 * a callback function will handle potential errors, translate
7189 	 * the response and will do a callback to a target driver.
7190 	 * If it was synchronous, use the same framework callback to check
7191 	 * an execution status.
7192 	 */
7193 	if (synch) {
7194 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
7195 		    "synchronous execution status %x\n",
7196 		    spx->txlt_sata_pkt->satapkt_reason);
7197 		sata_txlt_atapi_completion(spx->txlt_sata_pkt);
7198 	}
7199 	return (TRAN_ACCEPT);
7200 }
7201 
7202 
7203 /*
7204  * ATAPI Packet command completion.
7205  *
7206  * Failure of the command passed via Packet command are considered device
7207  * error. SATA HBA driver would have to retrieve error data (via Request
7208  * Sense command delivered via error retrieval sata packet) and copy it
7209  * to satacmd_rqsense array. From there, it is moved into scsi pkt sense data.
7210  */
7211 static void
7212 sata_txlt_atapi_completion(sata_pkt_t *sata_pkt)
7213 {
7214 	sata_pkt_txlate_t *spx =
7215 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
7216 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7217 	struct scsi_extended_sense *sense;
7218 	struct buf *bp;
7219 	int rval;
7220 
7221 #ifdef SATA_DEBUG
7222 	uint8_t *rqsp = sata_pkt->satapkt_cmd.satacmd_rqsense;
7223 #endif
7224 
7225 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7226 	    STATE_SENT_CMD | STATE_GOT_STATUS;
7227 
7228 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
7229 		/* Normal completion */
7230 		if (sata_pkt->satapkt_cmd.satacmd_bp != NULL)
7231 			scsipkt->pkt_state |= STATE_XFERRED_DATA;
7232 		scsipkt->pkt_reason = CMD_CMPLT;
7233 		*scsipkt->pkt_scbp = STATUS_GOOD;
7234 		if (spx->txlt_tmp_buf != NULL) {
7235 			/* Temporary buffer was used */
7236 			bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
7237 			if (bp->b_flags & B_READ) {
7238 				rval = ddi_dma_sync(
7239 				    spx->txlt_buf_dma_handle, 0, 0,
7240 				    DDI_DMA_SYNC_FORCPU);
7241 				ASSERT(rval == DDI_SUCCESS);
7242 				bcopy(spx->txlt_tmp_buf, bp->b_un.b_addr,
7243 				    bp->b_bcount);
7244 			}
7245 		}
7246 	} else {
7247 		/*
7248 		 * Something went wrong - analyze return
7249 		 */
7250 		*scsipkt->pkt_scbp = STATUS_CHECK;
7251 		sense = sata_arq_sense(spx);
7252 
7253 		if (sata_pkt->satapkt_reason == SATA_PKT_DEV_ERROR) {
7254 			/*
7255 			 * pkt_reason should be CMD_CMPLT for DEVICE ERROR.
7256 			 * Under this condition ERR bit is set for ATA command,
7257 			 * and CHK bit set for ATAPI command.
7258 			 *
7259 			 * Please check st_intr & sdintr about how pkt_reason
7260 			 * is used.
7261 			 */
7262 			scsipkt->pkt_reason = CMD_CMPLT;
7263 
7264 			/*
7265 			 * We may not have ARQ data if there was a double
7266 			 * error. But sense data in sata packet was pre-set
7267 			 * with NO SENSE so it is valid even if HBA could
7268 			 * not retrieve a real sense data.
7269 			 * Just copy this sense data into scsi pkt sense area.
7270 			 */
7271 			bcopy(sata_pkt->satapkt_cmd.satacmd_rqsense, sense,
7272 			    SATA_ATAPI_MIN_RQSENSE_LEN);
7273 #ifdef SATA_DEBUG
7274 			if (sata_debug_flags & SATA_DBG_SCSI_IF) {
7275 				sata_log(spx->txlt_sata_hba_inst, CE_WARN,
7276 				    "sata_txlt_atapi_completion: %02x\n"
7277 				    "RQSENSE:  %02x %02x %02x %02x %02x %02x "
7278 				    "          %02x %02x %02x %02x %02x %02x "
7279 				    "          %02x %02x %02x %02x %02x %02x\n",
7280 				    scsipkt->pkt_reason,
7281 				    rqsp[0], rqsp[1], rqsp[2], rqsp[3],
7282 				    rqsp[4], rqsp[5], rqsp[6], rqsp[7],
7283 				    rqsp[8], rqsp[9], rqsp[10], rqsp[11],
7284 				    rqsp[12], rqsp[13], rqsp[14], rqsp[15],
7285 				    rqsp[16], rqsp[17]);
7286 			}
7287 #endif
7288 		} else {
7289 			switch (sata_pkt->satapkt_reason) {
7290 			case SATA_PKT_PORT_ERROR:
7291 				/*
7292 				 * We have no device data.
7293 				 */
7294 				scsipkt->pkt_reason = CMD_INCOMPLETE;
7295 				scsipkt->pkt_state &= ~(STATE_GOT_BUS |
7296 				    STATE_GOT_TARGET | STATE_SENT_CMD |
7297 				    STATE_GOT_STATUS);
7298 				sense->es_key = KEY_HARDWARE_ERROR;
7299 				break;
7300 
7301 			case SATA_PKT_TIMEOUT:
7302 				scsipkt->pkt_reason = CMD_TIMEOUT;
7303 				scsipkt->pkt_statistics |=
7304 				    STAT_TIMEOUT | STAT_DEV_RESET;
7305 				/*
7306 				 * Need to check if HARDWARE_ERROR/
7307 				 * TIMEOUT_ON_LOGICAL_UNIT 4/3E/2 would be more
7308 				 * appropriate.
7309 				 */
7310 				break;
7311 
7312 			case SATA_PKT_ABORTED:
7313 				scsipkt->pkt_reason = CMD_ABORTED;
7314 				scsipkt->pkt_statistics |= STAT_ABORTED;
7315 				/* Should we set key COMMAND_ABPRTED? */
7316 				break;
7317 
7318 			case SATA_PKT_RESET:
7319 				scsipkt->pkt_reason = CMD_RESET;
7320 				scsipkt->pkt_statistics |= STAT_DEV_RESET;
7321 				/*
7322 				 * May be we should set Unit Attention /
7323 				 * Reset. Perhaps the same should be
7324 				 * returned for disks....
7325 				 */
7326 				sense->es_key = KEY_UNIT_ATTENTION;
7327 				sense->es_add_code = SD_SCSI_ASC_RESET;
7328 				break;
7329 
7330 			default:
7331 				SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
7332 				    "sata_txlt_atapi_completion: "
7333 				    "invalid packet completion reason"));
7334 				scsipkt->pkt_reason = CMD_TRAN_ERR;
7335 				scsipkt->pkt_state &= ~(STATE_GOT_BUS |
7336 				    STATE_GOT_TARGET | STATE_SENT_CMD |
7337 				    STATE_GOT_STATUS);
7338 				break;
7339 			}
7340 		}
7341 	}
7342 
7343 	SATAATAPITRACE(spx, 0);
7344 
7345 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
7346 	    scsipkt->pkt_comp != NULL) {
7347 		/* scsi callback required */
7348 		(*scsipkt->pkt_comp)(scsipkt);
7349 	}
7350 }
7351 
7352 /*
7353  * Set up error retrieval sata command for ATAPI Packet Command error data
7354  * recovery.
7355  *
7356  * Returns SATA_SUCCESS when data buffer is allocated and packet set-up,
7357  * returns SATA_FAILURE otherwise.
7358  */
7359 
7360 static int
7361 sata_atapi_err_ret_cmd_setup(sata_pkt_txlate_t *spx, sata_drive_info_t *sdinfo)
7362 {
7363 	sata_pkt_t *spkt = spx->txlt_sata_pkt;
7364 	sata_cmd_t *scmd;
7365 	struct buf *bp;
7366 
7367 	/*
7368 	 * Allocate dma-able buffer error data.
7369 	 * Buffer allocation will take care of buffer alignment and other DMA
7370 	 * attributes.
7371 	 */
7372 	bp = sata_alloc_local_buffer(spx, SATA_ATAPI_MIN_RQSENSE_LEN);
7373 	if (bp == NULL) {
7374 		SATADBG1(SATA_DBG_ATAPI, spx->txlt_sata_hba_inst,
7375 		    "sata_get_err_retrieval_pkt: "
7376 		    "cannot allocate buffer for error data", NULL);
7377 		return (SATA_FAILURE);
7378 	}
7379 	bp_mapin(bp); /* make data buffer accessible */
7380 
7381 	/* Operation modes are up to the caller */
7382 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
7383 
7384 	/* Synchronous mode, no callback - may be changed by the caller */
7385 	spkt->satapkt_comp = NULL;
7386 	spkt->satapkt_time = sata_default_pkt_time;
7387 
7388 	scmd = &spkt->satapkt_cmd;
7389 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
7390 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
7391 
7392 	sata_atapi_packet_cmd_setup(scmd, sdinfo);
7393 
7394 	/*
7395 	 * Set-up acdb. Request Sense CDB (packet command content) is
7396 	 * not in DMA-able buffer. Its handling is HBA-specific (how
7397 	 * it is transfered into packet FIS).
7398 	 */
7399 	scmd->satacmd_acdb_len = sdinfo->satadrv_atapi_cdb_len;
7400 	bcopy(sata_rqsense_cdb, scmd->satacmd_acdb, SATA_ATAPI_RQSENSE_CDB_LEN);
7401 	/* Following zeroing of pad bytes may not be necessary */
7402 	bzero(&scmd->satacmd_acdb[SATA_ATAPI_RQSENSE_CDB_LEN],
7403 	    sdinfo->satadrv_atapi_cdb_len - SATA_ATAPI_RQSENSE_CDB_LEN);
7404 
7405 	/*
7406 	 * Set-up pointer to the buffer handle, so HBA can sync buffer
7407 	 * before accessing it. Handle is in usual place in translate struct.
7408 	 */
7409 	scmd->satacmd_err_ret_buf_handle = &spx->txlt_buf_dma_handle;
7410 
7411 	/*
7412 	 * Preset request sense data to NO SENSE.
7413 	 * Here it is redundant, only for a symetry with scsi-originated
7414 	 * packets. It should not be used for anything but debugging.
7415 	 */
7416 	bzero(scmd->satacmd_rqsense, SATA_ATAPI_RQSENSE_LEN);
7417 	sata_fixed_sense_data_preset(
7418 	    (struct scsi_extended_sense *)scmd->satacmd_rqsense);
7419 
7420 	ASSERT(scmd->satacmd_num_dma_cookies != 0);
7421 	ASSERT(scmd->satacmd_dma_cookie_list != NULL);
7422 
7423 	return (SATA_SUCCESS);
7424 }
7425 
7426 /*
7427  * Set-up ATAPI packet command.
7428  * Data transfer direction has to be set-up in sata_cmd structure prior to
7429  * calling this function.
7430  *
7431  * Returns void
7432  */
7433 
7434 static void
7435 sata_atapi_packet_cmd_setup(sata_cmd_t *scmd, sata_drive_info_t *sdinfo)
7436 {
7437 	scmd->satacmd_addr_type = 0;		/* N/A */
7438 	scmd->satacmd_sec_count_lsb = 0;	/* no tag */
7439 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
7440 	scmd->satacmd_lba_mid_lsb = (uint8_t)SATA_ATAPI_MAX_BYTES_PER_DRQ;
7441 	scmd->satacmd_lba_high_lsb =
7442 	    (uint8_t)(SATA_ATAPI_MAX_BYTES_PER_DRQ >> 8);
7443 	scmd->satacmd_cmd_reg = SATAC_PACKET;	/* Command */
7444 
7445 	/*
7446 	 * We want all data to be transfered via DMA.
7447 	 * But specify it only if drive supports DMA and DMA mode is
7448 	 * selected - some drives are sensitive about it.
7449 	 * Hopefully it wil work for all drives....
7450 	 */
7451 	if (sdinfo->satadrv_settings & SATA_DEV_DMA)
7452 		scmd->satacmd_features_reg = SATA_ATAPI_F_DMA;
7453 
7454 	/*
7455 	 * Features register requires special care for devices that use
7456 	 * Serial ATA bridge - they need an explicit specification of
7457 	 * the data transfer direction for Packet DMA commands.
7458 	 * Setting this bit is harmless if DMA is not used.
7459 	 *
7460 	 * Many drives do not implement word 80, specifying what ATA/ATAPI
7461 	 * spec they follow.
7462 	 * We are arbitrarily following the latest SerialATA 2.6 spec,
7463 	 * which uses ATA/ATAPI 6 specification for Identify Data, unless
7464 	 * ATA/ATAPI-7 support is explicitly indicated.
7465 	 */
7466 	if (sdinfo->satadrv_id.ai_majorversion != 0 &&
7467 	    sdinfo->satadrv_id.ai_majorversion != 0xffff &&
7468 	    (sdinfo->satadrv_id.ai_majorversion & SATA_MAJVER_7) != 0) {
7469 		/*
7470 		 * Specification of major version is valid and version 7
7471 		 * is supported. It does automatically imply that all
7472 		 * spec features are supported. For now, we assume that
7473 		 * DMADIR setting is valid. ATA/ATAPI7 spec is incomplete.
7474 		 */
7475 		if ((sdinfo->satadrv_id.ai_dirdma &
7476 		    SATA_ATAPI_ID_DMADIR_REQ) != 0) {
7477 			if (scmd->satacmd_flags.sata_data_direction ==
7478 			    SATA_DIR_READ)
7479 			scmd->satacmd_features_reg |=
7480 			    SATA_ATAPI_F_DATA_DIR_READ;
7481 		}
7482 	}
7483 }
7484 
7485 
7486 #ifdef SATA_DEBUG
7487 
7488 /* Display 18 bytes of Inquiry data */
7489 static void
7490 sata_show_inqry_data(uint8_t *buf)
7491 {
7492 	struct scsi_inquiry *inq = (struct scsi_inquiry *)buf;
7493 	uint8_t *p;
7494 
7495 	cmn_err(CE_NOTE, "Inquiry data:");
7496 	cmn_err(CE_NOTE, "device type %x", inq->inq_dtype);
7497 	cmn_err(CE_NOTE, "removable media %x", inq->inq_rmb);
7498 	cmn_err(CE_NOTE, "version %x", inq->inq_ansi);
7499 	cmn_err(CE_NOTE, "ATAPI transport version %d",
7500 	    SATA_ATAPI_TRANS_VERSION(inq));
7501 	cmn_err(CE_NOTE, "response data format %d, aenc %d",
7502 	    inq->inq_rdf, inq->inq_aenc);
7503 	cmn_err(CE_NOTE, " additional length %d", inq->inq_len);
7504 	cmn_err(CE_NOTE, "tpgs %d", inq->inq_tpgs);
7505 	p = (uint8_t *)inq->inq_vid;
7506 	cmn_err(CE_NOTE, "vendor id (binary): %02x %02x %02x %02x "
7507 	    "%02x %02x %02x %02x",
7508 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7]);
7509 	p = (uint8_t *)inq->inq_vid;
7510 	cmn_err(CE_NOTE, "vendor id: %c %c %c %c %c %c %c %c",
7511 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7]);
7512 
7513 	p = (uint8_t *)inq->inq_pid;
7514 	cmn_err(CE_NOTE, "product id (binary): %02x %02x %02x %02x "
7515 	    "%02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x",
7516 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
7517 	    p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
7518 	p = (uint8_t *)inq->inq_pid;
7519 	cmn_err(CE_NOTE, "product id: %c %c %c %c %c %c %c %c "
7520 	    "%c %c %c %c %c %c %c %c",
7521 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
7522 	    p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
7523 
7524 	p = (uint8_t *)inq->inq_revision;
7525 	cmn_err(CE_NOTE, "revision (binary): %02x %02x %02x %02x",
7526 	    p[0], p[1], p[2], p[3]);
7527 	p = (uint8_t *)inq->inq_revision;
7528 	cmn_err(CE_NOTE, "revision: %c %c %c %c",
7529 	    p[0], p[1], p[2], p[3]);
7530 
7531 }
7532 
7533 
7534 static void
7535 sata_save_atapi_trace(sata_pkt_txlate_t *spx, int count)
7536 {
7537 	struct scsi_pkt *scsi_pkt = spx->txlt_scsi_pkt;
7538 
7539 	if (scsi_pkt == NULL)
7540 		return;
7541 	if (count != 0) {
7542 		/* saving cdb */
7543 		bzero(sata_atapi_trace[sata_atapi_trace_index].acdb,
7544 		    SATA_ATAPI_MAX_CDB_LEN);
7545 		bcopy(scsi_pkt->pkt_cdbp,
7546 		    sata_atapi_trace[sata_atapi_trace_index].acdb, count);
7547 	} else {
7548 		bcopy(&((struct scsi_arq_status *)scsi_pkt->pkt_scbp)->
7549 		    sts_sensedata,
7550 		    sata_atapi_trace[sata_atapi_trace_index].arqs,
7551 		    SATA_ATAPI_MIN_RQSENSE_LEN);
7552 		sata_atapi_trace[sata_atapi_trace_index].scsi_pkt_reason =
7553 		    scsi_pkt->pkt_reason;
7554 		sata_atapi_trace[sata_atapi_trace_index].sata_pkt_reason =
7555 		    spx->txlt_sata_pkt->satapkt_reason;
7556 
7557 		if (++sata_atapi_trace_index >= 64)
7558 			sata_atapi_trace_index = 0;
7559 	}
7560 }
7561 
7562 #endif
7563 
7564 /*
7565  * Fetch inquiry data from ATAPI device
7566  * Returns SATA_SUCCESS if operation was successfull, SATA_FAILURE otherwise.
7567  *
7568  * Note:
7569  * inqb pointer does not point to a DMA-able buffer. It is a local buffer
7570  * where the caller expects to see the inquiry data.
7571  *
7572  */
7573 
7574 static int
7575 sata_get_atapi_inquiry_data(sata_hba_inst_t *sata_hba,
7576     sata_address_t *saddr, struct scsi_inquiry *inq)
7577 {
7578 	sata_pkt_txlate_t *spx;
7579 	sata_pkt_t *spkt;
7580 	struct buf *bp;
7581 	sata_drive_info_t *sdinfo;
7582 	sata_cmd_t *scmd;
7583 	int rval;
7584 	uint8_t *rqsp;
7585 #ifdef SATA_DEBUG
7586 	char msg_buf[MAXPATHLEN];
7587 #endif
7588 
7589 	ASSERT(sata_hba != NULL);
7590 
7591 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
7592 	spx->txlt_sata_hba_inst = sata_hba;
7593 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
7594 	spkt = sata_pkt_alloc(spx, NULL);
7595 	if (spkt == NULL) {
7596 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
7597 		return (SATA_FAILURE);
7598 	}
7599 	/* address is needed now */
7600 	spkt->satapkt_device.satadev_addr = *saddr;
7601 
7602 	/* scsi_inquiry size buffer */
7603 	bp = sata_alloc_local_buffer(spx, sizeof (struct scsi_inquiry));
7604 	if (bp == NULL) {
7605 		sata_pkt_free(spx);
7606 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
7607 		SATA_LOG_D((sata_hba, CE_WARN,
7608 		    "sata_get_atapi_inquiry_data: "
7609 		    "cannot allocate data buffer"));
7610 		return (SATA_FAILURE);
7611 	}
7612 	bp_mapin(bp); /* make data buffer accessible */
7613 
7614 	scmd = &spkt->satapkt_cmd;
7615 	ASSERT(scmd->satacmd_num_dma_cookies != 0);
7616 	ASSERT(scmd->satacmd_dma_cookie_list != NULL);
7617 
7618 	/* Use synchronous mode */
7619 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
7620 	spkt->satapkt_comp = NULL;
7621 	spkt->satapkt_time = sata_default_pkt_time;
7622 
7623 	/* Issue inquiry command - 6 bytes cdb, data transfer, read */
7624 
7625 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
7626 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
7627 
7628 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
7629 	sdinfo = sata_get_device_info(sata_hba,
7630 	    &spx->txlt_sata_pkt->satapkt_device);
7631 	if (sdinfo == NULL) {
7632 		/* we have to be carefull about the disapearing device */
7633 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
7634 		rval = SATA_FAILURE;
7635 		goto cleanup;
7636 	}
7637 	sata_atapi_packet_cmd_setup(scmd, sdinfo);
7638 
7639 	/*
7640 	 * Set-up acdb. This works for atapi transport version 2 and later.
7641 	 */
7642 	scmd->satacmd_acdb_len = sdinfo->satadrv_atapi_cdb_len;
7643 	bzero(scmd->satacmd_acdb, SATA_ATAPI_MAX_CDB_LEN);
7644 	scmd->satacmd_acdb[0] = 0x12;	/* Inquiry */
7645 	scmd->satacmd_acdb[1] = 0x00;
7646 	scmd->satacmd_acdb[2] = 0x00;
7647 	scmd->satacmd_acdb[3] = 0x00;
7648 	scmd->satacmd_acdb[4] = sizeof (struct scsi_inquiry);
7649 	scmd->satacmd_acdb[5] = 0x00;
7650 
7651 	sata_fixed_sense_data_preset(
7652 	    (struct scsi_extended_sense *)scmd->satacmd_rqsense);
7653 
7654 	/* Transfer command to HBA */
7655 	if (sata_hba_start(spx, &rval) != 0) {
7656 		/* Pkt not accepted for execution */
7657 		SATADBG1(SATA_DBG_ATAPI, sata_hba,
7658 		    "sata_get_atapi_inquiry_data: "
7659 		    "Packet not accepted for execution - ret: %02x", rval);
7660 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
7661 		rval = SATA_FAILURE;
7662 		goto cleanup;
7663 	}
7664 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
7665 
7666 	if (spkt->satapkt_reason == SATA_PKT_COMPLETED) {
7667 		SATADBG1(SATA_DBG_ATAPI, sata_hba,
7668 		    "sata_get_atapi_inquiry_data: "
7669 		    "Packet completed successfully - ret: %02x", rval);
7670 		if (spx->txlt_buf_dma_handle != NULL) {
7671 			/*
7672 			 * Sync buffer. Handle is in usual place in translate
7673 			 * struct.
7674 			 */
7675 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
7676 			    DDI_DMA_SYNC_FORCPU);
7677 			ASSERT(rval == DDI_SUCCESS);
7678 		}
7679 		/*
7680 		 * Normal completion - copy data into caller's buffer
7681 		 */
7682 		bcopy(bp->b_un.b_addr, (uint8_t *)inq,
7683 		    sizeof (struct scsi_inquiry));
7684 #ifdef SATA_DEBUG
7685 		if (sata_debug_flags & SATA_DBG_ATAPI) {
7686 			sata_show_inqry_data((uint8_t *)inq);
7687 		}
7688 #endif
7689 		rval = SATA_SUCCESS;
7690 	} else {
7691 		/*
7692 		 * Something went wrong - analyze return - check rqsense data
7693 		 */
7694 		rval = SATA_FAILURE;
7695 		if (spkt->satapkt_reason == SATA_PKT_DEV_ERROR) {
7696 			/*
7697 			 * ARQ data hopefull show something other than NO SENSE
7698 			 */
7699 			rqsp = scmd->satacmd_rqsense;
7700 #ifdef SATA_DEBUG
7701 			if (sata_debug_flags & SATA_DBG_ATAPI) {
7702 				msg_buf[0] = '\0';
7703 				(void) snprintf(msg_buf, MAXPATHLEN,
7704 				    "ATAPI packet completion reason: %02x\n"
7705 				    "RQSENSE:  %02x %02x %02x %02x %02x %02x\n"
7706 				    "          %02x %02x %02x %02x %02x %02x\n"
7707 				    "          %02x %02x %02x %02x %02x %02x",
7708 				    spkt->satapkt_reason,
7709 				    rqsp[0], rqsp[1], rqsp[2], rqsp[3],
7710 				    rqsp[4], rqsp[5], rqsp[6], rqsp[7],
7711 				    rqsp[8], rqsp[9], rqsp[10], rqsp[11],
7712 				    rqsp[12], rqsp[13], rqsp[14], rqsp[15],
7713 				    rqsp[16], rqsp[17]);
7714 				sata_log(spx->txlt_sata_hba_inst, CE_WARN,
7715 				    "%s", msg_buf);
7716 			}
7717 #endif
7718 		} else {
7719 			switch (spkt->satapkt_reason) {
7720 			case SATA_PKT_PORT_ERROR:
7721 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
7722 				    "sata_get_atapi_inquiry_data: "
7723 				    "packet reason: port error", NULL);
7724 				break;
7725 
7726 			case SATA_PKT_TIMEOUT:
7727 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
7728 				    "sata_get_atapi_inquiry_data: "
7729 				    "packet reason: timeout", NULL);
7730 				break;
7731 
7732 			case SATA_PKT_ABORTED:
7733 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
7734 				    "sata_get_atapi_inquiry_data: "
7735 				    "packet reason: aborted", NULL);
7736 				break;
7737 
7738 			case SATA_PKT_RESET:
7739 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
7740 				    "sata_get_atapi_inquiry_data: "
7741 				    "packet reason: reset\n", NULL);
7742 				break;
7743 			default:
7744 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
7745 				    "sata_get_atapi_inquiry_data: "
7746 				    "invalid packet reason: %02x\n",
7747 				    spkt->satapkt_reason);
7748 				break;
7749 			}
7750 		}
7751 	}
7752 cleanup:
7753 	sata_free_local_buffer(spx);
7754 	sata_pkt_free(spx);
7755 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
7756 	return (rval);
7757 }
7758 
7759 
7760 
7761 
7762 
7763 #if 0
7764 #ifdef SATA_DEBUG
7765 
7766 /*
7767  * Test ATAPI packet command.
7768  * Single threaded test: send packet command in synch mode, process completion
7769  *
7770  */
7771 static void
7772 sata_test_atapi_packet_command(sata_hba_inst_t *sata_hba_inst, int cport)
7773 {
7774 	sata_pkt_txlate_t *spx;
7775 	sata_pkt_t *spkt;
7776 	struct buf *bp;
7777 	sata_device_t sata_device;
7778 	sata_drive_info_t *sdinfo;
7779 	sata_cmd_t *scmd;
7780 	int rval;
7781 	uint8_t *rqsp;
7782 
7783 	ASSERT(sata_hba_inst != NULL);
7784 	sata_device.satadev_addr.cport = cport;
7785 	sata_device.satadev_addr.pmport = 0;
7786 	sata_device.satadev_addr.qual = SATA_ADDR_DCPORT;
7787 	sata_device.satadev_rev = SATA_DEVICE_REV;
7788 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
7789 	sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
7790 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
7791 	if (sdinfo == NULL) {
7792 		sata_log(sata_hba_inst, CE_WARN,
7793 		    "sata_test_atapi_packet_command: "
7794 		    "no device info for cport %d",
7795 		    sata_device.satadev_addr.cport);
7796 		return;
7797 	}
7798 
7799 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
7800 	spx->txlt_sata_hba_inst = sata_hba_inst;
7801 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
7802 	spkt = sata_pkt_alloc(spx, NULL);
7803 	if (spkt == NULL) {
7804 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
7805 		return;
7806 	}
7807 	/* address is needed now */
7808 	spkt->satapkt_device.satadev_addr = sata_device.satadev_addr;
7809 
7810 	/* 1024k buffer */
7811 	bp = sata_alloc_local_buffer(spx, 1024);
7812 	if (bp == NULL) {
7813 		sata_pkt_free(spx);
7814 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
7815 		sata_log(sata_hba_inst, CE_WARN,
7816 		    "sata_test_atapi_packet_command: "
7817 		    "cannot allocate data buffer");
7818 		return;
7819 	}
7820 	bp_mapin(bp); /* make data buffer accessible */
7821 
7822 	scmd = &spkt->satapkt_cmd;
7823 	ASSERT(scmd->satacmd_num_dma_cookies != 0);
7824 	ASSERT(scmd->satacmd_dma_cookie_list != NULL);
7825 
7826 	/* Use synchronous mode */
7827 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
7828 
7829 	/* Synchronous mode, no callback - may be changed by the caller */
7830 	spkt->satapkt_comp = NULL;
7831 	spkt->satapkt_time = sata_default_pkt_time;
7832 
7833 	/* Issue inquiry command - 6 bytes cdb, data transfer, read */
7834 
7835 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
7836 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
7837 
7838 	sata_atapi_packet_cmd_setup(scmd, sdinfo);
7839 
7840 	/* Set-up acdb. */
7841 	scmd->satacmd_acdb_len = sdinfo->satadrv_atapi_cdb_len;
7842 	bzero(scmd->satacmd_acdb, SATA_ATAPI_MAX_CDB_LEN);
7843 	scmd->satacmd_acdb[0] = 0x12;	/* Inquiry */
7844 	scmd->satacmd_acdb[1] = 0x00;
7845 	scmd->satacmd_acdb[2] = 0x00;
7846 	scmd->satacmd_acdb[3] = 0x00;
7847 	scmd->satacmd_acdb[4] = sizeof (struct scsi_inquiry);
7848 	scmd->satacmd_acdb[5] = 0x00;
7849 
7850 	sata_fixed_sense_data_preset(
7851 	    (struct scsi_extended_sense *)scmd->satacmd_rqsense);
7852 
7853 	/* Transfer command to HBA */
7854 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
7855 	if (sata_hba_start(spx, &rval) != 0) {
7856 		/* Pkt not accepted for execution */
7857 		sata_log(sata_hba_inst, CE_WARN,
7858 		    "sata_test_atapi_packet_command: "
7859 		    "Packet not accepted for execution - ret: %02x", rval);
7860 		mutex_exit(
7861 		    &SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
7862 		goto cleanup;
7863 	}
7864 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
7865 
7866 	if (spx->txlt_buf_dma_handle != NULL) {
7867 		/*
7868 		 * Sync buffer. Handle is in usual place in translate struct.
7869 		 */
7870 		rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
7871 		    DDI_DMA_SYNC_FORCPU);
7872 		ASSERT(rval == DDI_SUCCESS);
7873 	}
7874 	if (spkt->satapkt_reason == SATA_PKT_COMPLETED) {
7875 		sata_log(sata_hba_inst, CE_WARN,
7876 		    "sata_test_atapi_packet_command: "
7877 		    "Packet completed successfully");
7878 		/*
7879 		 * Normal completion - show inquiry data
7880 		 */
7881 		sata_show_inqry_data((uint8_t *)bp->b_un.b_addr);
7882 	} else {
7883 		/*
7884 		 * Something went wrong - analyze return - check rqsense data
7885 		 */
7886 		if (spkt->satapkt_reason == SATA_PKT_DEV_ERROR) {
7887 			/*
7888 			 * ARQ data hopefull show something other than NO SENSE
7889 			 */
7890 			rqsp = scmd->satacmd_rqsense;
7891 			sata_log(spx->txlt_sata_hba_inst, CE_WARN,
7892 			    "ATAPI packet completion reason: %02x\n"
7893 			    "RQSENSE:  %02x %02x %02x %02x %02x %02x "
7894 			    "          %02x %02x %02x %02x %02x %02x "
7895 			    "          %02x %02x %02x %02x %02x %02x\n",
7896 			    spkt->satapkt_reason,
7897 			    rqsp[0], rqsp[1], rqsp[2], rqsp[3],
7898 			    rqsp[4], rqsp[5], rqsp[6], rqsp[7],
7899 			    rqsp[8], rqsp[9], rqsp[10], rqsp[11],
7900 			    rqsp[12], rqsp[13], rqsp[14], rqsp[15],
7901 			    rqsp[16], rqsp[17]);
7902 		} else {
7903 			switch (spkt->satapkt_reason) {
7904 			case SATA_PKT_PORT_ERROR:
7905 				sata_log(sata_hba_inst, CE_WARN,
7906 				    "sata_test_atapi_packet_command: "
7907 				    "packet reason: port error\n");
7908 				break;
7909 
7910 			case SATA_PKT_TIMEOUT:
7911 				sata_log(sata_hba_inst, CE_WARN,
7912 				    "sata_test_atapi_packet_command: "
7913 				    "packet reason: timeout\n");
7914 				break;
7915 
7916 			case SATA_PKT_ABORTED:
7917 				sata_log(sata_hba_inst, CE_WARN,
7918 				    "sata_test_atapi_packet_command: "
7919 				    "packet reason: aborted\n");
7920 				break;
7921 
7922 			case SATA_PKT_RESET:
7923 				sata_log(sata_hba_inst, CE_WARN,
7924 				    "sata_test_atapi_packet_command: "
7925 				    "packet reason: reset\n");
7926 				break;
7927 			default:
7928 				sata_log(sata_hba_inst, CE_WARN,
7929 				    "sata_test_atapi_packet_command: "
7930 				    "invalid packet reason: %02x\n",
7931 				    spkt->satapkt_reason);
7932 				break;
7933 			}
7934 		}
7935 	}
7936 cleanup:
7937 	sata_free_local_buffer(spx);
7938 	sata_pkt_free(spx);
7939 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
7940 }
7941 
7942 #endif /* SATA_DEBUG */
7943 #endif /* 1 */
7944 
7945 
7946 /* ************************** LOCAL HELPER FUNCTIONS *********************** */
7947 
7948 /*
7949  * Validate sata_tran info
7950  * SATA_FAILURE returns if structure is inconsistent or structure revision
7951  * does not match one used by the framework.
7952  *
7953  * Returns SATA_SUCCESS if sata_hba_tran has matching revision and contains
7954  * required function pointers.
7955  * Returns SATA_FAILURE otherwise.
7956  */
7957 static int
7958 sata_validate_sata_hba_tran(dev_info_t *dip, sata_hba_tran_t *sata_tran)
7959 {
7960 	/*
7961 	 * SATA_TRAN_HBA_REV is the current (highest) revision number
7962 	 * of the SATA interface.
7963 	 */
7964 	if (sata_tran->sata_tran_hba_rev > SATA_TRAN_HBA_REV) {
7965 		sata_log(NULL, CE_WARN,
7966 		    "sata: invalid sata_hba_tran version %d for driver %s",
7967 		    sata_tran->sata_tran_hba_rev, ddi_driver_name(dip));
7968 		return (SATA_FAILURE);
7969 	}
7970 
7971 	if (dip != sata_tran->sata_tran_hba_dip) {
7972 		SATA_LOG_D((NULL, CE_WARN,
7973 		    "sata: inconsistent sata_tran_hba_dip "
7974 		    "%p / %p", sata_tran->sata_tran_hba_dip, dip));
7975 		return (SATA_FAILURE);
7976 	}
7977 
7978 	if (sata_tran->sata_tran_probe_port == NULL ||
7979 	    sata_tran->sata_tran_start == NULL ||
7980 	    sata_tran->sata_tran_abort == NULL ||
7981 	    sata_tran->sata_tran_reset_dport == NULL ||
7982 	    sata_tran->sata_tran_hotplug_ops == NULL ||
7983 	    sata_tran->sata_tran_hotplug_ops->sata_tran_port_activate == NULL ||
7984 	    sata_tran->sata_tran_hotplug_ops->sata_tran_port_deactivate ==
7985 	    NULL) {
7986 		SATA_LOG_D((NULL, CE_WARN, "sata: sata_hba_tran missing "
7987 		    "required functions"));
7988 	}
7989 	return (SATA_SUCCESS);
7990 }
7991 
7992 /*
7993  * Remove HBA instance from sata_hba_list.
7994  */
7995 static void
7996 sata_remove_hba_instance(dev_info_t *dip)
7997 {
7998 	sata_hba_inst_t	*sata_hba_inst;
7999 
8000 	mutex_enter(&sata_mutex);
8001 	for (sata_hba_inst = sata_hba_list;
8002 	    sata_hba_inst != (struct sata_hba_inst *)NULL;
8003 	    sata_hba_inst = sata_hba_inst->satahba_next) {
8004 		if (sata_hba_inst->satahba_dip == dip)
8005 			break;
8006 	}
8007 
8008 	if (sata_hba_inst == (struct sata_hba_inst *)NULL) {
8009 #ifdef SATA_DEBUG
8010 		cmn_err(CE_WARN, "sata_remove_hba_instance: "
8011 		    "unknown HBA instance\n");
8012 #endif
8013 		ASSERT(FALSE);
8014 	}
8015 	if (sata_hba_inst == sata_hba_list) {
8016 		sata_hba_list = sata_hba_inst->satahba_next;
8017 		if (sata_hba_list) {
8018 			sata_hba_list->satahba_prev =
8019 			    (struct sata_hba_inst *)NULL;
8020 		}
8021 		if (sata_hba_inst == sata_hba_list_tail) {
8022 			sata_hba_list_tail = NULL;
8023 		}
8024 	} else if (sata_hba_inst == sata_hba_list_tail) {
8025 		sata_hba_list_tail = sata_hba_inst->satahba_prev;
8026 		if (sata_hba_list_tail) {
8027 			sata_hba_list_tail->satahba_next =
8028 			    (struct sata_hba_inst *)NULL;
8029 		}
8030 	} else {
8031 		sata_hba_inst->satahba_prev->satahba_next =
8032 		    sata_hba_inst->satahba_next;
8033 		sata_hba_inst->satahba_next->satahba_prev =
8034 		    sata_hba_inst->satahba_prev;
8035 	}
8036 	mutex_exit(&sata_mutex);
8037 }
8038 
8039 
8040 
8041 
8042 
8043 /*
8044  * Probe all SATA ports of the specified HBA instance.
8045  * The assumption is that there are no target and attachment point minor nodes
8046  * created by the boot subsystems, so we do not need to prune device tree.
8047  *
8048  * This function is called only from sata_hba_attach(). It does not have to
8049  * be protected by controller mutex, because the hba_attached flag is not set
8050  * yet and no one would be touching this HBA instance other than this thread.
8051  * Determines if port is active and what type of the device is attached
8052  * (if any). Allocates necessary structures for each port.
8053  *
8054  * An AP (Attachement Point) node is created for each SATA device port even
8055  * when there is no device attached.
8056  */
8057 
8058 static 	void
8059 sata_probe_ports(sata_hba_inst_t *sata_hba_inst)
8060 {
8061 	dev_info_t		*dip = SATA_DIP(sata_hba_inst);
8062 	int			ncport, npmport;
8063 	sata_cport_info_t 	*cportinfo;
8064 	sata_drive_info_t	*drive;
8065 	sata_pmult_info_t	*pminfo;
8066 	sata_pmport_info_t 	*pmportinfo;
8067 	sata_device_t		sata_device;
8068 	int			rval;
8069 	dev_t			minor_number;
8070 	char			name[16];
8071 	clock_t			start_time, cur_time;
8072 
8073 	/*
8074 	 * Probe controller ports first, to find port status and
8075 	 * any port multiplier attached.
8076 	 */
8077 	for (ncport = 0; ncport < SATA_NUM_CPORTS(sata_hba_inst); ncport++) {
8078 		/* allocate cport structure */
8079 		cportinfo = kmem_zalloc(sizeof (sata_cport_info_t), KM_SLEEP);
8080 		ASSERT(cportinfo != NULL);
8081 		mutex_init(&cportinfo->cport_mutex, NULL, MUTEX_DRIVER, NULL);
8082 
8083 		mutex_enter(&cportinfo->cport_mutex);
8084 
8085 		cportinfo->cport_addr.cport = ncport;
8086 		cportinfo->cport_addr.pmport = 0;
8087 		cportinfo->cport_addr.qual = SATA_ADDR_CPORT;
8088 		cportinfo->cport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
8089 		cportinfo->cport_state |= SATA_STATE_PROBING;
8090 		SATA_CPORT_INFO(sata_hba_inst, ncport) = cportinfo;
8091 
8092 		/*
8093 		 * Regardless if a port is usable or not, create
8094 		 * an attachment point
8095 		 */
8096 		mutex_exit(&cportinfo->cport_mutex);
8097 		minor_number =
8098 		    SATA_MAKE_AP_MINOR(ddi_get_instance(dip), ncport, 0, 0);
8099 		(void) sprintf(name, "%d", ncport);
8100 		if (ddi_create_minor_node(dip, name, S_IFCHR,
8101 		    minor_number, DDI_NT_SATA_ATTACHMENT_POINT, 0) !=
8102 		    DDI_SUCCESS) {
8103 			sata_log(sata_hba_inst, CE_WARN, "sata_hba_attach: "
8104 			    "cannot create SATA attachment point for port %d",
8105 			    ncport);
8106 		}
8107 
8108 		/* Probe port */
8109 		start_time = ddi_get_lbolt();
8110 	reprobe_cport:
8111 		sata_device.satadev_addr.cport = ncport;
8112 		sata_device.satadev_addr.pmport = 0;
8113 		sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
8114 		sata_device.satadev_rev = SATA_DEVICE_REV;
8115 
8116 		rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
8117 		    (dip, &sata_device);
8118 
8119 		mutex_enter(&cportinfo->cport_mutex);
8120 		sata_update_port_scr(&cportinfo->cport_scr, &sata_device);
8121 		if (rval != SATA_SUCCESS) {
8122 			/* Something went wrong? Fail the port */
8123 			cportinfo->cport_state = SATA_PSTATE_FAILED;
8124 			mutex_exit(&cportinfo->cport_mutex);
8125 			continue;
8126 		}
8127 		cportinfo->cport_state &= ~SATA_STATE_PROBING;
8128 		cportinfo->cport_state |= SATA_STATE_PROBED;
8129 		cportinfo->cport_dev_type = sata_device.satadev_type;
8130 
8131 		cportinfo->cport_state |= SATA_STATE_READY;
8132 		if (cportinfo->cport_dev_type == SATA_DTYPE_NONE) {
8133 			mutex_exit(&cportinfo->cport_mutex);
8134 			continue;
8135 		}
8136 		if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
8137 			/*
8138 			 * There is some device attached.
8139 			 * Allocate device info structure
8140 			 */
8141 			if (SATA_CPORTINFO_DRV_INFO(cportinfo) == NULL) {
8142 				mutex_exit(&cportinfo->cport_mutex);
8143 				SATA_CPORTINFO_DRV_INFO(cportinfo) =
8144 				    kmem_zalloc(sizeof (sata_drive_info_t),
8145 				    KM_SLEEP);
8146 				mutex_enter(&cportinfo->cport_mutex);
8147 			}
8148 			drive = SATA_CPORTINFO_DRV_INFO(cportinfo);
8149 			drive->satadrv_addr = cportinfo->cport_addr;
8150 			drive->satadrv_addr.qual = SATA_ADDR_DCPORT;
8151 			drive->satadrv_type = cportinfo->cport_dev_type;
8152 			drive->satadrv_state = SATA_STATE_UNKNOWN;
8153 
8154 			mutex_exit(&cportinfo->cport_mutex);
8155 			if (sata_add_device(dip, sata_hba_inst, ncport, 0) !=
8156 			    SATA_SUCCESS) {
8157 				/*
8158 				 * Plugged device was not correctly identified.
8159 				 * Retry, within a SATA_DEV_IDENTIFY_TIMEOUT
8160 				 */
8161 				cur_time = ddi_get_lbolt();
8162 				if ((cur_time - start_time) <
8163 				    drv_usectohz(SATA_DEV_IDENTIFY_TIMEOUT)) {
8164 					/* sleep for a while */
8165 					delay(drv_usectohz(
8166 					    SATA_DEV_RETRY_DLY));
8167 					goto reprobe_cport;
8168 				}
8169 			}
8170 		} else {
8171 			mutex_exit(&cportinfo->cport_mutex);
8172 			ASSERT(cportinfo->cport_dev_type == SATA_DTYPE_PMULT);
8173 			pminfo = kmem_zalloc(sizeof (sata_pmult_info_t),
8174 			    KM_SLEEP);
8175 			mutex_enter(&cportinfo->cport_mutex);
8176 			ASSERT(pminfo != NULL);
8177 			SATA_CPORTINFO_PMULT_INFO(cportinfo) = pminfo;
8178 			pminfo->pmult_addr.cport = cportinfo->cport_addr.cport;
8179 			pminfo->pmult_addr.pmport = SATA_PMULT_HOSTPORT;
8180 			pminfo->pmult_addr.qual = SATA_ADDR_PMPORT;
8181 			pminfo->pmult_num_dev_ports =
8182 			    sata_device.satadev_add_info;
8183 			mutex_init(&pminfo->pmult_mutex, NULL, MUTEX_DRIVER,
8184 			    NULL);
8185 			pminfo->pmult_state = SATA_STATE_PROBING;
8186 			mutex_exit(&cportinfo->cport_mutex);
8187 
8188 			/* Probe Port Multiplier ports */
8189 			for (npmport = 0;
8190 			    npmport < pminfo->pmult_num_dev_ports;
8191 			    npmport++) {
8192 				pmportinfo = kmem_zalloc(
8193 				    sizeof (sata_pmport_info_t), KM_SLEEP);
8194 				mutex_enter(&cportinfo->cport_mutex);
8195 				ASSERT(pmportinfo != NULL);
8196 				pmportinfo->pmport_addr.cport = ncport;
8197 				pmportinfo->pmport_addr.pmport = npmport;
8198 				pmportinfo->pmport_addr.qual =
8199 				    SATA_ADDR_PMPORT;
8200 				pminfo->pmult_dev_port[npmport] = pmportinfo;
8201 
8202 				mutex_init(&pmportinfo->pmport_mutex, NULL,
8203 				    MUTEX_DRIVER, NULL);
8204 
8205 				mutex_exit(&cportinfo->cport_mutex);
8206 
8207 				/* Create an attachment point */
8208 				minor_number = SATA_MAKE_AP_MINOR(
8209 				    ddi_get_instance(dip), ncport, npmport, 1);
8210 				(void) sprintf(name, "%d.%d", ncport, npmport);
8211 				if (ddi_create_minor_node(dip, name, S_IFCHR,
8212 				    minor_number, DDI_NT_SATA_ATTACHMENT_POINT,
8213 				    0) != DDI_SUCCESS) {
8214 					sata_log(sata_hba_inst, CE_WARN,
8215 					    "sata_hba_attach: "
8216 					    "cannot create SATA attachment "
8217 					    "point for port %d pmult port %d",
8218 					    ncport, npmport);
8219 				}
8220 
8221 				start_time = ddi_get_lbolt();
8222 			reprobe_pmport:
8223 				sata_device.satadev_addr.pmport = npmport;
8224 				sata_device.satadev_addr.qual =
8225 				    SATA_ADDR_PMPORT;
8226 
8227 				rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
8228 				    (dip, &sata_device);
8229 				mutex_enter(&cportinfo->cport_mutex);
8230 
8231 				/* sata_update_port_info() */
8232 				sata_update_port_scr(&pmportinfo->pmport_scr,
8233 				    &sata_device);
8234 
8235 				if (rval != SATA_SUCCESS) {
8236 					pmportinfo->pmport_state =
8237 					    SATA_PSTATE_FAILED;
8238 					mutex_exit(&cportinfo->cport_mutex);
8239 					continue;
8240 				}
8241 				pmportinfo->pmport_state &=
8242 				    ~SATA_STATE_PROBING;
8243 				pmportinfo->pmport_state |= SATA_STATE_PROBED;
8244 				pmportinfo->pmport_dev_type =
8245 				    sata_device.satadev_type;
8246 
8247 				pmportinfo->pmport_state |= SATA_STATE_READY;
8248 				if (pmportinfo->pmport_dev_type ==
8249 				    SATA_DTYPE_NONE) {
8250 					mutex_exit(&cportinfo->cport_mutex);
8251 					continue;
8252 				}
8253 				/* Port multipliers cannot be chained */
8254 				ASSERT(pmportinfo->pmport_dev_type !=
8255 				    SATA_DTYPE_PMULT);
8256 				/*
8257 				 * There is something attached to Port
8258 				 * Multiplier device port
8259 				 * Allocate device info structure
8260 				 */
8261 				if (pmportinfo->pmport_sata_drive == NULL) {
8262 					mutex_exit(&cportinfo->cport_mutex);
8263 					pmportinfo->pmport_sata_drive =
8264 					    kmem_zalloc(
8265 					    sizeof (sata_drive_info_t),
8266 					    KM_SLEEP);
8267 					mutex_enter(&cportinfo->cport_mutex);
8268 				}
8269 				drive = pmportinfo->pmport_sata_drive;
8270 				drive->satadrv_addr.cport =
8271 				    pmportinfo->pmport_addr.cport;
8272 				drive->satadrv_addr.pmport = npmport;
8273 				drive->satadrv_addr.qual = SATA_ADDR_DPMPORT;
8274 				drive->satadrv_type = pmportinfo->
8275 				    pmport_dev_type;
8276 				drive->satadrv_state = SATA_STATE_UNKNOWN;
8277 
8278 				mutex_exit(&cportinfo->cport_mutex);
8279 				if (sata_add_device(dip, sata_hba_inst, ncport,
8280 				    npmport) != SATA_SUCCESS) {
8281 					/*
8282 					 * Plugged device was not correctly
8283 					 * identified. Retry, within the
8284 					 * SATA_DEV_IDENTIFY_TIMEOUT
8285 					 */
8286 					cur_time = ddi_get_lbolt();
8287 					if ((cur_time - start_time) <
8288 					    drv_usectohz(
8289 					    SATA_DEV_IDENTIFY_TIMEOUT)) {
8290 						/* sleep for a while */
8291 						delay(drv_usectohz(
8292 						    SATA_DEV_RETRY_DLY));
8293 						goto reprobe_pmport;
8294 					}
8295 				}
8296 			}
8297 			pmportinfo->pmport_state =
8298 			    SATA_STATE_PROBED | SATA_STATE_READY;
8299 		}
8300 	}
8301 }
8302 
8303 /*
8304  * Add SATA device for specified HBA instance & port (SCSI target
8305  * device nodes).
8306  * This function is called (indirectly) only from sata_hba_attach().
8307  * A target node is created when there is a supported type device attached,
8308  * but may be removed if it cannot be put online.
8309  *
8310  * This function cannot be called from an interrupt context.
8311  *
8312  * ONLY DISK TARGET NODES ARE CREATED NOW
8313  *
8314  * Returns SATA_SUCCESS when port/device was fully processed, SATA_FAILURE when
8315  * device identification failed - adding a device could be retried.
8316  *
8317  */
8318 static 	int
8319 sata_add_device(dev_info_t *pdip, sata_hba_inst_t *sata_hba_inst, int cport,
8320     int pmport)
8321 {
8322 	sata_cport_info_t 	*cportinfo;
8323 	sata_pmult_info_t	*pminfo;
8324 	sata_pmport_info_t	*pmportinfo;
8325 	dev_info_t		*cdip;		/* child dip */
8326 	sata_device_t		sata_device;
8327 	int			rval;
8328 
8329 
8330 
8331 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
8332 	ASSERT(cportinfo->cport_dev_type != SATA_DTYPE_NONE);
8333 	mutex_enter(&cportinfo->cport_mutex);
8334 	/*
8335 	 * Some device is attached to a controller port.
8336 	 * We rely on controllers distinquishing between no-device,
8337 	 * attached port multiplier and other kind of attached device.
8338 	 * We need to get Identify Device data and determine
8339 	 * positively the dev type before trying to attach
8340 	 * the target driver.
8341 	 */
8342 	sata_device.satadev_rev = SATA_DEVICE_REV;
8343 	if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
8344 		/*
8345 		 * Not port multiplier.
8346 		 */
8347 		sata_device.satadev_addr = cportinfo->cport_addr;
8348 		sata_device.satadev_addr.qual = SATA_ADDR_DCPORT;
8349 		mutex_exit(&cportinfo->cport_mutex);
8350 
8351 		rval = sata_probe_device(sata_hba_inst, &sata_device);
8352 		if (rval != SATA_SUCCESS ||
8353 		    sata_device.satadev_type == SATA_DTYPE_UNKNOWN)
8354 			return (SATA_FAILURE);
8355 
8356 		mutex_enter(&cportinfo->cport_mutex);
8357 		sata_show_drive_info(sata_hba_inst,
8358 		    SATA_CPORTINFO_DRV_INFO(cportinfo));
8359 
8360 		if ((sata_device.satadev_type & SATA_VALID_DEV_TYPE) == 0) {
8361 			/*
8362 			 * Could not determine device type or
8363 			 * a device is not supported.
8364 			 * Degrade this device to unknown.
8365 			 */
8366 			cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
8367 			mutex_exit(&cportinfo->cport_mutex);
8368 			return (SATA_SUCCESS);
8369 		}
8370 		cportinfo->cport_dev_type = sata_device.satadev_type;
8371 		cportinfo->cport_tgtnode_clean = B_TRUE;
8372 		mutex_exit(&cportinfo->cport_mutex);
8373 
8374 		/*
8375 		 * Initialize device to the desired state. Even if it
8376 		 * fails, the device will still attach but syslog
8377 		 * will show the warning.
8378 		 */
8379 		if (sata_initialize_device(sata_hba_inst,
8380 		    SATA_CPORTINFO_DRV_INFO(cportinfo)) != SATA_SUCCESS) {
8381 			/* Retry */
8382 			rval = sata_initialize_device(sata_hba_inst,
8383 			    SATA_CPORTINFO_DRV_INFO(cportinfo));
8384 
8385 			if (rval == SATA_RETRY)
8386 				sata_log(sata_hba_inst, CE_WARN,
8387 				    "SATA device at port %d - "
8388 				    "default device features could not be set."
8389 				    " Device may not operate as expected.",
8390 				    cportinfo->cport_addr.cport);
8391 		}
8392 
8393 		cdip = sata_create_target_node(pdip, sata_hba_inst,
8394 		    &sata_device.satadev_addr);
8395 		mutex_enter(&cportinfo->cport_mutex);
8396 		if (cdip == NULL) {
8397 			/*
8398 			 * Attaching target node failed.
8399 			 * We retain sata_drive_info structure...
8400 			 */
8401 			mutex_exit(&cportinfo->cport_mutex);
8402 			return (SATA_SUCCESS);
8403 		}
8404 		(SATA_CPORTINFO_DRV_INFO(cportinfo))->
8405 		    satadrv_state = SATA_STATE_READY;
8406 	} else {
8407 		/* This must be Port Multiplier type */
8408 		if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
8409 			SATA_LOG_D((sata_hba_inst, CE_WARN,
8410 			    "sata_add_device: "
8411 			    "unrecognized dev type %x",
8412 			    cportinfo->cport_dev_type));
8413 			mutex_exit(&cportinfo->cport_mutex);
8414 			return (SATA_SUCCESS);
8415 		}
8416 		pminfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
8417 		pmportinfo = pminfo->pmult_dev_port[pmport];
8418 		sata_device.satadev_addr = pmportinfo->pmport_addr;
8419 		sata_device.satadev_addr.qual = SATA_ADDR_DPMPORT;
8420 		mutex_exit(&cportinfo->cport_mutex);
8421 
8422 		rval = sata_probe_device(sata_hba_inst, &sata_device);
8423 		if (rval != SATA_SUCCESS ||
8424 		    sata_device.satadev_type == SATA_DTYPE_UNKNOWN) {
8425 			return (SATA_FAILURE);
8426 		}
8427 		mutex_enter(&cportinfo->cport_mutex);
8428 		sata_show_drive_info(sata_hba_inst,
8429 		    SATA_CPORTINFO_DRV_INFO(cportinfo));
8430 
8431 		if ((sata_device.satadev_type & SATA_VALID_DEV_TYPE) == 0) {
8432 			/*
8433 			 * Could not determine device type.
8434 			 * Degrade this device to unknown.
8435 			 */
8436 			pmportinfo->pmport_dev_type = SATA_DTYPE_UNKNOWN;
8437 			mutex_exit(&cportinfo->cport_mutex);
8438 			return (SATA_SUCCESS);
8439 		}
8440 		pmportinfo->pmport_dev_type = sata_device.satadev_type;
8441 		pmportinfo->pmport_tgtnode_clean = B_TRUE;
8442 		mutex_exit(&cportinfo->cport_mutex);
8443 
8444 		/*
8445 		 * Initialize device to the desired state.
8446 		 * Even if it fails, the device will still
8447 		 * attach but syslog will show the warning.
8448 		 */
8449 		if (sata_initialize_device(sata_hba_inst,
8450 		    pmportinfo->pmport_sata_drive) != SATA_SUCCESS) {
8451 			/* Retry */
8452 			rval = sata_initialize_device(sata_hba_inst,
8453 			    pmportinfo->pmport_sata_drive);
8454 
8455 			if (rval == SATA_RETRY)
8456 				sata_log(sata_hba_inst, CE_WARN,
8457 				    "SATA device at port %d pmport %d - "
8458 				    "default device features could not be set."
8459 				    " Device may not operate as expected.",
8460 				    pmportinfo->pmport_addr.cport,
8461 				    pmportinfo->pmport_addr.pmport);
8462 		}
8463 		cdip = sata_create_target_node(pdip, sata_hba_inst,
8464 		    &sata_device.satadev_addr);
8465 		mutex_enter(&cportinfo->cport_mutex);
8466 		if (cdip == NULL) {
8467 			/*
8468 			 * Attaching target node failed.
8469 			 * We retain sata_drive_info structure...
8470 			 */
8471 			mutex_exit(&cportinfo->cport_mutex);
8472 			return (SATA_SUCCESS);
8473 		}
8474 		pmportinfo->pmport_sata_drive->satadrv_state |=
8475 		    SATA_STATE_READY;
8476 	}
8477 	mutex_exit(&cportinfo->cport_mutex);
8478 	return (SATA_SUCCESS);
8479 }
8480 
8481 
8482 
8483 /*
8484  * Create scsi target node for attached device, create node properties and
8485  * attach the node.
8486  * The node could be removed if the device onlining fails.
8487  *
8488  * A dev_info_t pointer is returned if operation is successful, NULL is
8489  * returned otherwise.
8490  *
8491  * No port multiplier support.
8492  */
8493 
8494 static dev_info_t *
8495 sata_create_target_node(dev_info_t *dip, sata_hba_inst_t *sata_hba_inst,
8496 			sata_address_t *sata_addr)
8497 {
8498 	dev_info_t *cdip = NULL;
8499 	int rval;
8500 	char *nname = NULL;
8501 	char **compatible = NULL;
8502 	int ncompatible;
8503 	struct scsi_inquiry inq;
8504 	sata_device_t sata_device;
8505 	sata_drive_info_t *sdinfo;
8506 	int target;
8507 	int i;
8508 
8509 	sata_device.satadev_rev = SATA_DEVICE_REV;
8510 	sata_device.satadev_addr = *sata_addr;
8511 
8512 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, sata_addr->cport)));
8513 
8514 	sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
8515 
8516 	target = SATA_TO_SCSI_TARGET(sata_addr->cport,
8517 	    sata_addr->pmport, sata_addr->qual);
8518 
8519 	if (sdinfo == NULL) {
8520 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
8521 		    sata_addr->cport)));
8522 		SATA_LOG_D((sata_hba_inst, CE_WARN,
8523 		    "sata_create_target_node: no sdinfo for target %x",
8524 		    target));
8525 		return (NULL);
8526 	}
8527 
8528 	/*
8529 	 * create or get scsi inquiry data, expected by
8530 	 * scsi_hba_nodename_compatible_get()
8531 	 * SATA hard disks get Identify Data translated into Inguiry Data.
8532 	 * ATAPI devices respond directly to Inquiry request.
8533 	 */
8534 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
8535 		sata_identdev_to_inquiry(sata_hba_inst, sdinfo,
8536 		    (uint8_t *)&inq);
8537 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
8538 		    sata_addr->cport)));
8539 	} else { /* Assume supported ATAPI device */
8540 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
8541 		    sata_addr->cport)));
8542 		if (sata_get_atapi_inquiry_data(sata_hba_inst, sata_addr,
8543 		    &inq) == SATA_FAILURE)
8544 			return (NULL);
8545 		/*
8546 		 * Save supported ATAPI transport version
8547 		 */
8548 		sdinfo->satadrv_atapi_trans_ver =
8549 		    SATA_ATAPI_TRANS_VERSION(&inq);
8550 	}
8551 
8552 	/* determine the node name and compatible */
8553 	scsi_hba_nodename_compatible_get(&inq, NULL,
8554 	    inq.inq_dtype, NULL, &nname, &compatible, &ncompatible);
8555 
8556 #ifdef SATA_DEBUG
8557 	if (sata_debug_flags & SATA_DBG_NODES) {
8558 		if (nname == NULL) {
8559 			cmn_err(CE_NOTE, "sata_create_target_node: "
8560 			    "cannot determine nodename for target %d\n",
8561 			    target);
8562 		} else {
8563 			cmn_err(CE_WARN, "sata_create_target_node: "
8564 			    "target %d nodename: %s\n", target, nname);
8565 		}
8566 		if (compatible == NULL) {
8567 			cmn_err(CE_WARN,
8568 			    "sata_create_target_node: no compatible name\n");
8569 		} else {
8570 			for (i = 0; i < ncompatible; i++) {
8571 				cmn_err(CE_WARN, "sata_create_target_node: "
8572 				    "compatible name: %s\n", compatible[i]);
8573 			}
8574 		}
8575 	}
8576 #endif
8577 
8578 	/* if nodename can't be determined, log error and exit */
8579 	if (nname == NULL) {
8580 		SATA_LOG_D((sata_hba_inst, CE_WARN,
8581 		    "sata_create_target_node: cannot determine nodename "
8582 		    "for target %d\n", target));
8583 		scsi_hba_nodename_compatible_free(nname, compatible);
8584 		return (NULL);
8585 	}
8586 	/*
8587 	 * Create scsi target node
8588 	 */
8589 	ndi_devi_alloc_sleep(dip, nname, (pnode_t)DEVI_SID_NODEID, &cdip);
8590 	rval = ndi_prop_update_string(DDI_DEV_T_NONE, cdip,
8591 	    "device-type", "scsi");
8592 
8593 	if (rval != DDI_PROP_SUCCESS) {
8594 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
8595 		    "updating device_type prop failed %d", rval));
8596 		goto fail;
8597 	}
8598 
8599 	/*
8600 	 * Create target node properties: target & lun
8601 	 */
8602 	rval = ndi_prop_update_int(DDI_DEV_T_NONE, cdip, "target", target);
8603 	if (rval != DDI_PROP_SUCCESS) {
8604 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
8605 		    "updating target prop failed %d", rval));
8606 		goto fail;
8607 	}
8608 	rval = ndi_prop_update_int(DDI_DEV_T_NONE, cdip, "lun", 0);
8609 	if (rval != DDI_PROP_SUCCESS) {
8610 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
8611 		    "updating target prop failed %d", rval));
8612 		goto fail;
8613 	}
8614 
8615 	if (sdinfo->satadrv_type & SATA_DTYPE_ATAPI) {
8616 		/*
8617 		 * Add "variant" property
8618 		 */
8619 		rval = ndi_prop_update_string(DDI_DEV_T_NONE, cdip,
8620 		    "variant", "atapi");
8621 		if (rval != DDI_PROP_SUCCESS) {
8622 			SATA_LOG_D((sata_hba_inst, CE_WARN,
8623 			    "sata_create_target_node: variant atapi "
8624 			    "property could not be created: %d", rval));
8625 			goto fail;
8626 		}
8627 	}
8628 	/* decorate the node with compatible */
8629 	if (ndi_prop_update_string_array(DDI_DEV_T_NONE, cdip, "compatible",
8630 	    compatible, ncompatible) != DDI_PROP_SUCCESS) {
8631 		SATA_LOG_D((sata_hba_inst, CE_WARN,
8632 		    "sata_create_target_node: FAIL compatible props cdip 0x%p",
8633 		    (void *)cdip));
8634 		goto fail;
8635 	}
8636 
8637 
8638 	/*
8639 	 * Now, try to attach the driver. If probing of the device fails,
8640 	 * the target node may be removed
8641 	 */
8642 	rval = ndi_devi_online(cdip, NDI_ONLINE_ATTACH);
8643 
8644 	scsi_hba_nodename_compatible_free(nname, compatible);
8645 
8646 	if (rval == NDI_SUCCESS)
8647 		return (cdip);
8648 
8649 	/* target node was removed - are we sure? */
8650 	return (NULL);
8651 
8652 fail:
8653 	scsi_hba_nodename_compatible_free(nname, compatible);
8654 	ddi_prop_remove_all(cdip);
8655 	rval = ndi_devi_free(cdip);
8656 	if (rval != NDI_SUCCESS) {
8657 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
8658 		    "node removal failed %d", rval));
8659 	}
8660 	sata_log(sata_hba_inst, CE_WARN, "sata_create_target_node: "
8661 	    "cannot create target node for SATA device at port %d",
8662 	    sata_addr->cport);
8663 	return (NULL);
8664 }
8665 
8666 
8667 
8668 /*
8669  * Re-probe sata port, check for a device and attach info
8670  * structures when necessary. Identify Device data is fetched, if possible.
8671  * Assumption: sata address is already validated.
8672  * SATA_SUCCESS is returned if port is re-probed sucessfully, regardless of
8673  * the presence of a device and its type.
8674  *
8675  * flag arg specifies that the function should try multiple times to identify
8676  * device type and to initialize it, or it should return immediately on failure.
8677  * SATA_DEV_IDENTIFY_RETRY - retry
8678  * SATA_DEV_IDENTIFY_NORETRY - no retry
8679  *
8680  * SATA_FAILURE is returned if one of the operations failed.
8681  *
8682  * This function cannot be called in interrupt context - it may sleep.
8683  *
8684  * NOte: Port multiplier is not supported yet, although there may be some
8685  * pieces of code referencing to it.
8686  */
8687 static int
8688 sata_reprobe_port(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device,
8689     int flag)
8690 {
8691 	sata_cport_info_t *cportinfo;
8692 	sata_drive_info_t *sdinfo, *osdinfo;
8693 	boolean_t init_device = B_FALSE;
8694 	int prev_device_type = SATA_DTYPE_NONE;
8695 	int prev_device_settings = 0;
8696 	int prev_device_state = 0;
8697 	clock_t start_time;
8698 	int retry = B_FALSE;
8699 	int rval_probe, rval_init;
8700 
8701 	/* We only care about host sata cport for now */
8702 	cportinfo = SATA_CPORT_INFO(sata_hba_inst,
8703 	    sata_device->satadev_addr.cport);
8704 	osdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
8705 	if (osdinfo != NULL) {
8706 		/*
8707 		 * We are re-probing port with a previously attached device.
8708 		 * Save previous device type and settings.
8709 		 */
8710 		prev_device_type = cportinfo->cport_dev_type;
8711 		prev_device_settings = osdinfo->satadrv_settings;
8712 		prev_device_state = osdinfo->satadrv_state;
8713 	}
8714 	if (flag == SATA_DEV_IDENTIFY_RETRY) {
8715 		start_time = ddi_get_lbolt();
8716 		retry = B_TRUE;
8717 	}
8718 retry_probe:
8719 
8720 	/* probe port */
8721 	mutex_enter(&cportinfo->cport_mutex);
8722 	cportinfo->cport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
8723 	cportinfo->cport_state |= SATA_STATE_PROBING;
8724 	mutex_exit(&cportinfo->cport_mutex);
8725 
8726 	rval_probe = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
8727 	    (SATA_DIP(sata_hba_inst), sata_device);
8728 
8729 	mutex_enter(&cportinfo->cport_mutex);
8730 	if (rval_probe != SATA_SUCCESS) {
8731 		cportinfo->cport_state = SATA_PSTATE_FAILED;
8732 		mutex_exit(&cportinfo->cport_mutex);
8733 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_reprobe_port: "
8734 		    "SATA port %d probing failed",
8735 		    cportinfo->cport_addr.cport));
8736 		return (SATA_FAILURE);
8737 	}
8738 
8739 	/*
8740 	 * update sata port state and set device type
8741 	 */
8742 	sata_update_port_info(sata_hba_inst, sata_device);
8743 	cportinfo->cport_state &= ~SATA_STATE_PROBING;
8744 
8745 	/*
8746 	 * Sanity check - Port is active? Is the link active?
8747 	 * Is there any device attached?
8748 	 */
8749 	if ((cportinfo->cport_state &
8750 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
8751 	    (cportinfo->cport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
8752 	    SATA_PORT_DEVLINK_UP) {
8753 		/*
8754 		 * Port in non-usable state or no link active/no device.
8755 		 * Free info structure if necessary (direct attached drive
8756 		 * only, for now!
8757 		 */
8758 		sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
8759 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
8760 		/* Add here differentiation for device attached or not */
8761 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
8762 		mutex_exit(&cportinfo->cport_mutex);
8763 		if (sdinfo != NULL)
8764 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
8765 		return (SATA_SUCCESS);
8766 	}
8767 
8768 	cportinfo->cport_state |= SATA_STATE_READY;
8769 	cportinfo->cport_dev_type = sata_device->satadev_type;
8770 	sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
8771 
8772 	/*
8773 	 * If we are re-probing the port, there may be
8774 	 * sata_drive_info structure attached
8775 	 * (or sata_pm_info, if PMult is supported).
8776 	 */
8777 	if (sata_device->satadev_type == SATA_DTYPE_NONE) {
8778 		/*
8779 		 * There is no device, so remove device info structure,
8780 		 * if necessary.
8781 		 * Only direct attached drive is considered now, until
8782 		 * port multiplier is supported. If the previously
8783 		 * attached device was a port multiplier, we would need
8784 		 * to take care of devices attached beyond the port
8785 		 * multiplier.
8786 		 */
8787 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
8788 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
8789 		if (sdinfo != NULL) {
8790 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
8791 			sata_log(sata_hba_inst, CE_WARN,
8792 			    "SATA device detached "
8793 			    "from port %d", cportinfo->cport_addr.cport);
8794 		}
8795 		mutex_exit(&cportinfo->cport_mutex);
8796 		return (SATA_SUCCESS);
8797 	}
8798 
8799 	if (sata_device->satadev_type != SATA_DTYPE_PMULT) {
8800 		if (sdinfo == NULL) {
8801 			/*
8802 			 * There is some device attached, but there is
8803 			 * no sata_drive_info structure - allocate one
8804 			 */
8805 			mutex_exit(&cportinfo->cport_mutex);
8806 			sdinfo = kmem_zalloc(
8807 			    sizeof (sata_drive_info_t), KM_SLEEP);
8808 			mutex_enter(&cportinfo->cport_mutex);
8809 			/*
8810 			 * Recheck, that the port state did not change when we
8811 			 * released mutex.
8812 			 */
8813 			if (cportinfo->cport_state & SATA_STATE_READY) {
8814 				SATA_CPORTINFO_DRV_INFO(cportinfo) = sdinfo;
8815 				sdinfo->satadrv_addr = cportinfo->cport_addr;
8816 				sdinfo->satadrv_addr.qual = SATA_ADDR_DCPORT;
8817 				sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
8818 				sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
8819 			} else {
8820 				/*
8821 				 * Port is not in ready state, we
8822 				 * cannot attach a device.
8823 				 */
8824 				mutex_exit(&cportinfo->cport_mutex);
8825 				kmem_free(sdinfo, sizeof (sata_drive_info_t));
8826 				return (SATA_SUCCESS);
8827 			}
8828 			/*
8829 			 * Since we are adding device, presumably new one,
8830 			 * indicate that it  should be initalized,
8831 			 * as well as some internal framework states).
8832 			 */
8833 			init_device = B_TRUE;
8834 		}
8835 		cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
8836 		sata_device->satadev_addr.qual = sdinfo->satadrv_addr.qual;
8837 	} else {
8838 		/*
8839 		 * The device is a port multiplier - not handled now.
8840 		 */
8841 		cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
8842 		mutex_exit(&cportinfo->cport_mutex);
8843 		return (SATA_SUCCESS);
8844 	}
8845 	mutex_exit(&cportinfo->cport_mutex);
8846 	/*
8847 	 * Figure out what kind of device we are really
8848 	 * dealing with. Failure of identifying device does not fail this
8849 	 * function.
8850 	 */
8851 	rval_probe = sata_probe_device(sata_hba_inst, sata_device);
8852 	rval_init = SATA_FAILURE;
8853 	mutex_enter(&cportinfo->cport_mutex);
8854 	if (rval_probe == SATA_SUCCESS) {
8855 		/*
8856 		 * If we are dealing with the same type of a device as before,
8857 		 * restore its settings flags.
8858 		 */
8859 		if (osdinfo != NULL &&
8860 		    sata_device->satadev_type == prev_device_type)
8861 			sdinfo->satadrv_settings = prev_device_settings;
8862 
8863 		mutex_exit(&cportinfo->cport_mutex);
8864 		rval_init = SATA_SUCCESS;
8865 		/* Set initial device features, if necessary */
8866 		if (init_device == B_TRUE) {
8867 			rval_init = sata_initialize_device(sata_hba_inst,
8868 			    sdinfo);
8869 		}
8870 		if (rval_init == SATA_SUCCESS)
8871 			return (rval_init);
8872 		/* else we will retry if retry was asked for */
8873 
8874 	} else {
8875 		/*
8876 		 * If there was some device info before we probe the device,
8877 		 * restore previous device setting, so we can retry from scratch
8878 		 * later. Providing, of course, that device has not disapear
8879 		 * during probing process.
8880 		 */
8881 		if (sata_device->satadev_type != SATA_DTYPE_NONE) {
8882 			if (osdinfo != NULL) {
8883 				cportinfo->cport_dev_type = prev_device_type;
8884 				sdinfo->satadrv_type = prev_device_type;
8885 				sdinfo->satadrv_state = prev_device_state;
8886 			}
8887 		} else {
8888 			/* device is gone */
8889 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
8890 			cportinfo->cport_dev_type = SATA_DTYPE_NONE;
8891 			SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
8892 			mutex_exit(&cportinfo->cport_mutex);
8893 			return (SATA_SUCCESS);
8894 		}
8895 		mutex_exit(&cportinfo->cport_mutex);
8896 	}
8897 
8898 	if (retry) {
8899 		clock_t cur_time = ddi_get_lbolt();
8900 		/*
8901 		 * A device was not successfully identified or initialized.
8902 		 * Track retry time for device identification.
8903 		 */
8904 		if ((cur_time - start_time) <
8905 		    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
8906 			/* sleep for a while */
8907 			delay(drv_usectohz(SATA_DEV_RETRY_DLY));
8908 			goto retry_probe;
8909 		}
8910 		/* else no more retries */
8911 		mutex_enter(&cportinfo->cport_mutex);
8912 		if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
8913 			if (rval_init == SATA_RETRY) {
8914 				/*
8915 				 * Setting drive features have failed, but
8916 				 * because the drive is still accessible,
8917 				 * keep it and emit a warning message.
8918 				 */
8919 				sata_log(sata_hba_inst, CE_WARN,
8920 				    "SATA device at port %d - desired "
8921 				    "drive features could not be set. "
8922 				    "Device may not operate as expected.",
8923 				    cportinfo->cport_addr.cport);
8924 			} else {
8925 				SATA_CPORTINFO_DRV_INFO(cportinfo)->
8926 				    satadrv_state = SATA_DSTATE_FAILED;
8927 			}
8928 		}
8929 		mutex_exit(&cportinfo->cport_mutex);
8930 	}
8931 	return (SATA_SUCCESS);
8932 }
8933 
8934 /*
8935  * Initialize device
8936  * Specified device is initialized to a default state.
8937  *
8938  * Returns SATA_SUCCESS if all device features are set successfully,
8939  * SATA_RETRY if device is accessible but device features were not set
8940  * successfully, and SATA_FAILURE otherwise.
8941  */
8942 static int
8943 sata_initialize_device(sata_hba_inst_t *sata_hba_inst,
8944     sata_drive_info_t *sdinfo)
8945 {
8946 	int rval;
8947 
8948 	sata_save_drive_settings(sdinfo);
8949 
8950 	sdinfo->satadrv_settings |= SATA_DEV_READ_AHEAD;
8951 
8952 	sata_init_write_cache_mode(sdinfo);
8953 
8954 	rval = sata_set_drive_features(sata_hba_inst, sdinfo, 0);
8955 
8956 	/* Determine current data transfer mode */
8957 	if ((sdinfo->satadrv_id.ai_cap & SATA_DMA_SUPPORT) == 0) {
8958 		sdinfo->satadrv_settings &= ~SATA_DEV_DMA;
8959 	} else if ((sdinfo->satadrv_id.ai_validinfo &
8960 	    SATA_VALIDINFO_88) != 0 &&
8961 	    (sdinfo->satadrv_id.ai_ultradma & SATA_UDMA_SEL_MASK) != 0) {
8962 		sdinfo->satadrv_settings |= SATA_DEV_DMA;
8963 	} else if ((sdinfo->satadrv_id.ai_dworddma &
8964 	    SATA_MDMA_SEL_MASK) != 0) {
8965 		sdinfo->satadrv_settings |= SATA_DEV_DMA;
8966 	} else
8967 		/* DMA supported, not no DMA transfer mode is selected !? */
8968 		sdinfo->satadrv_settings &= ~SATA_DEV_DMA;
8969 
8970 	return (rval);
8971 }
8972 
8973 
8974 /*
8975  * Initialize write cache mode.
8976  *
8977  * The default write cache setting for SATA HDD is provided by sata_write_cache
8978  * static variable. ATAPI CD/DVDs devices have write cache default is
8979  * determined by sata_atapicdvd_write_cache static variable.
8980  * ATAPI tape devices have write cache default is determined by
8981  * sata_atapitape_write_cache static variable.
8982  * ATAPI disk devices have write cache default is determined by
8983  * sata_atapidisk_write_cache static variable.
8984  * 1 - enable
8985  * 0 - disable
8986  * any other value - current drive setting
8987  *
8988  * Although there is not reason to disable write cache on CD/DVD devices,
8989  * tape devices and ATAPI disk devices, the default setting control is provided
8990  * for the maximun flexibility.
8991  *
8992  * In the future, it may be overridden by the
8993  * disk-write-cache-enable property setting, if it is defined.
8994  * Returns SATA_SUCCESS if all device features are set successfully,
8995  * SATA_FAILURE otherwise.
8996  */
8997 static void
8998 sata_init_write_cache_mode(sata_drive_info_t *sdinfo)
8999 {
9000 	switch (sdinfo->satadrv_type) {
9001 	case SATA_DTYPE_ATADISK:
9002 		if (sata_write_cache == 1)
9003 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
9004 		else if (sata_write_cache == 0)
9005 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
9006 		/*
9007 		 * When sata_write_cache value is not 0 or 1,
9008 		 * a current setting of the drive's write cache is used.
9009 		 */
9010 		break;
9011 	case SATA_DTYPE_ATAPICD:
9012 		if (sata_atapicdvd_write_cache == 1)
9013 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
9014 		else if (sata_atapicdvd_write_cache == 0)
9015 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
9016 		/*
9017 		 * When sata_atapicdvd_write_cache value is not 0 or 1,
9018 		 * a current setting of the drive's write cache is used.
9019 		 */
9020 		break;
9021 	case SATA_DTYPE_ATAPITAPE:
9022 		if (sata_atapitape_write_cache == 1)
9023 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
9024 		else if (sata_atapitape_write_cache == 0)
9025 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
9026 		/*
9027 		 * When sata_atapitape_write_cache value is not 0 or 1,
9028 		 * a current setting of the drive's write cache is used.
9029 		 */
9030 		break;
9031 	case SATA_DTYPE_ATAPIDISK:
9032 		if (sata_atapidisk_write_cache == 1)
9033 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
9034 		else if (sata_atapidisk_write_cache == 0)
9035 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
9036 		/*
9037 		 * When sata_atapidisk_write_cache value is not 0 or 1,
9038 		 * a current setting of the drive's write cache is used.
9039 		 */
9040 		break;
9041 	}
9042 }
9043 
9044 
9045 /*
9046  * Validate sata address.
9047  * Specified cport, pmport and qualifier has to match
9048  * passed sata_scsi configuration info.
9049  * The presence of an attached device is not verified.
9050  *
9051  * Returns 0 when address is valid, -1 otherwise.
9052  */
9053 static int
9054 sata_validate_sata_address(sata_hba_inst_t *sata_hba_inst, int cport,
9055 	int pmport, int qual)
9056 {
9057 	if (qual == SATA_ADDR_DCPORT && pmport != 0)
9058 		goto invalid_address;
9059 	if (cport >= SATA_NUM_CPORTS(sata_hba_inst))
9060 		goto invalid_address;
9061 	if ((qual == SATA_ADDR_DPMPORT || qual == SATA_ADDR_PMPORT) &&
9062 	    ((SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) != SATA_DTYPE_PMULT) ||
9063 	    (SATA_PMULT_INFO(sata_hba_inst, cport) == NULL) ||
9064 	    (pmport >= SATA_NUM_PMPORTS(sata_hba_inst, cport))))
9065 		goto invalid_address;
9066 
9067 	return (0);
9068 
9069 invalid_address:
9070 	return (-1);
9071 
9072 }
9073 
9074 /*
9075  * Validate scsi address
9076  * SCSI target address is translated into SATA cport/pmport and compared
9077  * with a controller port/device configuration. LUN has to be 0.
9078  * Returns 0 if a scsi target refers to an attached device,
9079  * returns 1 if address is valid but device is not attached,
9080  * returns -1 if bad address or device is of an unsupported type.
9081  * Upon return sata_device argument is set.
9082  */
9083 static int
9084 sata_validate_scsi_address(sata_hba_inst_t *sata_hba_inst,
9085 	struct scsi_address *ap, sata_device_t *sata_device)
9086 {
9087 	int cport, pmport, qual, rval;
9088 
9089 	rval = -1;	/* Invalid address */
9090 	if (ap->a_lun != 0)
9091 		goto out;
9092 
9093 	qual = SCSI_TO_SATA_ADDR_QUAL(ap->a_target);
9094 	cport = SCSI_TO_SATA_CPORT(ap->a_target);
9095 	pmport = SCSI_TO_SATA_PMPORT(ap->a_target);
9096 
9097 	if (qual != SATA_ADDR_DCPORT && qual != SATA_ADDR_DPMPORT)
9098 		goto out;
9099 
9100 	if (sata_validate_sata_address(sata_hba_inst, cport, pmport, qual) ==
9101 	    0) {
9102 
9103 		sata_cport_info_t *cportinfo;
9104 		sata_pmult_info_t *pmultinfo;
9105 		sata_drive_info_t *sdinfo = NULL;
9106 
9107 		rval = 1;	/* Valid sata address */
9108 
9109 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
9110 		if (qual == SATA_ADDR_DCPORT) {
9111 			if (cportinfo == NULL ||
9112 			    cportinfo->cport_dev_type == SATA_DTYPE_NONE)
9113 				goto out;
9114 
9115 			if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT ||
9116 			    (cportinfo->cport_dev_type &
9117 			    SATA_VALID_DEV_TYPE) == 0) {
9118 				rval = -1;
9119 				goto out;
9120 			}
9121 			sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
9122 
9123 		} else if (qual == SATA_ADDR_DPMPORT) {
9124 			pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
9125 			if (pmultinfo == NULL) {
9126 				rval = -1;
9127 				goto out;
9128 			}
9129 			if (SATA_PMPORT_INFO(sata_hba_inst, cport, pmport) ==
9130 			    NULL ||
9131 			    SATA_PMPORT_DEV_TYPE(sata_hba_inst, cport,
9132 			    pmport) == SATA_DTYPE_NONE)
9133 				goto out;
9134 
9135 			sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, cport,
9136 			    pmport);
9137 		} else {
9138 			rval = -1;
9139 			goto out;
9140 		}
9141 		if ((sdinfo == NULL) ||
9142 		    (sdinfo->satadrv_type & SATA_VALID_DEV_TYPE) == 0)
9143 			goto out;
9144 
9145 		sata_device->satadev_type = sdinfo->satadrv_type;
9146 		sata_device->satadev_addr.qual = qual;
9147 		sata_device->satadev_addr.cport = cport;
9148 		sata_device->satadev_addr.pmport = pmport;
9149 		sata_device->satadev_rev = SATA_DEVICE_REV_1;
9150 		return (0);
9151 	}
9152 out:
9153 	if (rval == 1) {
9154 		SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
9155 		    "sata_validate_scsi_address: no valid target %x lun %x",
9156 		    ap->a_target, ap->a_lun);
9157 	}
9158 	return (rval);
9159 }
9160 
9161 /*
9162  * Find dip corresponding to passed device number
9163  *
9164  * Returns NULL if invalid device number is passed or device cannot be found,
9165  * Returns dip is device is found.
9166  */
9167 static dev_info_t *
9168 sata_devt_to_devinfo(dev_t dev)
9169 {
9170 	dev_info_t *dip;
9171 #ifndef __lock_lint
9172 	struct devnames *dnp;
9173 	major_t major = getmajor(dev);
9174 	int instance = SATA_MINOR2INSTANCE(getminor(dev));
9175 
9176 	if (major >= devcnt)
9177 		return (NULL);
9178 
9179 	dnp = &devnamesp[major];
9180 	LOCK_DEV_OPS(&(dnp->dn_lock));
9181 	dip = dnp->dn_head;
9182 	while (dip && (ddi_get_instance(dip) != instance)) {
9183 		dip = ddi_get_next(dip);
9184 	}
9185 	UNLOCK_DEV_OPS(&(dnp->dn_lock));
9186 #endif
9187 
9188 	return (dip);
9189 }
9190 
9191 
9192 /*
9193  * Probe device.
9194  * This function issues Identify Device command and initializes local
9195  * sata_drive_info structure if the device can be identified.
9196  * The device type is determined by examining Identify Device
9197  * command response.
9198  * If the sata_hba_inst has linked drive info structure for this
9199  * device address, the Identify Device data is stored into sata_drive_info
9200  * structure linked to the port info structure.
9201  *
9202  * sata_device has to refer to the valid sata port(s) for HBA described
9203  * by sata_hba_inst structure.
9204  *
9205  * Returns:
9206  *	SATA_SUCCESS if device type was successfully probed and port-linked
9207  *		drive info structure was updated;
9208  * 	SATA_FAILURE if there is no device, or device was not probed
9209  *		successully;
9210  *	SATA_RETRY if device probe can be retried later.
9211  * If a device cannot be identified, sata_device's dev_state and dev_type
9212  * fields are set to unknown.
9213  * There are no retries in this function. Any retries should be managed by
9214  * the caller.
9215  */
9216 
9217 
9218 static int
9219 sata_probe_device(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device)
9220 {
9221 	sata_drive_info_t *sdinfo;
9222 	sata_drive_info_t new_sdinfo;	/* local drive info struct */
9223 	int rval;
9224 
9225 	ASSERT((SATA_CPORT_STATE(sata_hba_inst,
9226 	    sata_device->satadev_addr.cport) &
9227 	    (SATA_STATE_PROBED | SATA_STATE_READY)) != 0);
9228 
9229 	sata_device->satadev_type = SATA_DTYPE_NONE;
9230 
9231 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
9232 	    sata_device->satadev_addr.cport)));
9233 
9234 	/* Get pointer to port-linked sata device info structure */
9235 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
9236 	if (sdinfo != NULL) {
9237 		sdinfo->satadrv_state &=
9238 		    ~(SATA_STATE_PROBED | SATA_STATE_READY);
9239 		sdinfo->satadrv_state |= SATA_STATE_PROBING;
9240 	} else {
9241 		/* No device to probe */
9242 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
9243 		    sata_device->satadev_addr.cport)));
9244 		sata_device->satadev_type = SATA_DTYPE_NONE;
9245 		sata_device->satadev_state = SATA_STATE_UNKNOWN;
9246 		return (SATA_FAILURE);
9247 	}
9248 	/*
9249 	 * Need to issue both types of identify device command and
9250 	 * determine device type by examining retreived data/status.
9251 	 * First, ATA Identify Device.
9252 	 */
9253 	bzero(&new_sdinfo, sizeof (sata_drive_info_t));
9254 	new_sdinfo.satadrv_addr = sata_device->satadev_addr;
9255 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
9256 	    sata_device->satadev_addr.cport)));
9257 	new_sdinfo.satadrv_type = SATA_DTYPE_ATADISK;
9258 	rval = sata_identify_device(sata_hba_inst, &new_sdinfo);
9259 	if (rval == SATA_RETRY) {
9260 		/* We may try to check for ATAPI device */
9261 		if (SATA_FEATURES(sata_hba_inst) & SATA_CTLF_ATAPI) {
9262 			/*
9263 			 * HBA supports ATAPI - try to issue Identify Packet
9264 			 * Device command.
9265 			 */
9266 			new_sdinfo.satadrv_type = SATA_DTYPE_ATAPI;
9267 			rval = sata_identify_device(sata_hba_inst, &new_sdinfo);
9268 		}
9269 	}
9270 	if (rval == SATA_SUCCESS) {
9271 		/*
9272 		 * Got something responding positively to ATA Identify Device
9273 		 * or to Identify Packet Device cmd.
9274 		 * Save last used device type.
9275 		 */
9276 		sata_device->satadev_type = new_sdinfo.satadrv_type;
9277 
9278 		/* save device info, if possible */
9279 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
9280 		    sata_device->satadev_addr.cport)));
9281 		sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
9282 		if (sdinfo == NULL) {
9283 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
9284 			    sata_device->satadev_addr.cport)));
9285 			return (SATA_FAILURE);
9286 		}
9287 		/*
9288 		 * Copy drive info into the port-linked drive info structure.
9289 		 */
9290 		*sdinfo = new_sdinfo;
9291 		sdinfo->satadrv_state &= ~SATA_STATE_PROBING;
9292 		sdinfo->satadrv_state |= SATA_STATE_PROBED;
9293 		if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
9294 			SATA_CPORT_DEV_TYPE(sata_hba_inst,
9295 			    sata_device->satadev_addr.cport) =
9296 			    sdinfo->satadrv_type;
9297 		else /* SATA_ADDR_DPMPORT */
9298 			SATA_PMPORT_DEV_TYPE(sata_hba_inst,
9299 			    sata_device->satadev_addr.cport,
9300 			    sata_device->satadev_addr.pmport) =
9301 			    sdinfo->satadrv_type;
9302 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
9303 		    sata_device->satadev_addr.cport)));
9304 		return (SATA_SUCCESS);
9305 	}
9306 
9307 	/*
9308 	 * It may be SATA_RETRY or SATA_FAILURE return.
9309 	 * Looks like we cannot determine the device type at this time.
9310 	 */
9311 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
9312 	    sata_device->satadev_addr.cport)));
9313 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
9314 	if (sdinfo != NULL) {
9315 		sata_device->satadev_type = SATA_DTYPE_UNKNOWN;
9316 		sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
9317 		sdinfo->satadrv_state &= ~SATA_STATE_PROBING;
9318 		sdinfo->satadrv_state |= SATA_STATE_PROBED;
9319 		if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
9320 			SATA_CPORT_DEV_TYPE(sata_hba_inst,
9321 			    sata_device->satadev_addr.cport) =
9322 			    SATA_DTYPE_UNKNOWN;
9323 		else {
9324 			/* SATA_ADDR_DPMPORT */
9325 			if ((SATA_PMULT_INFO(sata_hba_inst,
9326 			    sata_device->satadev_addr.cport) != NULL) &&
9327 			    (SATA_PMPORT_INFO(sata_hba_inst,
9328 			    sata_device->satadev_addr.cport,
9329 			    sata_device->satadev_addr.pmport) != NULL))
9330 				SATA_PMPORT_DEV_TYPE(sata_hba_inst,
9331 				    sata_device->satadev_addr.cport,
9332 				    sata_device->satadev_addr.pmport) =
9333 				    SATA_DTYPE_UNKNOWN;
9334 		}
9335 	}
9336 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
9337 	    sata_device->satadev_addr.cport)));
9338 	return (rval);
9339 }
9340 
9341 
9342 /*
9343  * Get pointer to sata_drive_info structure.
9344  *
9345  * The sata_device has to contain address (cport, pmport and qualifier) for
9346  * specified sata_scsi structure.
9347  *
9348  * Returns NULL if device address is not valid for this HBA configuration.
9349  * Otherwise, returns a pointer to sata_drive_info structure.
9350  *
9351  * This function should be called with a port mutex held.
9352  */
9353 static sata_drive_info_t *
9354 sata_get_device_info(sata_hba_inst_t *sata_hba_inst,
9355     sata_device_t *sata_device)
9356 {
9357 	uint8_t cport = sata_device->satadev_addr.cport;
9358 	uint8_t pmport = sata_device->satadev_addr.pmport;
9359 	uint8_t qual = sata_device->satadev_addr.qual;
9360 
9361 	if (cport >= SATA_NUM_CPORTS(sata_hba_inst))
9362 		return (NULL);
9363 
9364 	if (!(SATA_CPORT_STATE(sata_hba_inst, cport) &
9365 	    (SATA_STATE_PROBED | SATA_STATE_READY)))
9366 		/* Port not probed yet */
9367 		return (NULL);
9368 
9369 	if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) == SATA_DTYPE_NONE)
9370 		return (NULL);
9371 
9372 	if (qual == SATA_ADDR_DCPORT) {
9373 		/* Request for a device on a controller port */
9374 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) ==
9375 		    SATA_DTYPE_PMULT)
9376 			/* Port multiplier attached */
9377 			return (NULL);
9378 		return (SATA_CPORT_DRV_INFO(sata_hba_inst, cport));
9379 	}
9380 	if (qual == SATA_ADDR_DPMPORT) {
9381 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) !=
9382 		    SATA_DTYPE_PMULT)
9383 			return (NULL);
9384 
9385 		if (pmport > SATA_NUM_PMPORTS(sata_hba_inst, cport))
9386 			return (NULL);
9387 
9388 		return (SATA_PMPORT_DRV_INFO(sata_hba_inst, cport, pmport));
9389 	}
9390 
9391 	/* we should not get here */
9392 	return (NULL);
9393 }
9394 
9395 
9396 /*
9397  * sata_identify_device.
9398  * Send Identify Device command to SATA HBA driver.
9399  * If command executes successfully, update sata_drive_info structure pointed
9400  * to by sdinfo argument, including Identify Device data.
9401  * If command fails, invalidate data in sata_drive_info.
9402  *
9403  * Cannot be called from interrupt level.
9404  *
9405  * Returns:
9406  * SATA_SUCCESS if the device was identified as a supported device,
9407  * SATA_RETRY if the device was not identified but could be retried,
9408  * SATA_FAILURE if the device was not identified and identify attempt
9409  *	should not be retried.
9410  */
9411 static int
9412 sata_identify_device(sata_hba_inst_t *sata_hba_inst,
9413     sata_drive_info_t *sdinfo)
9414 {
9415 	uint16_t cfg_word;
9416 	int rval;
9417 
9418 	/* fetch device identify data */
9419 	if ((rval = sata_fetch_device_identify_data(sata_hba_inst,
9420 	    sdinfo)) != SATA_SUCCESS)
9421 		goto fail_unknown;
9422 
9423 	cfg_word = sdinfo->satadrv_id.ai_config;
9424 
9425 	/* Set the correct device type */
9426 	if ((cfg_word & SATA_ATA_TYPE_MASK) == SATA_ATA_TYPE) {
9427 		sdinfo->satadrv_type = SATA_DTYPE_ATADISK;
9428 	} else if (cfg_word == SATA_CFA_TYPE) {
9429 		/* It's a Compact Flash media via CF-to-SATA HDD adapter */
9430 		sdinfo->satadrv_type = SATA_DTYPE_ATADISK;
9431 	} else if ((cfg_word & SATA_ATAPI_TYPE_MASK) == SATA_ATAPI_TYPE) {
9432 		switch (cfg_word & SATA_ATAPI_ID_DEV_TYPE) {
9433 		case SATA_ATAPI_CDROM_DEV:
9434 			sdinfo->satadrv_type = SATA_DTYPE_ATAPICD;
9435 			break;
9436 		case SATA_ATAPI_SQACC_DEV:
9437 			sdinfo->satadrv_type = SATA_DTYPE_ATAPITAPE;
9438 			break;
9439 		case SATA_ATAPI_DIRACC_DEV:
9440 			sdinfo->satadrv_type = SATA_DTYPE_ATAPIDISK;
9441 			break;
9442 		default:
9443 			sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
9444 		}
9445 	} else {
9446 			sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
9447 	}
9448 
9449 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
9450 		if (sdinfo->satadrv_capacity == 0) {
9451 			/* Non-LBA disk. Too bad... */
9452 			sata_log(sata_hba_inst, CE_WARN,
9453 			    "SATA disk device at port %d does not support LBA",
9454 			    sdinfo->satadrv_addr.cport);
9455 			rval = SATA_FAILURE;
9456 			goto fail_unknown;
9457 		}
9458 	}
9459 #if 0
9460 	/* Left for historical reason */
9461 	/*
9462 	 * Some initial version of SATA spec indicated that at least
9463 	 * UDMA mode 4 has to be supported. It is not metioned in
9464 	 * SerialATA 2.6, so this restriction is removed.
9465 	 */
9466 	/* Check for Ultra DMA modes 6 through 0 being supported */
9467 	for (i = 6; i >= 0; --i) {
9468 		if (sdinfo->satadrv_id.ai_ultradma & (1 << i))
9469 			break;
9470 	}
9471 
9472 	/*
9473 	 * At least UDMA 4 mode has to be supported. If mode 4 or
9474 	 * higher are not supported by the device, fail this
9475 	 * device.
9476 	 */
9477 	if (i < 4) {
9478 		/* No required Ultra DMA mode supported */
9479 		sata_log(sata_hba_inst, CE_WARN,
9480 		    "SATA disk device at port %d does not support UDMA "
9481 		    "mode 4 or higher", sdinfo->satadrv_addr.cport);
9482 		SATA_LOG_D((sata_hba_inst, CE_WARN,
9483 		    "mode 4 or higher required, %d supported", i));
9484 		rval = SATA_FAILURE;
9485 		goto fail_unknown;
9486 	}
9487 #endif
9488 
9489 	/*
9490 	 * For Disk devices, if it doesn't support UDMA mode, we would
9491 	 * like to return failure directly.
9492 	 */
9493 	if ((sdinfo->satadrv_type == SATA_DTYPE_ATADISK) &&
9494 	    !((sdinfo->satadrv_id.ai_validinfo & SATA_VALIDINFO_88) != 0 &&
9495 	    (sdinfo->satadrv_id.ai_ultradma & SATA_UDMA_SUP_MASK) != 0)) {
9496 		sata_log(sata_hba_inst, CE_WARN,
9497 		    "SATA disk device at port %d does not support UDMA",
9498 		    sdinfo->satadrv_addr.cport);
9499 		rval = SATA_FAILURE;
9500 		goto fail_unknown;
9501 	}
9502 
9503 	return (SATA_SUCCESS);
9504 
9505 fail_unknown:
9506 	/* Invalidate sata_drive_info ? */
9507 	sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
9508 	sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
9509 	return (rval);
9510 }
9511 
9512 /*
9513  * Log/display device information
9514  */
9515 static void
9516 sata_show_drive_info(sata_hba_inst_t *sata_hba_inst,
9517     sata_drive_info_t *sdinfo)
9518 {
9519 	int valid_version;
9520 	char msg_buf[MAXPATHLEN];
9521 	int i;
9522 
9523 	/* Show HBA path */
9524 	(void) ddi_pathname(SATA_DIP(sata_hba_inst), msg_buf);
9525 
9526 	cmn_err(CE_CONT, "?%s :\n", msg_buf);
9527 
9528 	switch (sdinfo->satadrv_type) {
9529 	case SATA_DTYPE_ATADISK:
9530 		(void) sprintf(msg_buf, "SATA disk device at");
9531 		break;
9532 
9533 	case SATA_DTYPE_ATAPICD:
9534 		(void) sprintf(msg_buf, "SATA CD/DVD (ATAPI) device at");
9535 		break;
9536 
9537 	case SATA_DTYPE_ATAPITAPE:
9538 		(void) sprintf(msg_buf, "SATA tape (ATAPI) device at");
9539 		break;
9540 
9541 	case SATA_DTYPE_ATAPIDISK:
9542 		(void) sprintf(msg_buf, "SATA disk (ATAPI) device at");
9543 		break;
9544 
9545 	case SATA_DTYPE_UNKNOWN:
9546 		(void) sprintf(msg_buf,
9547 		    "Unsupported SATA device type (cfg 0x%x) at ",
9548 		    sdinfo->satadrv_id.ai_config);
9549 		break;
9550 	}
9551 
9552 	if (sdinfo->satadrv_addr.qual == SATA_ADDR_DCPORT)
9553 		cmn_err(CE_CONT, "?\t%s port %d\n",
9554 		    msg_buf, sdinfo->satadrv_addr.cport);
9555 	else
9556 		cmn_err(CE_CONT, "?\t%s port %d pmport %d\n",
9557 		    msg_buf, sdinfo->satadrv_addr.cport,
9558 		    sdinfo->satadrv_addr.pmport);
9559 
9560 	bcopy(&sdinfo->satadrv_id.ai_model, msg_buf,
9561 	    sizeof (sdinfo->satadrv_id.ai_model));
9562 	swab(msg_buf, msg_buf, sizeof (sdinfo->satadrv_id.ai_model));
9563 	msg_buf[sizeof (sdinfo->satadrv_id.ai_model)] = '\0';
9564 	cmn_err(CE_CONT, "?\tmodel %s\n", msg_buf);
9565 
9566 	bcopy(&sdinfo->satadrv_id.ai_fw, msg_buf,
9567 	    sizeof (sdinfo->satadrv_id.ai_fw));
9568 	swab(msg_buf, msg_buf, sizeof (sdinfo->satadrv_id.ai_fw));
9569 	msg_buf[sizeof (sdinfo->satadrv_id.ai_fw)] = '\0';
9570 	cmn_err(CE_CONT, "?\tfirmware %s\n", msg_buf);
9571 
9572 	bcopy(&sdinfo->satadrv_id.ai_drvser, msg_buf,
9573 	    sizeof (sdinfo->satadrv_id.ai_drvser));
9574 	swab(msg_buf, msg_buf, sizeof (sdinfo->satadrv_id.ai_drvser));
9575 	msg_buf[sizeof (sdinfo->satadrv_id.ai_drvser)] = '\0';
9576 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
9577 		cmn_err(CE_CONT, "?\tserial number %s\n", msg_buf);
9578 	} else {
9579 		/*
9580 		 * Some drives do not implement serial number and may
9581 		 * violate the spec by providing spaces rather than zeros
9582 		 * in serial number field. Scan the buffer to detect it.
9583 		 */
9584 		for (i = 0; i < sizeof (sdinfo->satadrv_id.ai_drvser); i++) {
9585 			if (msg_buf[i] != '\0' && msg_buf[i] != ' ')
9586 				break;
9587 		}
9588 		if (i == sizeof (sdinfo->satadrv_id.ai_drvser)) {
9589 			cmn_err(CE_CONT, "?\tserial number - none\n");
9590 		} else {
9591 			cmn_err(CE_CONT, "?\tserial number %s\n", msg_buf);
9592 		}
9593 	}
9594 
9595 #ifdef SATA_DEBUG
9596 	if (sdinfo->satadrv_id.ai_majorversion != 0 &&
9597 	    sdinfo->satadrv_id.ai_majorversion != 0xffff) {
9598 		int i;
9599 		for (i = 14; i >= 2; i--) {
9600 			if (sdinfo->satadrv_id.ai_majorversion & (1 << i)) {
9601 				valid_version = i;
9602 				break;
9603 			}
9604 		}
9605 		cmn_err(CE_CONT,
9606 		    "?\tATA/ATAPI-%d supported, majver 0x%x minver 0x%x\n",
9607 		    valid_version,
9608 		    sdinfo->satadrv_id.ai_majorversion,
9609 		    sdinfo->satadrv_id.ai_minorversion);
9610 	}
9611 #endif
9612 	/* Log some info */
9613 	cmn_err(CE_CONT, "?\tsupported features:\n");
9614 	msg_buf[0] = '\0';
9615 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
9616 		if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48)
9617 			(void) strlcat(msg_buf, "48-bit LBA, ", MAXPATHLEN);
9618 		else if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA28)
9619 			(void) strlcat(msg_buf, "28-bit LBA, ", MAXPATHLEN);
9620 	}
9621 	if (sdinfo->satadrv_features_support & SATA_DEV_F_DMA)
9622 		(void) strlcat(msg_buf, "DMA", MAXPATHLEN);
9623 	if (sdinfo->satadrv_features_support & SATA_DEV_F_NCQ)
9624 		(void) strlcat(msg_buf, ", Native Command Queueing",
9625 		    MAXPATHLEN);
9626 	if (sdinfo->satadrv_features_support & SATA_DEV_F_TCQ)
9627 		(void) strlcat(msg_buf, ", Legacy Tagged Queuing", MAXPATHLEN);
9628 	if ((sdinfo->satadrv_id.ai_cmdset82 & SATA_SMART_SUPPORTED) &&
9629 	    (sdinfo->satadrv_id.ai_features85 & SATA_SMART_ENABLED))
9630 		(void) strlcat(msg_buf, ", SMART", MAXPATHLEN);
9631 	if ((sdinfo->satadrv_id.ai_cmdset84 & SATA_SMART_SELF_TEST_SUPPORTED) &&
9632 	    (sdinfo->satadrv_id.ai_features87 & SATA_SMART_SELF_TEST_SUPPORTED))
9633 		(void) strlcat(msg_buf, ", SMART self-test", MAXPATHLEN);
9634 	cmn_err(CE_CONT, "?\t %s\n", msg_buf);
9635 	if (sdinfo->satadrv_features_support & SATA_DEV_F_SATA2)
9636 		cmn_err(CE_CONT, "?\tSATA Gen2 signaling speed (3.0Gbps)\n");
9637 	else if (sdinfo->satadrv_features_support & SATA_DEV_F_SATA1)
9638 		cmn_err(CE_CONT, "?\tSATA Gen1 signaling speed (1.5Gbps)\n");
9639 	if (sdinfo->satadrv_features_support &
9640 	    (SATA_DEV_F_TCQ | SATA_DEV_F_NCQ)) {
9641 		msg_buf[0] = '\0';
9642 		(void) snprintf(msg_buf, MAXPATHLEN,
9643 		    "Supported queue depth %d",
9644 		    sdinfo->satadrv_queue_depth);
9645 		if (!(sata_func_enable &
9646 		    (SATA_ENABLE_QUEUING | SATA_ENABLE_NCQ)))
9647 			(void) strlcat(msg_buf,
9648 			    " - queueing disabled globally", MAXPATHLEN);
9649 		else if (sdinfo->satadrv_queue_depth >
9650 		    sdinfo->satadrv_max_queue_depth) {
9651 			(void) snprintf(&msg_buf[strlen(msg_buf)],
9652 			    MAXPATHLEN - strlen(msg_buf), ", limited to %d",
9653 			    (int)sdinfo->satadrv_max_queue_depth);
9654 		}
9655 		cmn_err(CE_CONT, "?\t%s\n", msg_buf);
9656 	}
9657 
9658 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
9659 #ifdef __i386
9660 		(void) sprintf(msg_buf, "\tcapacity = %llu sectors\n",
9661 		    sdinfo->satadrv_capacity);
9662 #else
9663 		(void) sprintf(msg_buf, "\tcapacity = %lu sectors\n",
9664 		    sdinfo->satadrv_capacity);
9665 #endif
9666 		cmn_err(CE_CONT, "?%s", msg_buf);
9667 	}
9668 }
9669 
9670 
9671 /*
9672  * sata_save_drive_settings extracts current setting of the device and stores
9673  * it for future reference, in case the device setup would need to be restored
9674  * after the device reset.
9675  *
9676  * For all devices read ahead and write cache settings are saved, if the
9677  * device supports these features at all.
9678  * For ATAPI devices the Removable Media Status Notification setting is saved.
9679  */
9680 static void
9681 sata_save_drive_settings(sata_drive_info_t *sdinfo)
9682 {
9683 	if (SATA_READ_AHEAD_SUPPORTED(sdinfo->satadrv_id) ||
9684 	    SATA_WRITE_CACHE_SUPPORTED(sdinfo->satadrv_id)) {
9685 
9686 		/* Current setting of Read Ahead (and Read Cache) */
9687 		if (SATA_READ_AHEAD_ENABLED(sdinfo->satadrv_id))
9688 			sdinfo->satadrv_settings |= SATA_DEV_READ_AHEAD;
9689 		else
9690 			sdinfo->satadrv_settings &= ~SATA_DEV_READ_AHEAD;
9691 
9692 		/* Current setting of Write Cache */
9693 		if (SATA_WRITE_CACHE_ENABLED(sdinfo->satadrv_id))
9694 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
9695 		else
9696 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
9697 	}
9698 
9699 	if (sdinfo->satadrv_type == SATA_DTYPE_ATAPICD) {
9700 		if (SATA_RM_NOTIFIC_SUPPORTED(sdinfo->satadrv_id))
9701 			sdinfo->satadrv_settings |= SATA_DEV_RMSN;
9702 		else
9703 			sdinfo->satadrv_settings &= ~SATA_DEV_RMSN;
9704 	}
9705 }
9706 
9707 
9708 /*
9709  * sata_check_capacity function determines a disk capacity
9710  * and addressing mode (LBA28/LBA48) by examining a disk identify device data.
9711  *
9712  * NOTE: CHS mode is not supported! If a device does not support LBA,
9713  * this function is not called.
9714  *
9715  * Returns device capacity in number of blocks, i.e. largest addressable LBA+1
9716  */
9717 static uint64_t
9718 sata_check_capacity(sata_drive_info_t *sdinfo)
9719 {
9720 	uint64_t capacity = 0;
9721 	int i;
9722 
9723 	if (sdinfo->satadrv_type != SATA_DTYPE_ATADISK ||
9724 	    !sdinfo->satadrv_id.ai_cap & SATA_LBA_SUPPORT)
9725 		/* Capacity valid only for LBA-addressable disk devices */
9726 		return (0);
9727 
9728 	if ((sdinfo->satadrv_id.ai_validinfo & SATA_VALIDINFO_88) &&
9729 	    (sdinfo->satadrv_id.ai_cmdset83 & SATA_EXT48) &&
9730 	    (sdinfo->satadrv_id.ai_features86 & SATA_EXT48)) {
9731 		/* LBA48 mode supported and enabled */
9732 		sdinfo->satadrv_features_support |= SATA_DEV_F_LBA48 |
9733 		    SATA_DEV_F_LBA28;
9734 		for (i = 3;  i >= 0;  --i) {
9735 			capacity <<= 16;
9736 			capacity += sdinfo->satadrv_id.ai_addrsecxt[i];
9737 		}
9738 	} else {
9739 		capacity = sdinfo->satadrv_id.ai_addrsec[1];
9740 		capacity <<= 16;
9741 		capacity += sdinfo->satadrv_id.ai_addrsec[0];
9742 		if (capacity >= 0x1000000)
9743 			/* LBA28 mode */
9744 			sdinfo->satadrv_features_support |= SATA_DEV_F_LBA28;
9745 	}
9746 	return (capacity);
9747 }
9748 
9749 
9750 /*
9751  * Allocate consistent buffer for DMA transfer
9752  *
9753  * Cannot be called from interrupt level or with mutex held - it may sleep.
9754  *
9755  * Returns pointer to allocated buffer structure, or NULL if allocation failed.
9756  */
9757 static struct buf *
9758 sata_alloc_local_buffer(sata_pkt_txlate_t *spx, int len)
9759 {
9760 	struct scsi_address ap;
9761 	struct buf *bp;
9762 	ddi_dma_attr_t	cur_dma_attr;
9763 
9764 	ASSERT(spx->txlt_sata_pkt != NULL);
9765 	ap.a_hba_tran = spx->txlt_sata_hba_inst->satahba_scsi_tran;
9766 	ap.a_target = SATA_TO_SCSI_TARGET(
9767 	    spx->txlt_sata_pkt->satapkt_device.satadev_addr.cport,
9768 	    spx->txlt_sata_pkt->satapkt_device.satadev_addr.pmport,
9769 	    spx->txlt_sata_pkt->satapkt_device.satadev_addr.qual);
9770 	ap.a_lun = 0;
9771 
9772 	bp = scsi_alloc_consistent_buf(&ap, NULL, len,
9773 	    B_READ, SLEEP_FUNC, NULL);
9774 
9775 	if (bp != NULL) {
9776 		/* Allocate DMA resources for this buffer */
9777 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = bp;
9778 		/*
9779 		 * We use a local version of the dma_attr, to account
9780 		 * for a device addressing limitations.
9781 		 * sata_adjust_dma_attr() will handle sdinfo == NULL which
9782 		 * will cause dma attributes to be adjusted to a lowest
9783 		 * acceptable level.
9784 		 */
9785 		sata_adjust_dma_attr(NULL,
9786 		    SATA_DMA_ATTR(spx->txlt_sata_hba_inst), &cur_dma_attr);
9787 
9788 		if (sata_dma_buf_setup(spx, PKT_CONSISTENT,
9789 		    SLEEP_FUNC, NULL, &cur_dma_attr) != DDI_SUCCESS) {
9790 			scsi_free_consistent_buf(bp);
9791 			spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
9792 			bp = NULL;
9793 		}
9794 	}
9795 	return (bp);
9796 }
9797 
9798 /*
9799  * Release local buffer (consistent buffer for DMA transfer) allocated
9800  * via sata_alloc_local_buffer().
9801  */
9802 static void
9803 sata_free_local_buffer(sata_pkt_txlate_t *spx)
9804 {
9805 	ASSERT(spx->txlt_sata_pkt != NULL);
9806 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp != NULL);
9807 
9808 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies = 0;
9809 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_dma_cookie_list = NULL;
9810 
9811 	sata_common_free_dma_rsrcs(spx);
9812 
9813 	/* Free buffer */
9814 	scsi_free_consistent_buf(spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp);
9815 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
9816 }
9817 
9818 /*
9819  * Allocate sata_pkt
9820  * Pkt structure version and embedded strcutures version are initialized.
9821  * sata_pkt and sata_pkt_txlate structures are cross-linked.
9822  *
9823  * Since this may be called in interrupt context by sata_scsi_init_pkt,
9824  * callback argument determines if it can sleep or not.
9825  * Hence, it should not be called from interrupt context.
9826  *
9827  * If successful, non-NULL pointer to a sata pkt is returned.
9828  * Upon failure, NULL pointer is returned.
9829  */
9830 static sata_pkt_t *
9831 sata_pkt_alloc(sata_pkt_txlate_t *spx, int (*callback)(caddr_t))
9832 {
9833 	sata_pkt_t *spkt;
9834 	int kmsflag;
9835 
9836 	kmsflag = (callback == SLEEP_FUNC) ? KM_SLEEP : KM_NOSLEEP;
9837 	spkt = kmem_zalloc(sizeof (sata_pkt_t), kmsflag);
9838 	if (spkt == NULL) {
9839 		SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
9840 		    "sata_pkt_alloc: failed"));
9841 		return (NULL);
9842 	}
9843 	spkt->satapkt_rev = SATA_PKT_REV;
9844 	spkt->satapkt_cmd.satacmd_rev = SATA_CMD_REV;
9845 	spkt->satapkt_device.satadev_rev = SATA_DEVICE_REV;
9846 	spkt->satapkt_framework_private = spx;
9847 	spx->txlt_sata_pkt = spkt;
9848 	return (spkt);
9849 }
9850 
9851 /*
9852  * Free sata pkt allocated via sata_pkt_alloc()
9853  */
9854 static void
9855 sata_pkt_free(sata_pkt_txlate_t *spx)
9856 {
9857 	ASSERT(spx->txlt_sata_pkt != NULL);
9858 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp == NULL);
9859 	kmem_free(spx->txlt_sata_pkt, sizeof (sata_pkt_t));
9860 	spx->txlt_sata_pkt = NULL;
9861 }
9862 
9863 
9864 /*
9865  * Adjust DMA attributes.
9866  * SCSI cmds block count is up to 24 bits, SATA cmd block count vary
9867  * from 8 bits to 16 bits, depending on a command being used.
9868  * Limiting max block count arbitrarily to 256 for all read/write
9869  * commands may affects performance, so check both the device and
9870  * controller capability before adjusting dma attributes.
9871  */
9872 void
9873 sata_adjust_dma_attr(sata_drive_info_t *sdinfo, ddi_dma_attr_t *dma_attr,
9874     ddi_dma_attr_t *adj_dma_attr)
9875 {
9876 	uint32_t count_max;
9877 
9878 	/* Copy original attributes */
9879 	*adj_dma_attr = *dma_attr;
9880 	/*
9881 	 * Things to consider: device addressing capability,
9882 	 * "excessive" controller DMA capabilities.
9883 	 * If a device is being probed/initialized, there are
9884 	 * no device info - use default limits then.
9885 	 */
9886 	if (sdinfo == NULL) {
9887 		count_max = dma_attr->dma_attr_granular * 0x100;
9888 		if (dma_attr->dma_attr_count_max > count_max)
9889 			adj_dma_attr->dma_attr_count_max = count_max;
9890 		if (dma_attr->dma_attr_maxxfer > count_max)
9891 			adj_dma_attr->dma_attr_maxxfer = count_max;
9892 		return;
9893 	}
9894 
9895 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
9896 		if (sdinfo->satadrv_features_support & (SATA_DEV_F_LBA48)) {
9897 			/*
9898 			 * 16-bit sector count may be used - we rely on
9899 			 * the assumption that only read and write cmds
9900 			 * will request more than 256 sectors worth of data
9901 			 */
9902 			count_max = adj_dma_attr->dma_attr_granular * 0x10000;
9903 		} else {
9904 			/*
9905 			 * 8-bit sector count will be used - default limits
9906 			 * for dma attributes
9907 			 */
9908 			count_max = adj_dma_attr->dma_attr_granular * 0x100;
9909 		}
9910 		/*
9911 		 * Adjust controler dma attributes, if necessary
9912 		 */
9913 		if (dma_attr->dma_attr_count_max > count_max)
9914 			adj_dma_attr->dma_attr_count_max = count_max;
9915 		if (dma_attr->dma_attr_maxxfer > count_max)
9916 			adj_dma_attr->dma_attr_maxxfer = count_max;
9917 	}
9918 }
9919 
9920 
9921 /*
9922  * Allocate DMA resources for the buffer
9923  * This function handles initial DMA resource allocation as well as
9924  * DMA window shift and may be called repeatedly for the same DMA window
9925  * until all DMA cookies in the DMA window are processed.
9926  * To guarantee that there is always a coherent set of cookies to process
9927  * by SATA HBA driver (observing alignment, device granularity, etc.),
9928  * the number of slots for DMA cookies is equal to lesser of  a number of
9929  * cookies in a DMA window and a max number of scatter/gather entries.
9930  *
9931  * Returns DDI_SUCCESS upon successful operation.
9932  * Return failure code of a failing command or DDI_FAILURE when
9933  * internal cleanup failed.
9934  */
9935 static int
9936 sata_dma_buf_setup(sata_pkt_txlate_t *spx, int flags,
9937     int (*callback)(caddr_t), caddr_t arg,
9938     ddi_dma_attr_t *cur_dma_attr)
9939 {
9940 	int	rval;
9941 	off_t	offset;
9942 	size_t	size;
9943 	int	max_sg_len, req_len, i;
9944 	uint_t	dma_flags;
9945 	struct buf	*bp;
9946 	uint64_t	cur_txfer_len;
9947 
9948 
9949 	ASSERT(spx->txlt_sata_pkt != NULL);
9950 	bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
9951 	ASSERT(bp != NULL);
9952 
9953 
9954 	if (spx->txlt_buf_dma_handle == NULL) {
9955 		/*
9956 		 * No DMA resources allocated so far - this is a first call
9957 		 * for this sata pkt.
9958 		 */
9959 		rval = ddi_dma_alloc_handle(SATA_DIP(spx->txlt_sata_hba_inst),
9960 		    cur_dma_attr, callback, arg, &spx->txlt_buf_dma_handle);
9961 
9962 		if (rval != DDI_SUCCESS) {
9963 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
9964 			    "sata_dma_buf_setup: no buf DMA resources %x",
9965 			    rval));
9966 			return (rval);
9967 		}
9968 
9969 		if (bp->b_flags & B_READ)
9970 			dma_flags = DDI_DMA_READ;
9971 		else
9972 			dma_flags = DDI_DMA_WRITE;
9973 
9974 		if (flags & PKT_CONSISTENT)
9975 			dma_flags |= DDI_DMA_CONSISTENT;
9976 
9977 		if (flags & PKT_DMA_PARTIAL)
9978 			dma_flags |= DDI_DMA_PARTIAL;
9979 
9980 		/*
9981 		 * Check buffer alignment and size against dma attributes
9982 		 * Consider dma_attr_align only. There may be requests
9983 		 * with the size lower than device granularity, but they
9984 		 * will not read/write from/to the device, so no adjustment
9985 		 * is necessary. The dma_attr_minxfer theoretically should
9986 		 * be considered, but no HBA driver is checking it.
9987 		 */
9988 		if (IS_P2ALIGNED(bp->b_un.b_addr,
9989 		    cur_dma_attr->dma_attr_align)) {
9990 			rval = ddi_dma_buf_bind_handle(
9991 			    spx->txlt_buf_dma_handle,
9992 			    bp, dma_flags, callback, arg,
9993 			    &spx->txlt_dma_cookie,
9994 			    &spx->txlt_curwin_num_dma_cookies);
9995 		} else { /* Buffer is not aligned */
9996 
9997 			int	(*ddicallback)(caddr_t);
9998 			size_t	bufsz;
9999 
10000 			/* Check id sleeping is allowed */
10001 			ddicallback = (callback == NULL_FUNC) ?
10002 			    DDI_DMA_DONTWAIT : DDI_DMA_SLEEP;
10003 
10004 			SATADBG2(SATA_DBG_DMA_SETUP, spx->txlt_sata_hba_inst,
10005 			    "mis-aligned buffer: addr=0x%p, cnt=%lu",
10006 			    (void *)bp->b_un.b_addr, bp->b_bcount);
10007 
10008 			if (bp->b_flags & (B_PAGEIO|B_PHYS))
10009 				/*
10010 				 * CPU will need to access data in the buffer
10011 				 * (for copying) so map it.
10012 				 */
10013 				bp_mapin(bp);
10014 
10015 			ASSERT(spx->txlt_tmp_buf == NULL);
10016 
10017 			/* Buffer may be padded by ddi_dma_mem_alloc()! */
10018 			rval = ddi_dma_mem_alloc(
10019 			    spx->txlt_buf_dma_handle,
10020 			    bp->b_bcount,
10021 			    &sata_acc_attr,
10022 			    DDI_DMA_STREAMING,
10023 			    ddicallback, NULL,
10024 			    &spx->txlt_tmp_buf,
10025 			    &bufsz,
10026 			    &spx->txlt_tmp_buf_handle);
10027 
10028 			if (rval != DDI_SUCCESS) {
10029 				/* DMA mapping failed */
10030 				(void) ddi_dma_free_handle(
10031 				    &spx->txlt_buf_dma_handle);
10032 				spx->txlt_buf_dma_handle = NULL;
10033 #ifdef SATA_DEBUG
10034 				mbuffail_count++;
10035 #endif
10036 				SATADBG1(SATA_DBG_DMA_SETUP,
10037 				    spx->txlt_sata_hba_inst,
10038 				    "sata_dma_buf_setup: "
10039 				    "buf dma mem alloc failed %x\n", rval);
10040 				return (rval);
10041 			}
10042 			ASSERT(IS_P2ALIGNED(spx->txlt_tmp_buf,
10043 			    cur_dma_attr->dma_attr_align));
10044 
10045 #ifdef SATA_DEBUG
10046 			mbuf_count++;
10047 
10048 			if (bp->b_bcount != bufsz)
10049 				/*
10050 				 * This will require special handling, because
10051 				 * DMA cookies will be based on the temporary
10052 				 * buffer size, not the original buffer
10053 				 * b_bcount, so the residue may have to
10054 				 * be counted differently.
10055 				 */
10056 				SATADBG2(SATA_DBG_DMA_SETUP,
10057 				    spx->txlt_sata_hba_inst,
10058 				    "sata_dma_buf_setup: bp size %x != "
10059 				    "bufsz %x\n", bp->b_bcount, bufsz);
10060 #endif
10061 			if (dma_flags & DDI_DMA_WRITE) {
10062 				/*
10063 				 * Write operation - copy data into
10064 				 * an aligned temporary buffer. Buffer will be
10065 				 * synced for device by ddi_dma_addr_bind_handle
10066 				 */
10067 				bcopy(bp->b_un.b_addr, spx->txlt_tmp_buf,
10068 				    bp->b_bcount);
10069 			}
10070 
10071 			rval = ddi_dma_addr_bind_handle(
10072 			    spx->txlt_buf_dma_handle,
10073 			    NULL,
10074 			    spx->txlt_tmp_buf,
10075 			    bufsz, dma_flags, ddicallback, 0,
10076 			    &spx->txlt_dma_cookie,
10077 			    &spx->txlt_curwin_num_dma_cookies);
10078 		}
10079 
10080 		switch (rval) {
10081 		case DDI_DMA_PARTIAL_MAP:
10082 			SATADBG1(SATA_DBG_DMA_SETUP, spx->txlt_sata_hba_inst,
10083 			    "sata_dma_buf_setup: DMA Partial Map\n", NULL);
10084 			/*
10085 			 * Partial DMA mapping.
10086 			 * Retrieve number of DMA windows for this request.
10087 			 */
10088 			if (ddi_dma_numwin(spx->txlt_buf_dma_handle,
10089 			    &spx->txlt_num_dma_win) != DDI_SUCCESS) {
10090 				if (spx->txlt_tmp_buf != NULL) {
10091 					ddi_dma_mem_free(
10092 					    &spx->txlt_tmp_buf_handle);
10093 					spx->txlt_tmp_buf = NULL;
10094 				}
10095 				(void) ddi_dma_unbind_handle(
10096 				    spx->txlt_buf_dma_handle);
10097 				(void) ddi_dma_free_handle(
10098 				    &spx->txlt_buf_dma_handle);
10099 				spx->txlt_buf_dma_handle = NULL;
10100 				SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
10101 				    "sata_dma_buf_setup: numwin failed\n"));
10102 				return (DDI_FAILURE);
10103 			}
10104 			SATADBG2(SATA_DBG_DMA_SETUP,
10105 			    spx->txlt_sata_hba_inst,
10106 			    "sata_dma_buf_setup: windows: %d, cookies: %d\n",
10107 			    spx->txlt_num_dma_win,
10108 			    spx->txlt_curwin_num_dma_cookies);
10109 			spx->txlt_cur_dma_win = 0;
10110 			break;
10111 
10112 		case DDI_DMA_MAPPED:
10113 			/* DMA fully mapped */
10114 			spx->txlt_num_dma_win = 1;
10115 			spx->txlt_cur_dma_win = 0;
10116 			SATADBG1(SATA_DBG_DMA_SETUP,
10117 			    spx->txlt_sata_hba_inst,
10118 			    "sata_dma_buf_setup: windows: 1 "
10119 			    "cookies: %d\n", spx->txlt_curwin_num_dma_cookies);
10120 			break;
10121 
10122 		default:
10123 			/* DMA mapping failed */
10124 			if (spx->txlt_tmp_buf != NULL) {
10125 				ddi_dma_mem_free(
10126 				    &spx->txlt_tmp_buf_handle);
10127 				spx->txlt_tmp_buf = NULL;
10128 			}
10129 			(void) ddi_dma_free_handle(&spx->txlt_buf_dma_handle);
10130 			spx->txlt_buf_dma_handle = NULL;
10131 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
10132 			    "sata_dma_buf_setup: buf dma handle binding "
10133 			    "failed %x\n", rval));
10134 			return (rval);
10135 		}
10136 		spx->txlt_curwin_processed_dma_cookies = 0;
10137 		spx->txlt_dma_cookie_list = NULL;
10138 	} else {
10139 		/*
10140 		 * DMA setup is reused. Check if we need to process more
10141 		 * cookies in current window, or to get next window, if any.
10142 		 */
10143 
10144 		ASSERT(spx->txlt_curwin_processed_dma_cookies <=
10145 		    spx->txlt_curwin_num_dma_cookies);
10146 
10147 		if (spx->txlt_curwin_processed_dma_cookies ==
10148 		    spx->txlt_curwin_num_dma_cookies) {
10149 			/*
10150 			 * All cookies from current DMA window were processed.
10151 			 * Get next DMA window.
10152 			 */
10153 			spx->txlt_cur_dma_win++;
10154 			if (spx->txlt_cur_dma_win < spx->txlt_num_dma_win) {
10155 				(void) ddi_dma_getwin(spx->txlt_buf_dma_handle,
10156 				    spx->txlt_cur_dma_win, &offset, &size,
10157 				    &spx->txlt_dma_cookie,
10158 				    &spx->txlt_curwin_num_dma_cookies);
10159 				spx->txlt_curwin_processed_dma_cookies = 0;
10160 			} else {
10161 				/* No more windows! End of request! */
10162 				/* What to do? - panic for now */
10163 				ASSERT(spx->txlt_cur_dma_win >=
10164 				    spx->txlt_num_dma_win);
10165 
10166 				spx->txlt_curwin_num_dma_cookies = 0;
10167 				spx->txlt_curwin_processed_dma_cookies = 0;
10168 				spx->txlt_sata_pkt->
10169 				    satapkt_cmd.satacmd_num_dma_cookies = 0;
10170 				return (DDI_SUCCESS);
10171 			}
10172 		}
10173 	}
10174 	/* There better be at least one DMA cookie outstanding */
10175 	ASSERT((spx->txlt_curwin_num_dma_cookies -
10176 	    spx->txlt_curwin_processed_dma_cookies) > 0);
10177 
10178 	if (spx->txlt_dma_cookie_list == &spx->txlt_dma_cookie) {
10179 		/* The default cookie slot was used in previous run */
10180 		ASSERT(spx->txlt_curwin_processed_dma_cookies == 0);
10181 		spx->txlt_dma_cookie_list = NULL;
10182 		spx->txlt_dma_cookie_list_len = 0;
10183 	}
10184 	if (spx->txlt_curwin_processed_dma_cookies == 0) {
10185 		/*
10186 		 * Processing a new DMA window - set-up dma cookies list.
10187 		 * We may reuse previously allocated cookie array if it is
10188 		 * possible.
10189 		 */
10190 		if (spx->txlt_dma_cookie_list != NULL &&
10191 		    spx->txlt_dma_cookie_list_len <
10192 		    spx->txlt_curwin_num_dma_cookies) {
10193 			/*
10194 			 * New DMA window contains more cookies than
10195 			 * the previous one. We need larger cookie list - free
10196 			 * the old one.
10197 			 */
10198 			(void) kmem_free(spx->txlt_dma_cookie_list,
10199 			    spx->txlt_dma_cookie_list_len *
10200 			    sizeof (ddi_dma_cookie_t));
10201 			spx->txlt_dma_cookie_list = NULL;
10202 			spx->txlt_dma_cookie_list_len = 0;
10203 		}
10204 		if (spx->txlt_dma_cookie_list == NULL) {
10205 			/*
10206 			 * Calculate lesser of number of cookies in this
10207 			 * DMA window and number of s/g entries.
10208 			 */
10209 			max_sg_len = cur_dma_attr->dma_attr_sgllen;
10210 			req_len = MIN(max_sg_len,
10211 			    spx->txlt_curwin_num_dma_cookies);
10212 
10213 			/* Allocate new dma cookie array if necessary */
10214 			if (req_len == 1) {
10215 				/* Only one cookie - no need for a list */
10216 				spx->txlt_dma_cookie_list =
10217 				    &spx->txlt_dma_cookie;
10218 				spx->txlt_dma_cookie_list_len = 1;
10219 			} else {
10220 				/*
10221 				 * More than one cookie - try to allocate space.
10222 				 */
10223 				spx->txlt_dma_cookie_list = kmem_zalloc(
10224 				    sizeof (ddi_dma_cookie_t) * req_len,
10225 				    callback == NULL_FUNC ? KM_NOSLEEP :
10226 				    KM_SLEEP);
10227 				if (spx->txlt_dma_cookie_list == NULL) {
10228 					SATADBG1(SATA_DBG_DMA_SETUP,
10229 					    spx->txlt_sata_hba_inst,
10230 					    "sata_dma_buf_setup: cookie list "
10231 					    "allocation failed\n", NULL);
10232 					/*
10233 					 * We could not allocate space for
10234 					 * neccessary number of dma cookies in
10235 					 * this window, so we fail this request.
10236 					 * Next invocation would try again to
10237 					 * allocate space for cookie list.
10238 					 * Note:Packet residue was not modified.
10239 					 */
10240 					return (DDI_DMA_NORESOURCES);
10241 				} else {
10242 					spx->txlt_dma_cookie_list_len = req_len;
10243 				}
10244 			}
10245 		}
10246 		/*
10247 		 * Fetch DMA cookies into cookie list in sata_pkt_txlate.
10248 		 * First cookie was already fetched.
10249 		 */
10250 		*(&spx->txlt_dma_cookie_list[0]) = spx->txlt_dma_cookie;
10251 		cur_txfer_len =
10252 		    (uint64_t)spx->txlt_dma_cookie_list[0].dmac_size;
10253 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies = 1;
10254 		spx->txlt_curwin_processed_dma_cookies++;
10255 		for (i = 1; (i < spx->txlt_dma_cookie_list_len) &&
10256 		    (i < spx->txlt_curwin_num_dma_cookies); i++) {
10257 			ddi_dma_nextcookie(spx->txlt_buf_dma_handle,
10258 			    &spx->txlt_dma_cookie_list[i]);
10259 			cur_txfer_len +=
10260 			    (uint64_t)spx->txlt_dma_cookie_list[i].dmac_size;
10261 			spx->txlt_curwin_processed_dma_cookies++;
10262 			spx->txlt_sata_pkt->
10263 			    satapkt_cmd.satacmd_num_dma_cookies += 1;
10264 		}
10265 	} else {
10266 		SATADBG2(SATA_DBG_DMA_SETUP, spx->txlt_sata_hba_inst,
10267 		    "sata_dma_buf_setup: sliding within DMA window, "
10268 		    "cur cookie %d, total cookies %d\n",
10269 		    spx->txlt_curwin_processed_dma_cookies,
10270 		    spx->txlt_curwin_num_dma_cookies);
10271 
10272 		/*
10273 		 * Not all cookies from the current dma window were used because
10274 		 * of s/g limitation.
10275 		 * There is no need to re-size the list - it was set at
10276 		 * optimal size, or only default entry is used (s/g = 1).
10277 		 */
10278 		if (spx->txlt_dma_cookie_list == NULL) {
10279 			spx->txlt_dma_cookie_list = &spx->txlt_dma_cookie;
10280 			spx->txlt_dma_cookie_list_len = 1;
10281 		}
10282 		/*
10283 		 * Since we are processing remaining cookies in a DMA window,
10284 		 * there may be less of them than the number of entries in the
10285 		 * current dma cookie list.
10286 		 */
10287 		req_len = MIN(spx->txlt_dma_cookie_list_len,
10288 		    (spx->txlt_curwin_num_dma_cookies -
10289 		    spx->txlt_curwin_processed_dma_cookies));
10290 
10291 		/* Fetch the next batch of cookies */
10292 		for (i = 0, cur_txfer_len = 0; i < req_len; i++) {
10293 			ddi_dma_nextcookie(spx->txlt_buf_dma_handle,
10294 			    &spx->txlt_dma_cookie_list[i]);
10295 			cur_txfer_len +=
10296 			    (uint64_t)spx->txlt_dma_cookie_list[i].dmac_size;
10297 			spx->txlt_sata_pkt->
10298 			    satapkt_cmd.satacmd_num_dma_cookies++;
10299 			spx->txlt_curwin_processed_dma_cookies++;
10300 		}
10301 	}
10302 
10303 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies > 0);
10304 
10305 	/* Point sata_cmd to the cookie list */
10306 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_dma_cookie_list =
10307 	    &spx->txlt_dma_cookie_list[0];
10308 
10309 	/* Remember number of DMA cookies passed in sata packet */
10310 	spx->txlt_num_dma_cookies =
10311 	    spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies;
10312 
10313 	ASSERT(cur_txfer_len != 0);
10314 	if (cur_txfer_len <= bp->b_bcount)
10315 		spx->txlt_total_residue -= cur_txfer_len;
10316 	else {
10317 		/*
10318 		 * Temporary DMA buffer has been padded by
10319 		 * ddi_dma_mem_alloc()!
10320 		 * This requires special handling, because DMA cookies are
10321 		 * based on the temporary buffer size, not the b_bcount,
10322 		 * and we have extra bytes to transfer - but the packet
10323 		 * residue has to stay correct because we will copy only
10324 		 * the requested number of bytes.
10325 		 */
10326 		spx->txlt_total_residue -= bp->b_bcount;
10327 	}
10328 
10329 	return (DDI_SUCCESS);
10330 }
10331 
10332 /*
10333  * Common routine for releasing DMA resources
10334  */
10335 static void
10336 sata_common_free_dma_rsrcs(sata_pkt_txlate_t *spx)
10337 {
10338 	if (spx->txlt_buf_dma_handle != NULL) {
10339 		if (spx->txlt_tmp_buf != NULL)  {
10340 			/*
10341 			 * Intermediate DMA buffer was allocated.
10342 			 * Free allocated buffer and associated access handle.
10343 			 */
10344 			ddi_dma_mem_free(&spx->txlt_tmp_buf_handle);
10345 			spx->txlt_tmp_buf = NULL;
10346 		}
10347 		/*
10348 		 * Free DMA resources - cookies and handles
10349 		 */
10350 		/* ASSERT(spx->txlt_dma_cookie_list != NULL); */
10351 		if (spx->txlt_dma_cookie_list != NULL) {
10352 			if (spx->txlt_dma_cookie_list !=
10353 			    &spx->txlt_dma_cookie) {
10354 				(void) kmem_free(spx->txlt_dma_cookie_list,
10355 				    spx->txlt_dma_cookie_list_len *
10356 				    sizeof (ddi_dma_cookie_t));
10357 				spx->txlt_dma_cookie_list = NULL;
10358 			}
10359 		}
10360 		(void) ddi_dma_unbind_handle(spx->txlt_buf_dma_handle);
10361 		(void) ddi_dma_free_handle(&spx->txlt_buf_dma_handle);
10362 		spx->txlt_buf_dma_handle = NULL;
10363 	}
10364 }
10365 
10366 /*
10367  * Free DMA resources
10368  * Used by the HBA driver to release DMA resources that it does not use.
10369  *
10370  * Returns Void
10371  */
10372 void
10373 sata_free_dma_resources(sata_pkt_t *sata_pkt)
10374 {
10375 	sata_pkt_txlate_t *spx;
10376 
10377 	if (sata_pkt == NULL)
10378 		return;
10379 
10380 	spx = (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
10381 
10382 	sata_common_free_dma_rsrcs(spx);
10383 }
10384 
10385 /*
10386  * Fetch Device Identify data.
10387  * Send DEVICE IDENTIFY or IDENTIFY PACKET DEVICE (depending on a device type)
10388  * command to a device and get the device identify data.
10389  * The device_info structure has to be set to device type (for selecting proper
10390  * device identify command).
10391  *
10392  * Returns:
10393  * SATA_SUCCESS if cmd succeeded
10394  * SATA_RETRY if cmd was rejected and could be retried,
10395  * SATA_FAILURE if cmd failed and should not be retried (port error)
10396  *
10397  * Cannot be called in an interrupt context.
10398  */
10399 
10400 static int
10401 sata_fetch_device_identify_data(sata_hba_inst_t *sata_hba_inst,
10402     sata_drive_info_t *sdinfo)
10403 {
10404 	struct buf *bp;
10405 	sata_pkt_t *spkt;
10406 	sata_cmd_t *scmd;
10407 	sata_pkt_txlate_t *spx;
10408 	int rval;
10409 
10410 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
10411 	spx->txlt_sata_hba_inst = sata_hba_inst;
10412 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
10413 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
10414 	if (spkt == NULL) {
10415 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
10416 		return (SATA_RETRY); /* may retry later */
10417 	}
10418 	/* address is needed now */
10419 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
10420 
10421 	/*
10422 	 * Allocate buffer for Identify Data return data
10423 	 */
10424 	bp = sata_alloc_local_buffer(spx, sizeof (sata_id_t));
10425 	if (bp == NULL) {
10426 		sata_pkt_free(spx);
10427 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
10428 		SATA_LOG_D((sata_hba_inst, CE_WARN,
10429 		    "sata_fetch_device_identify_data: "
10430 		    "cannot allocate buffer for ID"));
10431 		return (SATA_RETRY); /* may retry later */
10432 	}
10433 
10434 	/* Fill sata_pkt */
10435 	sdinfo->satadrv_state = SATA_STATE_PROBING;
10436 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
10437 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
10438 	/* Synchronous mode, no callback */
10439 	spkt->satapkt_comp = NULL;
10440 	/* Timeout 30s */
10441 	spkt->satapkt_time = sata_default_pkt_time;
10442 
10443 	scmd = &spkt->satapkt_cmd;
10444 	scmd->satacmd_bp = bp;
10445 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
10446 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
10447 
10448 	/* Build Identify Device cmd in the sata_pkt */
10449 	scmd->satacmd_addr_type = 0;		/* N/A */
10450 	scmd->satacmd_sec_count_lsb = 0;	/* N/A */
10451 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
10452 	scmd->satacmd_lba_mid_lsb = 0;		/* N/A */
10453 	scmd->satacmd_lba_high_lsb = 0;		/* N/A */
10454 	scmd->satacmd_features_reg = 0;		/* N/A */
10455 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
10456 	if (sdinfo->satadrv_type & SATA_DTYPE_ATAPI) {
10457 		/* Identify Packet Device cmd */
10458 		scmd->satacmd_cmd_reg = SATAC_ID_PACKET_DEVICE;
10459 	} else {
10460 		/* Identify Device cmd - mandatory for all other devices */
10461 		scmd->satacmd_cmd_reg = SATAC_ID_DEVICE;
10462 	}
10463 
10464 	/* Send pkt to SATA HBA driver */
10465 	rval = (*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt);
10466 
10467 #ifdef SATA_INJECT_FAULTS
10468 	sata_inject_pkt_fault(spkt, &rval, sata_fault_type);
10469 #endif
10470 
10471 	if (rval == SATA_TRAN_ACCEPTED &&
10472 	    spkt->satapkt_reason == SATA_PKT_COMPLETED) {
10473 		if (spx->txlt_buf_dma_handle != NULL) {
10474 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
10475 			    DDI_DMA_SYNC_FORKERNEL);
10476 			ASSERT(rval == DDI_SUCCESS);
10477 		}
10478 		if ((((sata_id_t *)(bp->b_un.b_addr))->ai_config &
10479 		    SATA_INCOMPLETE_DATA) == SATA_INCOMPLETE_DATA) {
10480 			SATA_LOG_D((sata_hba_inst, CE_WARN,
10481 			    "SATA disk device at port %d - "
10482 			    "partial Identify Data",
10483 			    sdinfo->satadrv_addr.cport));
10484 			rval = SATA_RETRY; /* may retry later */
10485 			goto fail;
10486 		}
10487 		/* Update sata_drive_info */
10488 		bcopy(bp->b_un.b_addr, &sdinfo->satadrv_id,
10489 		    sizeof (sata_id_t));
10490 
10491 		sdinfo->satadrv_features_support = 0;
10492 		if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
10493 			/*
10494 			 * Retrieve capacity (disks only) and addressing mode
10495 			 */
10496 			sdinfo->satadrv_capacity = sata_check_capacity(sdinfo);
10497 		} else {
10498 			/*
10499 			 * For ATAPI devices one would have to issue
10500 			 * Get Capacity cmd for media capacity. Not here.
10501 			 */
10502 			sdinfo->satadrv_capacity = 0;
10503 			/*
10504 			 * Check what cdb length is supported
10505 			 */
10506 			if ((sdinfo->satadrv_id.ai_config &
10507 			    SATA_ATAPI_ID_PKT_SZ) == SATA_ATAPI_ID_PKT_16B)
10508 				sdinfo->satadrv_atapi_cdb_len = 16;
10509 			else
10510 				sdinfo->satadrv_atapi_cdb_len = 12;
10511 		}
10512 		/* Setup supported features flags */
10513 		if (sdinfo->satadrv_id.ai_cap & SATA_DMA_SUPPORT)
10514 			sdinfo->satadrv_features_support |= SATA_DEV_F_DMA;
10515 
10516 		/* Check for SATA GEN and NCQ support */
10517 		if (sdinfo->satadrv_id.ai_satacap != 0 &&
10518 		    sdinfo->satadrv_id.ai_satacap != 0xffff) {
10519 			/* SATA compliance */
10520 			if (sdinfo->satadrv_id.ai_satacap & SATA_NCQ)
10521 				sdinfo->satadrv_features_support |=
10522 				    SATA_DEV_F_NCQ;
10523 			if (sdinfo->satadrv_id.ai_satacap &
10524 			    (SATA_1_SPEED | SATA_2_SPEED)) {
10525 				if (sdinfo->satadrv_id.ai_satacap &
10526 				    SATA_2_SPEED)
10527 					sdinfo->satadrv_features_support |=
10528 					    SATA_DEV_F_SATA2;
10529 				if (sdinfo->satadrv_id.ai_satacap &
10530 				    SATA_1_SPEED)
10531 					sdinfo->satadrv_features_support |=
10532 					    SATA_DEV_F_SATA1;
10533 			} else {
10534 				sdinfo->satadrv_features_support |=
10535 				    SATA_DEV_F_SATA1;
10536 			}
10537 		}
10538 		if ((sdinfo->satadrv_id.ai_cmdset83 & SATA_RW_DMA_QUEUED_CMD) &&
10539 		    (sdinfo->satadrv_id.ai_features86 & SATA_RW_DMA_QUEUED_CMD))
10540 			sdinfo->satadrv_features_support |= SATA_DEV_F_TCQ;
10541 
10542 		sdinfo->satadrv_queue_depth = sdinfo->satadrv_id.ai_qdepth;
10543 		if ((sdinfo->satadrv_features_support & SATA_DEV_F_NCQ) ||
10544 		    (sdinfo->satadrv_features_support & SATA_DEV_F_TCQ)) {
10545 			++sdinfo->satadrv_queue_depth;
10546 			/* Adjust according to controller capabilities */
10547 			sdinfo->satadrv_max_queue_depth = MIN(
10548 			    sdinfo->satadrv_queue_depth,
10549 			    SATA_QDEPTH(sata_hba_inst));
10550 			/* Adjust according to global queue depth limit */
10551 			sdinfo->satadrv_max_queue_depth = MIN(
10552 			    sdinfo->satadrv_max_queue_depth,
10553 			    sata_current_max_qdepth);
10554 			if (sdinfo->satadrv_max_queue_depth == 0)
10555 				sdinfo->satadrv_max_queue_depth = 1;
10556 		} else
10557 			sdinfo->satadrv_max_queue_depth = 1;
10558 
10559 		rval = SATA_SUCCESS;
10560 	} else {
10561 		/*
10562 		 * Woops, no Identify Data.
10563 		 */
10564 		if (rval == SATA_TRAN_BUSY || rval == SATA_TRAN_QUEUE_FULL) {
10565 			rval = SATA_RETRY; /* may retry later */
10566 		} else if (rval == SATA_TRAN_ACCEPTED) {
10567 			if (spkt->satapkt_reason == SATA_PKT_DEV_ERROR ||
10568 			    spkt->satapkt_reason == SATA_PKT_ABORTED ||
10569 			    spkt->satapkt_reason == SATA_PKT_TIMEOUT ||
10570 			    spkt->satapkt_reason == SATA_PKT_RESET)
10571 				rval = SATA_RETRY; /* may retry later */
10572 			else
10573 				rval = SATA_FAILURE;
10574 		} else {
10575 			rval = SATA_FAILURE;
10576 		}
10577 	}
10578 fail:
10579 	/* Free allocated resources */
10580 	sata_free_local_buffer(spx);
10581 	sata_pkt_free(spx);
10582 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
10583 
10584 	return (rval);
10585 }
10586 
10587 
10588 /*
10589  * Some devices may not come-up with default DMA mode (UDMA or MWDMA).
10590  * UDMA mode is checked first, followed by MWDMA mode.
10591  * set correctly, so this function is setting it to the highest supported level.
10592  * Older SATA spec required that the device supports at least DMA 4 mode and
10593  * UDMA mode is selected.  It is not mentioned in SerialATA 2.6, so this
10594  * restriction has been removed.
10595  *
10596  * Returns SATA_SUCCESS if proper DMA mode is selected or no DMA is supported.
10597  * Returns SATA_FAILURE if proper DMA mode could not be selected.
10598  *
10599  * NOTE: This function should be called only if DMA mode is supported.
10600  */
10601 static int
10602 sata_set_dma_mode(sata_hba_inst_t *sata_hba_inst, sata_drive_info_t *sdinfo)
10603 {
10604 	sata_pkt_t *spkt;
10605 	sata_cmd_t *scmd;
10606 	sata_pkt_txlate_t *spx;
10607 	int mode;
10608 	uint8_t subcmd;
10609 	int rval = SATA_SUCCESS;
10610 
10611 	ASSERT(sdinfo != NULL);
10612 	ASSERT(sata_hba_inst != NULL);
10613 
10614 	if ((sdinfo->satadrv_id.ai_validinfo & SATA_VALIDINFO_88) != 0 &&
10615 	    (sdinfo->satadrv_id.ai_ultradma & SATA_UDMA_SUP_MASK) != 0) {
10616 		/* Find highest Ultra DMA mode supported */
10617 		for (mode = 6; mode >= 0; --mode) {
10618 			if (sdinfo->satadrv_id.ai_ultradma & (1 << mode))
10619 				break;
10620 		}
10621 #if 0
10622 		/* Left for historical reasons */
10623 		/*
10624 		 * Some initial version of SATA spec indicated that at least
10625 		 * UDMA mode 4 has to be supported. It is not mentioned in
10626 		 * SerialATA 2.6, so this restriction is removed.
10627 		 */
10628 		if (mode < 4)
10629 			return (SATA_FAILURE);
10630 #endif
10631 
10632 		/*
10633 		 * We're still going to set DMA mode whatever is selected
10634 		 * by default
10635 		 *
10636 		 * We saw an old maxtor sata drive will select Ultra DMA and
10637 		 * Multi-Word DMA simultaneouly by default, which is going
10638 		 * to cause DMA command timed out, so we need to select DMA
10639 		 * mode even when it's already done by default
10640 		 */
10641 
10642 		subcmd = SATAC_TRANSFER_MODE_ULTRA_DMA;
10643 
10644 	} else if ((sdinfo->satadrv_id.ai_dworddma & SATA_MDMA_SUP_MASK) != 0) {
10645 		/* Find highest MultiWord DMA mode supported */
10646 		for (mode = 2; mode >= 0; --mode) {
10647 			if (sdinfo->satadrv_id.ai_dworddma & (1 << mode))
10648 				break;
10649 		}
10650 
10651 		/*
10652 		 * We're still going to set DMA mode whatever is selected
10653 		 * by default
10654 		 *
10655 		 * We saw an old maxtor sata drive will select Ultra DMA and
10656 		 * Multi-Word DMA simultaneouly by default, which is going
10657 		 * to cause DMA command timed out, so we need to select DMA
10658 		 * mode even when it's already done by default
10659 		 */
10660 
10661 		subcmd = SATAC_TRANSFER_MODE_MULTI_WORD_DMA;
10662 	} else
10663 		return (SATA_SUCCESS);
10664 
10665 	/*
10666 	 * Set DMA mode via SET FEATURES COMMAND.
10667 	 * Prepare packet for SET FEATURES COMMAND.
10668 	 */
10669 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
10670 	spx->txlt_sata_hba_inst = sata_hba_inst;
10671 	spx->txlt_scsi_pkt = NULL;	/* No scsi pkt involved */
10672 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
10673 	if (spkt == NULL) {
10674 		SATA_LOG_D((sata_hba_inst, CE_WARN,
10675 		    "sata_set_dma_mode: could not set DMA mode %", mode));
10676 		rval = SATA_FAILURE;
10677 		goto done;
10678 	}
10679 	/* Fill sata_pkt */
10680 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
10681 	/* Timeout 30s */
10682 	spkt->satapkt_time = sata_default_pkt_time;
10683 	/* Synchronous mode, no callback, interrupts */
10684 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
10685 	spkt->satapkt_comp = NULL;
10686 	scmd = &spkt->satapkt_cmd;
10687 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
10688 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
10689 	scmd->satacmd_addr_type = 0;
10690 	scmd->satacmd_device_reg = 0;
10691 	scmd->satacmd_status_reg = 0;
10692 	scmd->satacmd_error_reg = 0;
10693 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
10694 	scmd->satacmd_features_reg = SATAC_SF_TRANSFER_MODE;
10695 	scmd->satacmd_sec_count_lsb = subcmd | mode;
10696 
10697 	/* Transfer command to HBA */
10698 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst),
10699 	    spkt) != SATA_TRAN_ACCEPTED ||
10700 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
10701 		/* Pkt execution failed */
10702 		rval = SATA_FAILURE;
10703 	}
10704 done:
10705 
10706 	/* Free allocated resources */
10707 	if (spkt != NULL)
10708 		sata_pkt_free(spx);
10709 	(void) kmem_free(spx, sizeof (sata_pkt_txlate_t));
10710 
10711 	return (rval);
10712 }
10713 
10714 
10715 /*
10716  * Set device caching mode.
10717  * One of the following operations should be specified:
10718  * SATAC_SF_ENABLE_READ_AHEAD
10719  * SATAC_SF_DISABLE_READ_AHEAD
10720  * SATAC_SF_ENABLE_WRITE_CACHE
10721  * SATAC_SF_DISABLE_WRITE_CACHE
10722  *
10723  * If operation fails, system log messgage is emitted.
10724  * Returns SATA_SUCCESS when the operation succeeds, SATA_RETRY if
10725  * command was sent but did not succeed, and SATA_FAILURE otherwise.
10726  */
10727 
10728 static int
10729 sata_set_cache_mode(sata_hba_inst_t *sata_hba_inst, sata_drive_info_t *sdinfo,
10730     int cache_op)
10731 {
10732 	sata_pkt_t *spkt;
10733 	sata_cmd_t *scmd;
10734 	sata_pkt_txlate_t *spx;
10735 	int rval = SATA_SUCCESS;
10736 	int hba_rval;
10737 	char *infop;
10738 
10739 	ASSERT(sdinfo != NULL);
10740 	ASSERT(sata_hba_inst != NULL);
10741 	ASSERT(cache_op == SATAC_SF_ENABLE_READ_AHEAD ||
10742 	    cache_op == SATAC_SF_DISABLE_READ_AHEAD ||
10743 	    cache_op == SATAC_SF_ENABLE_WRITE_CACHE ||
10744 	    cache_op == SATAC_SF_DISABLE_WRITE_CACHE);
10745 
10746 
10747 	/* Prepare packet for SET FEATURES COMMAND */
10748 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
10749 	spx->txlt_sata_hba_inst = sata_hba_inst;
10750 	spx->txlt_scsi_pkt = NULL;	/* No scsi pkt involved */
10751 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
10752 	if (spkt == NULL) {
10753 		rval = SATA_FAILURE;
10754 		goto failure;
10755 	}
10756 	/* Fill sata_pkt */
10757 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
10758 	/* Timeout 30s */
10759 	spkt->satapkt_time = sata_default_pkt_time;
10760 	/* Synchronous mode, no callback, interrupts */
10761 	spkt->satapkt_op_mode =
10762 	    SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
10763 	spkt->satapkt_comp = NULL;
10764 	scmd = &spkt->satapkt_cmd;
10765 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
10766 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
10767 	scmd->satacmd_addr_type = 0;
10768 	scmd->satacmd_device_reg = 0;
10769 	scmd->satacmd_status_reg = 0;
10770 	scmd->satacmd_error_reg = 0;
10771 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
10772 	scmd->satacmd_features_reg = cache_op;
10773 
10774 	/* Transfer command to HBA */
10775 	hba_rval = (*SATA_START_FUNC(sata_hba_inst))(
10776 	    SATA_DIP(sata_hba_inst), spkt);
10777 
10778 #ifdef SATA_INJECT_FAULTS
10779 	sata_inject_pkt_fault(spkt, &rval, sata_fault_type);
10780 #endif
10781 
10782 	if ((hba_rval != SATA_TRAN_ACCEPTED) ||
10783 	    (spkt->satapkt_reason != SATA_PKT_COMPLETED)) {
10784 		/* Pkt execution failed */
10785 		switch (cache_op) {
10786 		case SATAC_SF_ENABLE_READ_AHEAD:
10787 			infop = "enabling read ahead failed";
10788 			break;
10789 		case SATAC_SF_DISABLE_READ_AHEAD:
10790 			infop = "disabling read ahead failed";
10791 			break;
10792 		case SATAC_SF_ENABLE_WRITE_CACHE:
10793 			infop = "enabling write cache failed";
10794 			break;
10795 		case SATAC_SF_DISABLE_WRITE_CACHE:
10796 			infop = "disabling write cache failed";
10797 			break;
10798 		}
10799 		SATA_LOG_D((sata_hba_inst, CE_WARN, "%s", infop));
10800 		rval = SATA_RETRY;
10801 	}
10802 failure:
10803 	/* Free allocated resources */
10804 	if (spkt != NULL)
10805 		sata_pkt_free(spx);
10806 	(void) kmem_free(spx, sizeof (sata_pkt_txlate_t));
10807 	return (rval);
10808 }
10809 
10810 /*
10811  * Set Removable Media Status Notification (enable/disable)
10812  * state == 0 , disable
10813  * state != 0 , enable
10814  *
10815  * If operation fails, system log messgage is emitted.
10816  * Returns SATA_SUCCESS when the operation succeeds, SATA_FAILURE otherwise.
10817  */
10818 
10819 static int
10820 sata_set_rmsn(sata_hba_inst_t *sata_hba_inst, sata_drive_info_t *sdinfo,
10821     int state)
10822 {
10823 	sata_pkt_t *spkt;
10824 	sata_cmd_t *scmd;
10825 	sata_pkt_txlate_t *spx;
10826 	int rval = SATA_SUCCESS;
10827 	char *infop;
10828 
10829 	ASSERT(sdinfo != NULL);
10830 	ASSERT(sata_hba_inst != NULL);
10831 
10832 	/* Prepare packet for SET FEATURES COMMAND */
10833 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
10834 	spx->txlt_sata_hba_inst = sata_hba_inst;
10835 	spx->txlt_scsi_pkt = NULL;	/* No scsi pkt involved */
10836 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
10837 	if (spkt == NULL) {
10838 		rval = SATA_FAILURE;
10839 		goto failure;
10840 	}
10841 	/* Fill sata_pkt */
10842 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
10843 	/* Timeout 30s */
10844 	spkt->satapkt_time = sata_default_pkt_time;
10845 	/* Synchronous mode, no callback, interrupts */
10846 	spkt->satapkt_op_mode =
10847 	    SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
10848 	spkt->satapkt_comp = NULL;
10849 	scmd = &spkt->satapkt_cmd;
10850 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
10851 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
10852 	scmd->satacmd_addr_type = 0;
10853 	scmd->satacmd_device_reg = 0;
10854 	scmd->satacmd_status_reg = 0;
10855 	scmd->satacmd_error_reg = 0;
10856 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
10857 	if (state == 0)
10858 		scmd->satacmd_features_reg = SATAC_SF_DISABLE_RMSN;
10859 	else
10860 		scmd->satacmd_features_reg = SATAC_SF_ENABLE_RMSN;
10861 
10862 	/* Transfer command to HBA */
10863 	if (((*SATA_START_FUNC(sata_hba_inst))(
10864 	    SATA_DIP(sata_hba_inst), spkt) != SATA_TRAN_ACCEPTED) ||
10865 	    (spkt->satapkt_reason != SATA_PKT_COMPLETED)) {
10866 		/* Pkt execution failed */
10867 		if (state == 0)
10868 			infop = "disabling Removable Media Status "
10869 			    "Notification failed";
10870 		else
10871 			infop = "enabling Removable Media Status "
10872 			    "Notification failed";
10873 
10874 		SATA_LOG_D((sata_hba_inst, CE_WARN, "%s", infop));
10875 		rval = SATA_FAILURE;
10876 	}
10877 failure:
10878 	/* Free allocated resources */
10879 	if (spkt != NULL)
10880 		sata_pkt_free(spx);
10881 	(void) kmem_free(spx, sizeof (sata_pkt_txlate_t));
10882 	return (rval);
10883 }
10884 
10885 
10886 /*
10887  * Update port SCR block
10888  */
10889 static void
10890 sata_update_port_scr(sata_port_scr_t *port_scr, sata_device_t *device)
10891 {
10892 	port_scr->sstatus = device->satadev_scr.sstatus;
10893 	port_scr->serror = device->satadev_scr.serror;
10894 	port_scr->scontrol = device->satadev_scr.scontrol;
10895 	port_scr->sactive = device->satadev_scr.sactive;
10896 	port_scr->snotific = device->satadev_scr.snotific;
10897 }
10898 
10899 /*
10900  * Update state and copy port ss* values from passed sata_device structure.
10901  * sata_address is validated - if not valid, nothing is changed in sata_scsi
10902  * configuration struct.
10903  *
10904  * SATA_PSTATE_SHUTDOWN in port state is not reset to 0 by this function
10905  * regardless of the state in device argument.
10906  *
10907  * Port mutex should be held while calling this function.
10908  */
10909 static void
10910 sata_update_port_info(sata_hba_inst_t *sata_hba_inst,
10911 	sata_device_t *sata_device)
10912 {
10913 	ASSERT(mutex_owned(&SATA_CPORT_MUTEX(sata_hba_inst,
10914 	    sata_device->satadev_addr.cport)));
10915 
10916 	if (sata_device->satadev_addr.qual == SATA_ADDR_CPORT ||
10917 	    sata_device->satadev_addr.qual == SATA_ADDR_DCPORT) {
10918 
10919 		sata_cport_info_t *cportinfo;
10920 
10921 		if (SATA_NUM_CPORTS(sata_hba_inst) <=
10922 		    sata_device->satadev_addr.cport)
10923 			return;
10924 
10925 		cportinfo = SATA_CPORT_INFO(sata_hba_inst,
10926 		    sata_device->satadev_addr.cport);
10927 		sata_update_port_scr(&cportinfo->cport_scr, sata_device);
10928 
10929 		/* Preserve SATA_PSTATE_SHUTDOWN flag */
10930 		cportinfo->cport_state &= ~(SATA_PSTATE_PWRON |
10931 		    SATA_PSTATE_PWROFF | SATA_PSTATE_FAILED);
10932 		cportinfo->cport_state |=
10933 		    sata_device->satadev_state & SATA_PSTATE_VALID;
10934 	} else {
10935 		sata_pmport_info_t *pmportinfo;
10936 
10937 		if ((sata_device->satadev_addr.qual != SATA_ADDR_PMPORT) ||
10938 		    (sata_device->satadev_addr.qual != SATA_ADDR_DPMPORT) ||
10939 		    SATA_NUM_PMPORTS(sata_hba_inst,
10940 		    sata_device->satadev_addr.cport) <
10941 		    sata_device->satadev_addr.pmport)
10942 			return;
10943 
10944 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
10945 		    sata_device->satadev_addr.cport,
10946 		    sata_device->satadev_addr.pmport);
10947 		sata_update_port_scr(&pmportinfo->pmport_scr, sata_device);
10948 
10949 		/* Preserve SATA_PSTATE_SHUTDOWN flag */
10950 		pmportinfo->pmport_state &=
10951 		    ~(SATA_PSTATE_PWRON | SATA_PSTATE_PWROFF |
10952 		    SATA_PSTATE_FAILED);
10953 		pmportinfo->pmport_state |=
10954 		    sata_device->satadev_state & SATA_PSTATE_VALID;
10955 	}
10956 }
10957 
10958 
10959 
10960 /*
10961  * Extract SATA port specification from an IOCTL argument.
10962  *
10963  * This function return the port the user land send us as is, unless it
10964  * cannot retrieve port spec, then -1 is returned.
10965  *
10966  * Note: Only cport  - no port multiplier port.
10967  */
10968 static int32_t
10969 sata_get_port_num(sata_hba_inst_t *sata_hba_inst, struct devctl_iocdata *dcp)
10970 {
10971 	int32_t port;
10972 
10973 	/* Extract port number from nvpair in dca structure  */
10974 	if (nvlist_lookup_int32(ndi_dc_get_ap_data(dcp), "port", &port) != 0) {
10975 		SATA_LOG_D((sata_hba_inst, CE_NOTE,
10976 		    "sata_get_port_num: invalid port spec 0x%x in ioctl",
10977 		    port));
10978 		port = -1;
10979 	}
10980 
10981 	return (port);
10982 }
10983 
10984 /*
10985  * Get dev_info_t pointer to the device node pointed to by port argument.
10986  * NOTE: target argument is a value used in ioctls to identify
10987  * the AP - it is not a sata_address.
10988  * It is a combination of cport, pmport and address qualifier, encodded same
10989  * way as a scsi target number.
10990  * At this moment it carries only cport number.
10991  *
10992  * No PMult hotplug support.
10993  *
10994  * Returns dev_info_t pointer if target device was found, NULL otherwise.
10995  */
10996 
10997 static dev_info_t *
10998 sata_get_target_dip(dev_info_t *dip, int32_t port)
10999 {
11000 	dev_info_t	*cdip = NULL;
11001 	int		target, tgt;
11002 	int		ncport;
11003 	int 		circ;
11004 
11005 	ncport = port & SATA_CFGA_CPORT_MASK;
11006 	target = SATA_TO_SCSI_TARGET(ncport, 0, SATA_ADDR_DCPORT);
11007 
11008 	ndi_devi_enter(dip, &circ);
11009 	for (cdip = ddi_get_child(dip); cdip != NULL; ) {
11010 		dev_info_t *next = ddi_get_next_sibling(cdip);
11011 
11012 		tgt = ddi_prop_get_int(DDI_DEV_T_ANY, cdip,
11013 		    DDI_PROP_DONTPASS, "target", -1);
11014 		if (tgt == -1) {
11015 			/*
11016 			 * This is actually an error condition, but not
11017 			 * a fatal one. Just continue the search.
11018 			 */
11019 			cdip = next;
11020 			continue;
11021 		}
11022 
11023 		if (tgt == target)
11024 			break;
11025 
11026 		cdip = next;
11027 	}
11028 	ndi_devi_exit(dip, circ);
11029 
11030 	return (cdip);
11031 }
11032 
11033 /*
11034  * Get dev_info_t pointer to the device node pointed to by port argument.
11035  * NOTE: target argument is a value used in ioctls to identify
11036  * the AP - it is not a sata_address.
11037  * It is a combination of cport, pmport and address qualifier, encoded same
11038  * way as a scsi target number.
11039  * At this moment it carries only cport number.
11040  *
11041  * No PMult hotplug support.
11042  *
11043  * Returns dev_info_t pointer if target device was found, NULL otherwise.
11044  */
11045 
11046 static dev_info_t *
11047 sata_get_scsi_target_dip(dev_info_t *dip, sata_address_t *saddr)
11048 {
11049 	dev_info_t	*cdip = NULL;
11050 	int		target, tgt;
11051 	int 		circ;
11052 
11053 	target = SATA_TO_SCSI_TARGET(saddr->cport, saddr->pmport, saddr->qual);
11054 
11055 	ndi_devi_enter(dip, &circ);
11056 	for (cdip = ddi_get_child(dip); cdip != NULL; ) {
11057 		dev_info_t *next = ddi_get_next_sibling(cdip);
11058 
11059 		tgt = ddi_prop_get_int(DDI_DEV_T_ANY, cdip,
11060 		    DDI_PROP_DONTPASS, "target", -1);
11061 		if (tgt == -1) {
11062 			/*
11063 			 * This is actually an error condition, but not
11064 			 * a fatal one. Just continue the search.
11065 			 */
11066 			cdip = next;
11067 			continue;
11068 		}
11069 
11070 		if (tgt == target)
11071 			break;
11072 
11073 		cdip = next;
11074 	}
11075 	ndi_devi_exit(dip, circ);
11076 
11077 	return (cdip);
11078 }
11079 
11080 /*
11081  * Process sata port disconnect request.
11082  * Normally, cfgadm sata plugin will try to offline (unconfigure) the device
11083  * before this request. Nevertheless, if a device is still configured,
11084  * we need to attempt to offline and unconfigure device.
11085  * Regardless of the unconfigure operation results the port is marked as
11086  * deactivated and no access to the attached device is possible.
11087  * If the target node remains because unconfigure operation failed, its state
11088  * will be set to DEVICE_REMOVED, preventing it to be used again when a device
11089  * is inserted/re-inserted. The event daemon will repeatedly try to unconfigure
11090  * the device and remove old target node.
11091  *
11092  * This function invokes sata_hba_inst->satahba_tran->
11093  * sata_tran_hotplug_ops->sata_tran_port_deactivate().
11094  * If successful, the device structure (if any) attached to the specified port
11095  * is removed and state of the port marked appropriately.
11096  * Failure of the port_deactivate may keep port in the physically active state,
11097  * or may fail the port.
11098  *
11099  * NOTE: Port multiplier code is not completed nor tested.
11100  */
11101 
11102 static int
11103 sata_ioctl_disconnect(sata_hba_inst_t *sata_hba_inst,
11104     sata_device_t *sata_device)
11105 {
11106 	sata_drive_info_t *sdinfo = NULL;
11107 	sata_cport_info_t *cportinfo = NULL;
11108 	sata_pmport_info_t *pmportinfo = NULL;
11109 	sata_pmult_info_t *pmultinfo = NULL;
11110 	dev_info_t *tdip;
11111 	int cport, pmport, qual;
11112 	int rval = SATA_SUCCESS;
11113 	int rv = 0;
11114 
11115 	cport = sata_device->satadev_addr.cport;
11116 	pmport = sata_device->satadev_addr.pmport;
11117 	qual = sata_device->satadev_addr.qual;
11118 
11119 	ASSERT(qual == SATA_ADDR_CPORT || qual == SATA_ADDR_PMPORT);
11120 
11121 	/*
11122 	 * DEVCTL_AP_DISCONNECT invokes sata_hba_inst->satahba_tran->
11123 	 * sata_tran_hotplug_ops->sata_tran_port_deactivate().
11124 	 * Do the sanity check.
11125 	 */
11126 	if (SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst) == NULL) {
11127 		/* No physical port deactivation supported. */
11128 		return (EINVAL);
11129 	}
11130 
11131 	/* Check the current state of the port */
11132 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
11133 	    (SATA_DIP(sata_hba_inst), sata_device);
11134 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11135 	sata_update_port_info(sata_hba_inst, sata_device);
11136 	if (rval != SATA_SUCCESS ||
11137 	    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
11138 		/* Device port status is unknown or it is in failed state */
11139 		if (qual == SATA_ADDR_PMPORT) {
11140 			SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) =
11141 			    SATA_PSTATE_FAILED;
11142 			SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
11143 			    "sata_hba_ioctl: connect: failed to deactivate "
11144 			    "SATA port %d", cport);
11145 		} else {
11146 			SATA_CPORT_STATE(sata_hba_inst, cport) =
11147 			    SATA_PSTATE_FAILED;
11148 			SATADBG2(SATA_DBG_IOCTL_IF, sata_hba_inst,
11149 			    "sata_hba_ioctl: connect: failed to deactivate "
11150 			    "SATA port %d:%d", cport, pmport);
11151 		}
11152 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
11153 		    cport)->cport_mutex);
11154 		return (EIO);
11155 	}
11156 	/*
11157 	 * Set port's dev_state to not ready - this will disable
11158 	 * an access to a potentially attached device.
11159 	 */
11160 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
11161 	if (qual == SATA_ADDR_PMPORT) {
11162 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
11163 		if (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE) {
11164 			sdinfo = pmportinfo->pmport_sata_drive;
11165 			ASSERT(sdinfo != NULL);
11166 		}
11167 		pmportinfo->pmport_state &= ~SATA_STATE_READY;
11168 	} else {
11169 		/* Assuming cport */
11170 
11171 		if (cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
11172 			if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT) {
11173 				pmultinfo =
11174 				    cportinfo->cport_devp.cport_sata_pmult;
11175 				ASSERT(pmultinfo != NULL);
11176 			} else {
11177 				sdinfo = cportinfo->cport_devp.cport_sata_drive;
11178 			}
11179 		}
11180 		cportinfo->cport_state &= ~SATA_STATE_READY;
11181 	}
11182 	if (sdinfo != NULL) {
11183 		if ((sdinfo->satadrv_type & (SATA_VALID_DEV_TYPE)) != 0) {
11184 			/*
11185 			 * If a target node exists, try to offline
11186 			 * a device and remove target node.
11187 			 */
11188 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
11189 			    cport)->cport_mutex);
11190 			/* We are addressing attached device, not a port */
11191 			sata_device->satadev_addr.qual =
11192 			    sdinfo->satadrv_addr.qual;
11193 			tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
11194 			    &sata_device->satadev_addr);
11195 			if (tdip != NULL && ndi_devi_offline(tdip,
11196 			    NDI_DEVI_REMOVE) != NDI_SUCCESS) {
11197 				/*
11198 				 * Problem
11199 				 * The target node remained attached.
11200 				 * This happens when the device file was open
11201 				 * or a node was waiting for resources.
11202 				 * Cannot do anything about it.
11203 				 */
11204 				if (qual == SATA_ADDR_CPORT) {
11205 					SATA_LOG_D((sata_hba_inst, CE_WARN,
11206 					    "sata_hba_ioctl: disconnect: could "
11207 					    "not unconfigure device before "
11208 					    "disconnecting the SATA port %d",
11209 					    cport));
11210 				} else {
11211 					SATA_LOG_D((sata_hba_inst, CE_WARN,
11212 					    "sata_hba_ioctl: disconnect: could "
11213 					    "not unconfigure device before "
11214 					    "disconnecting the SATA port %d:%d",
11215 					    cport, pmport));
11216 				}
11217 				/*
11218 				 * Set DEVICE REMOVED state in the target
11219 				 * node. It will prevent access to the device
11220 				 * even when a new device is attached, until
11221 				 * the old target node is released, removed and
11222 				 * recreated for a new  device.
11223 				 */
11224 				sata_set_device_removed(tdip);
11225 
11226 				/*
11227 				 * Instruct event daemon to try the target
11228 				 * node cleanup later.
11229 				 */
11230 				sata_set_target_node_cleanup(
11231 				    sata_hba_inst, &sata_device->satadev_addr);
11232 			}
11233 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
11234 			    cport)->cport_mutex);
11235 		}
11236 
11237 		/* Remove and release sata_drive info structure. */
11238 		if (pmportinfo != NULL) {
11239 			SATA_PMPORT_DRV_INFO(sata_hba_inst, cport, pmport) =
11240 			    NULL;
11241 			pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
11242 		} else {
11243 			SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
11244 			cportinfo->cport_dev_type = SATA_DTYPE_NONE;
11245 		}
11246 		(void) kmem_free((void *)sdinfo, sizeof (sata_drive_info_t));
11247 	}
11248 #if 0
11249 	else if (pmultinfo != NULL) {
11250 		/*
11251 		 * Port Multiplier itself needs special handling.
11252 		 * All device ports need to be processed here!
11253 		 */
11254 	}
11255 #endif
11256 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11257 	/* Just ask HBA driver to deactivate port */
11258 	/*	sata_device->satadev_addr.qual = SATA_ADDR_DCPORT; */
11259 
11260 	rval = (*SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst))
11261 	    (SATA_DIP(sata_hba_inst), sata_device);
11262 
11263 	/*
11264 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
11265 	 * without the hint (to force listener to investivate the state).
11266 	 */
11267 	sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
11268 	    SE_NO_HINT);
11269 
11270 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11271 	sata_update_port_info(sata_hba_inst, sata_device);
11272 
11273 	if (rval != SATA_SUCCESS) {
11274 		/*
11275 		 * Port deactivation failure - do not
11276 		 * change port state unless the state
11277 		 * returned by HBA indicates a port failure.
11278 		 * NOTE: device structures were released, so devices now are
11279 		 * invisible! Port reset is needed to re-enumerate devices.
11280 		 */
11281 		if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
11282 			if (pmportinfo != NULL)
11283 				pmportinfo->pmport_state = SATA_PSTATE_FAILED;
11284 			else
11285 				cportinfo->cport_state = SATA_PSTATE_FAILED;
11286 			rv = EIO;
11287 		}
11288 	} else {
11289 		/*
11290 		 * Deactivation succeded. From now on the sata framework
11291 		 * will not care what is happening to the device, until
11292 		 * the port is activated again.
11293 		 */
11294 		cportinfo->cport_state |= SATA_PSTATE_SHUTDOWN;
11295 	}
11296 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11297 	return (rv);
11298 }
11299 
11300 
11301 
11302 /*
11303  * Process sata port connect request
11304  * The sata cfgadm pluging will invoke this operation only if port was found
11305  * in the disconnect state (failed state is also treated as the disconnected
11306  * state).
11307  * DEVCTL_AP_CONNECT would invoke  sata_hba_inst->satahba_tran->
11308  * sata_tran_hotplug_ops->sata_tran_port_activate().
11309  * If successful and a device is found attached to the port,
11310  * the initialization sequence is executed to attach a device structure to
11311  * a port structure. The state of the port and a device would be set
11312  * appropriately.
11313  * The device is not set in configured state (system-wise) by this operation.
11314  *
11315  * Note, that activating the port may generate link events,
11316  * so it is important that following processing and the
11317  * event processing does not interfere with each other!
11318  *
11319  * This operation may remove port failed state and will
11320  * try to make port active and in good standing.
11321  *
11322  * NOTE: Port multiplier code is not completed nor tested.
11323  */
11324 
11325 static int
11326 sata_ioctl_connect(sata_hba_inst_t *sata_hba_inst,
11327     sata_device_t *sata_device)
11328 {
11329 	int cport, pmport, qual;
11330 	int rv = 0;
11331 
11332 	cport = sata_device->satadev_addr.cport;
11333 	pmport = sata_device->satadev_addr.pmport;
11334 	qual = sata_device->satadev_addr.qual;
11335 
11336 	ASSERT(qual == SATA_ADDR_CPORT || qual == SATA_ADDR_PMPORT);
11337 
11338 	/*
11339 	 * DEVCTL_AP_CONNECT would invoke sata_hba_inst->
11340 	 * satahba_tran->sata_tran_hotplug_ops->sata_tran_port_activate().
11341 	 * Perform sanity check now.
11342 	 */
11343 	if (SATA_PORT_ACTIVATE_FUNC(sata_hba_inst) == NULL) {
11344 		/* No physical port activation supported. */
11345 		return (EINVAL);
11346 	}
11347 
11348 	/* Just ask HBA driver to activate port */
11349 	if ((*SATA_PORT_ACTIVATE_FUNC(sata_hba_inst))
11350 	    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
11351 		/*
11352 		 * Port activation failure.
11353 		 */
11354 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
11355 		    cport)->cport_mutex);
11356 		sata_update_port_info(sata_hba_inst, sata_device);
11357 		if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
11358 			if (qual == SATA_ADDR_DCPORT) {
11359 				SATA_CPORT_STATE(sata_hba_inst, cport) =
11360 				    SATA_PSTATE_FAILED;
11361 				SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
11362 				    "sata_hba_ioctl: connect: failed to "
11363 				    "activate SATA port %d", cport);
11364 			} else { /* port multiplier device port */
11365 				SATA_PMPORT_STATE(sata_hba_inst, cport,
11366 				    pmport) = SATA_PSTATE_FAILED;
11367 				SATADBG2(SATA_DBG_IOCTL_IF, sata_hba_inst,
11368 				    "sata_hba_ioctl: connect: failed to "
11369 				    "activate SATA port %d:%d", cport, pmport);
11370 
11371 			}
11372 		}
11373 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
11374 		    cport)->cport_mutex);
11375 		SATADBG2(SATA_DBG_IOCTL_IF, sata_hba_inst,
11376 		    "sata_hba_ioctl: connect: failed to activate SATA "
11377 		    "port %d:%d", cport, pmport);
11378 		return (EIO);
11379 	}
11380 
11381 	/* Virgin port state - will be updated by the port re-probe. */
11382 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11383 	if (qual == SATA_ADDR_CPORT)
11384 		SATA_CPORT_STATE(sata_hba_inst, cport) = 0;
11385 	else /* port multiplier device port */
11386 		SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) = 0;
11387 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11388 
11389 	/*
11390 	 * Probe the port to find its state and attached device.
11391 	 */
11392 	if (sata_reprobe_port(sata_hba_inst, sata_device,
11393 	    SATA_DEV_IDENTIFY_RETRY) == SATA_FAILURE)
11394 		rv = EIO;
11395 
11396 	/*
11397 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
11398 	 * without the hint
11399 	 */
11400 	sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
11401 	    SE_NO_HINT);
11402 
11403 	/*
11404 	 * If there is a device attached to the port, emit
11405 	 * a message.
11406 	 */
11407 	if (sata_device->satadev_type != SATA_DTYPE_NONE) {
11408 
11409 		if (qual == SATA_ADDR_CPORT) {
11410 			sata_log(sata_hba_inst, CE_WARN,
11411 			    "SATA device detected at port %d", cport);
11412 			if (sata_device->satadev_type == SATA_DTYPE_UNKNOWN) {
11413 				/*
11414 				 * A device was not successfully identified
11415 				 */
11416 				sata_log(sata_hba_inst, CE_WARN,
11417 				    "Could not identify SATA "
11418 				    "device at port %d", cport);
11419 			}
11420 		} else { /* port multiplier device port */
11421 			sata_log(sata_hba_inst, CE_WARN,
11422 			    "SATA device detected at port %d:%d",
11423 			    cport, pmport);
11424 			if (sata_device->satadev_type == SATA_DTYPE_UNKNOWN) {
11425 				/*
11426 				 * A device was not successfully identified
11427 				 */
11428 				sata_log(sata_hba_inst, CE_WARN,
11429 				    "Could not identify SATA "
11430 				    "device at port %d:%d", cport, pmport);
11431 			}
11432 		}
11433 	}
11434 
11435 	return (rv);
11436 }
11437 
11438 
11439 /*
11440  * Process sata device unconfigure request.
11441  * The unconfigure operation uses generic nexus operation to
11442  * offline a device. It leaves a target device node attached.
11443  * and obviously sata_drive_info attached as well, because
11444  * from the hardware point of view nothing has changed.
11445  */
11446 static int
11447 sata_ioctl_unconfigure(sata_hba_inst_t *sata_hba_inst,
11448     sata_device_t *sata_device)
11449 {
11450 	int rv = 0;
11451 	dev_info_t *tdip;
11452 
11453 	/* We are addressing attached device, not a port */
11454 	if (sata_device->satadev_addr.qual == SATA_ADDR_CPORT)
11455 		sata_device->satadev_addr.qual = SATA_ADDR_DCPORT;
11456 	else if (sata_device->satadev_addr.qual == SATA_ADDR_PMPORT)
11457 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
11458 
11459 	if ((tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
11460 	    &sata_device->satadev_addr)) != NULL) {
11461 
11462 		if (ndi_devi_offline(tdip, NDI_UNCONFIG) != NDI_SUCCESS) {
11463 			SATA_LOG_D((sata_hba_inst, CE_WARN,
11464 			    "sata_hba_ioctl: unconfigure: "
11465 			    "failed to unconfigure device at SATA port %d:%d",
11466 			    sata_device->satadev_addr.cport,
11467 			    sata_device->satadev_addr.pmport));
11468 			rv = EIO;
11469 		}
11470 		/*
11471 		 * The target node devi_state should be marked with
11472 		 * DEVI_DEVICE_OFFLINE by ndi_devi_offline().
11473 		 * This would be the indication for cfgadm that
11474 		 * the AP node occupant state is 'unconfigured'.
11475 		 */
11476 
11477 	} else {
11478 		/*
11479 		 * This would indicate a failure on the part of cfgadm
11480 		 * to detect correct state of the node prior to this
11481 		 * call - one cannot unconfigure non-existing device.
11482 		 */
11483 		SATA_LOG_D((sata_hba_inst, CE_WARN,
11484 		    "sata_hba_ioctl: unconfigure: "
11485 		    "attempt to unconfigure non-existing device "
11486 		    "at SATA port %d:%d",
11487 		    sata_device->satadev_addr.cport,
11488 		    sata_device->satadev_addr.pmport));
11489 		rv = ENXIO;
11490 	}
11491 	return (rv);
11492 }
11493 
11494 /*
11495  * Process sata device configure request
11496  * If port is in a failed state, operation is aborted - one has to use
11497  * an explicit connect or port activate request to try to get a port into
11498  * non-failed mode. Port reset wil also work in such situation.
11499  * If the port is in disconnected (shutdown) state, the connect operation is
11500  * attempted prior to any other action.
11501  * When port is in the active state, there is a device attached and the target
11502  * node exists, a device was most likely offlined.
11503  * If target node does not exist, a new target node is created. In both cases
11504  * an attempt is made to online (configure) the device.
11505  *
11506  * NOTE: Port multiplier code is not completed nor tested.
11507  */
11508 static int
11509 sata_ioctl_configure(sata_hba_inst_t *sata_hba_inst,
11510     sata_device_t *sata_device)
11511 {
11512 	int cport, pmport, qual;
11513 	int rval;
11514 	boolean_t target = TRUE;
11515 	sata_cport_info_t *cportinfo;
11516 	sata_pmport_info_t *pmportinfo = NULL;
11517 	dev_info_t *tdip;
11518 	sata_drive_info_t *sdinfo;
11519 
11520 	cport = sata_device->satadev_addr.cport;
11521 	pmport = sata_device->satadev_addr.pmport;
11522 	qual = sata_device->satadev_addr.qual;
11523 
11524 	/* Get current port state */
11525 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
11526 	    (SATA_DIP(sata_hba_inst), sata_device);
11527 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11528 	sata_update_port_info(sata_hba_inst, sata_device);
11529 
11530 	if (rval != SATA_SUCCESS ||
11531 	    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
11532 		/*
11533 		 * Obviously, device on a failed port is not visible
11534 		 */
11535 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11536 		return (ENXIO);
11537 	}
11538 
11539 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
11540 	if (qual == SATA_ADDR_PMPORT)
11541 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
11542 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11543 
11544 	if ((sata_device->satadev_state & SATA_PSTATE_SHUTDOWN) != 0) {
11545 		/* need to activate port */
11546 		target = FALSE;
11547 
11548 		/* Sanity check */
11549 		if (SATA_PORT_ACTIVATE_FUNC(sata_hba_inst) == NULL)
11550 			return (ENXIO);
11551 
11552 		/* Just let HBA driver to activate port */
11553 		if ((*SATA_PORT_ACTIVATE_FUNC(sata_hba_inst))
11554 		    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
11555 			/*
11556 			 * Port activation failure - do not change port state
11557 			 * unless the state returned by HBA indicates a port
11558 			 * failure.
11559 			 */
11560 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
11561 			    cport)->cport_mutex);
11562 			sata_update_port_info(sata_hba_inst, sata_device);
11563 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
11564 				if (qual == SATA_ADDR_PMPORT)
11565 					pmportinfo->pmport_state =
11566 					    SATA_PSTATE_FAILED;
11567 				else
11568 					cportinfo->cport_state =
11569 					    SATA_PSTATE_FAILED;
11570 			}
11571 			mutex_exit(&SATA_CPORT_INFO(
11572 			    sata_hba_inst, cport)->cport_mutex);
11573 			SATA_LOG_D((sata_hba_inst, CE_WARN,
11574 			    "sata_hba_ioctl: configure: "
11575 			    "failed to activate SATA port %d:%d",
11576 			    cport, pmport));
11577 			return (EIO);
11578 		}
11579 		/*
11580 		 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
11581 		 * without the hint.
11582 		 */
11583 		sata_gen_sysevent(sata_hba_inst,
11584 		    &sata_device->satadev_addr, SE_NO_HINT);
11585 
11586 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
11587 		    cport_mutex);
11588 		/* Virgin port state */
11589 		if (qual == SATA_ADDR_PMPORT)
11590 			pmportinfo->pmport_state = 0;
11591 		else
11592 			cportinfo->cport_state = 0;
11593 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11594 	}
11595 	/*
11596 	 * Always reprobe port, to get current device info.
11597 	 */
11598 	if (sata_reprobe_port(sata_hba_inst, sata_device,
11599 	    SATA_DEV_IDENTIFY_RETRY) != SATA_SUCCESS)
11600 		return (EIO);
11601 
11602 	if (sata_device->satadev_type != SATA_DTYPE_NONE && target == FALSE) {
11603 		if (qual == SATA_ADDR_PMPORT) {
11604 			/*
11605 			 * That's the transition from "inactive" port
11606 			 * to active one with device attached.
11607 			 */
11608 			sata_log(sata_hba_inst, CE_WARN,
11609 			    "SATA device detected at port %d:%d",
11610 			    cport, pmport);
11611 		} else {
11612 			/*
11613 			 * When PM is attached to the cport and cport is
11614 			 * activated, every PM device port needs to be reprobed.
11615 			 * We need to emit message for all devices detected
11616 			 * at port multiplier's device ports.
11617 			 * Add such code here.
11618 			 * For now, just inform about device attached to
11619 			 * cport.
11620 			 */
11621 			sata_log(sata_hba_inst, CE_WARN,
11622 			    "SATA device detected at port %d", cport);
11623 		}
11624 	}
11625 
11626 	/*
11627 	 * This is where real configuration operation starts.
11628 	 *
11629 	 * When PM is attached to the cport and cport is activated,
11630 	 * devices attached PM device ports may have to be configured
11631 	 * explicitly. This may change when port multiplier is supported.
11632 	 * For now, configure only disks and other valid target devices.
11633 	 */
11634 	if (!(sata_device->satadev_type & SATA_VALID_DEV_TYPE)) {
11635 		if (qual == SATA_ADDR_CPORT) {
11636 			if (sata_device->satadev_type == SATA_DTYPE_UNKNOWN) {
11637 				/*
11638 				 * A device was not successfully identified
11639 				 */
11640 				sata_log(sata_hba_inst, CE_WARN,
11641 				    "Could not identify SATA "
11642 				    "device at port %d", cport);
11643 			}
11644 		} else { /* port multiplier device port */
11645 			if (sata_device->satadev_type == SATA_DTYPE_UNKNOWN) {
11646 				/*
11647 				 * A device was not successfully identified
11648 				 */
11649 				sata_log(sata_hba_inst, CE_WARN,
11650 				    "Could not identify SATA "
11651 				    "device at port %d:%d", cport, pmport);
11652 			}
11653 		}
11654 		return (ENXIO);		/* No device to configure */
11655 	}
11656 
11657 	/*
11658 	 * Here we may have a device in reset condition,
11659 	 * but because we are just configuring it, there is
11660 	 * no need to process the reset other than just
11661 	 * to clear device reset condition in the HBA driver.
11662 	 * Setting the flag SATA_EVNT_CLEAR_DEVICE_RESET will
11663 	 * cause a first command sent the HBA driver with the request
11664 	 * to clear device reset condition.
11665 	 */
11666 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11667 	if (qual == SATA_ADDR_PMPORT)
11668 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
11669 	else
11670 		sata_device->satadev_addr.qual = SATA_ADDR_DCPORT;
11671 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
11672 	if (sdinfo == NULL) {
11673 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11674 		return (ENXIO);
11675 	}
11676 	if (sdinfo->satadrv_event_flags &
11677 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) {
11678 		sdinfo->satadrv_event_flags = 0;
11679 	}
11680 	sdinfo->satadrv_event_flags |= SATA_EVNT_CLEAR_DEVICE_RESET;
11681 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11682 
11683 	if ((tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
11684 	    &sata_device->satadev_addr)) != NULL) {
11685 		/*
11686 		 * Target node exists. Verify, that it belongs
11687 		 * to existing, attached device and not to
11688 		 * a removed device.
11689 		 */
11690 		if (sata_check_device_removed(tdip) == B_TRUE) {
11691 			if (qual == SATA_ADDR_DPMPORT)
11692 				sata_log(sata_hba_inst, CE_WARN,
11693 				    "SATA device at port %d cannot be "
11694 				    "configured. "
11695 				    "Application(s) accessing "
11696 				    "previously attached device "
11697 				    "have to release it before newly "
11698 				    "inserted device can be made accessible.",
11699 				    cport);
11700 			else
11701 				sata_log(sata_hba_inst, CE_WARN,
11702 				    "SATA device at port %d:%d cannot be"
11703 				    "configured. "
11704 				    "Application(s) accessing "
11705 				    "previously attached device "
11706 				    "have to release it before newly "
11707 				    "inserted device can be made accessible.",
11708 				    cport, pmport);
11709 			return (EIO);
11710 		}
11711 		/*
11712 		 * Device was not removed and re-inserted.
11713 		 * Try to online it.
11714 		 */
11715 		if (ndi_devi_online(tdip, 0) != NDI_SUCCESS) {
11716 			SATA_LOG_D((sata_hba_inst, CE_WARN,
11717 			    "sata_hba_ioctl: configure: "
11718 			    "onlining device at SATA port "
11719 			    "%d:%d failed", cport, pmport));
11720 			return (EIO);
11721 		}
11722 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
11723 		    cport)->cport_mutex);
11724 
11725 		if (qual == SATA_ADDR_DPMPORT)
11726 			pmportinfo->pmport_tgtnode_clean = B_TRUE;
11727 		else
11728 			cportinfo-> cport_tgtnode_clean = B_TRUE;
11729 
11730 		mutex_exit(&SATA_CPORT_INFO(
11731 		    sata_hba_inst, cport)->cport_mutex);
11732 	} else {
11733 		/*
11734 		 * No target node - need to create a new target node.
11735 		 */
11736 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
11737 		    cport_mutex);
11738 		if (qual == SATA_ADDR_DPMPORT)
11739 			pmportinfo->pmport_tgtnode_clean = B_TRUE;
11740 		else
11741 			cportinfo-> cport_tgtnode_clean = B_TRUE;
11742 
11743 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
11744 		    cport_mutex);
11745 		tdip = sata_create_target_node(SATA_DIP(sata_hba_inst),
11746 		    sata_hba_inst, &sata_device->satadev_addr);
11747 		if (tdip == NULL) {
11748 			/* Configure operation failed */
11749 			SATA_LOG_D((sata_hba_inst, CE_WARN,
11750 			    "sata_hba_ioctl: configure: "
11751 			    "configuring SATA device at port %d:%d "
11752 			    "failed", cport, pmport));
11753 			return (EIO);
11754 		}
11755 	}
11756 	return (0);
11757 }
11758 
11759 
11760 /*
11761  * Process ioctl deactivate port request.
11762  * Arbitrarily unconfigure attached device, if any.
11763  * Even if the unconfigure fails, proceed with the
11764  * port deactivation.
11765  *
11766  * NOTE: Port Multiplier code is not completed and tested.
11767  */
11768 
11769 static int
11770 sata_ioctl_deactivate(sata_hba_inst_t *sata_hba_inst,
11771     sata_device_t *sata_device)
11772 {
11773 	int cport, pmport, qual;
11774 	int rval, rv = 0;
11775 	sata_cport_info_t *cportinfo;
11776 	sata_pmport_info_t *pmportinfo = NULL;
11777 	dev_info_t *tdip;
11778 	sata_drive_info_t *sdinfo = NULL;
11779 
11780 	/* Sanity check */
11781 	if (SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst) == NULL)
11782 		return (ENOTSUP);
11783 
11784 	cport = sata_device->satadev_addr.cport;
11785 	pmport = sata_device->satadev_addr.pmport;
11786 	qual = sata_device->satadev_addr.qual;
11787 
11788 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11789 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
11790 	if (qual == SATA_ADDR_CPORT) {
11791 		sata_device->satadev_addr.qual = SATA_ADDR_DCPORT;
11792 		if (cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
11793 			/*
11794 			 * For now, assume that port multiplier is not
11795 			 * supported, i.e. deal only with valid devices
11796 			 */
11797 			if ((cportinfo->cport_dev_type &
11798 			    SATA_VALID_DEV_TYPE) != 0)
11799 				sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
11800 			/*
11801 			 * If attached device is a port multiplier, we will
11802 			 * have to unconfigure all devices attached to the
11803 			 * port multiplier. Add this code here.
11804 			 */
11805 		}
11806 		cportinfo->cport_state &= ~SATA_STATE_READY;
11807 	} else {
11808 		/* Port multiplier device port */
11809 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
11810 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
11811 		if (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE &&
11812 		    (pmportinfo->pmport_dev_type & SATA_VALID_DEV_TYPE) != 0)
11813 			sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
11814 		pmportinfo->pmport_state &= ~SATA_STATE_READY;
11815 	}
11816 
11817 	if (sdinfo != NULL) {
11818 		/*
11819 		 * If a target node exists, try to offline a device and
11820 		 * to remove a target node.
11821 		 */
11822 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
11823 		    cport_mutex);
11824 		tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
11825 		    &sata_device->satadev_addr);
11826 		if (tdip != NULL) {
11827 			/* target node exist */
11828 			SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
11829 			    "sata_hba_ioctl: port deactivate: "
11830 			    "target node exists.", NULL);
11831 
11832 			if (ndi_devi_offline(tdip, NDI_DEVI_REMOVE) !=
11833 			    NDI_SUCCESS) {
11834 				SATA_LOG_D((sata_hba_inst, CE_WARN,
11835 				    "sata_hba_ioctl: port deactivate: "
11836 				    "failed to unconfigure device at port "
11837 				    "%d:%d before deactivating the port",
11838 				    cport, pmport));
11839 				/*
11840 				 * Set DEVICE REMOVED state in the target
11841 				 * node. It will prevent an access to
11842 				 * the device even when a new device is
11843 				 * attached, until the old target node is
11844 				 * released, removed and recreated for a new
11845 				 * device.
11846 				 */
11847 				sata_set_device_removed(tdip);
11848 
11849 				/*
11850 				 * Instruct the event daemon to try the
11851 				 * target node cleanup later.
11852 				 */
11853 				sata_set_target_node_cleanup(sata_hba_inst,
11854 				    &sata_device->satadev_addr);
11855 			}
11856 		}
11857 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
11858 		    cport_mutex);
11859 		/*
11860 		 * In any case, remove and release sata_drive_info
11861 		 * structure.
11862 		 */
11863 		if (qual == SATA_ADDR_CPORT) {
11864 			SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
11865 			cportinfo->cport_dev_type = SATA_DTYPE_NONE;
11866 		} else { /* port multiplier device port */
11867 			SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
11868 			pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
11869 		}
11870 		(void) kmem_free((void *)sdinfo, sizeof (sata_drive_info_t));
11871 	}
11872 	if (qual == SATA_ADDR_CPORT) {
11873 		cportinfo->cport_state &= ~(SATA_STATE_PROBED |
11874 		    SATA_STATE_PROBING);
11875 	} else { /* port multiplier device port */
11876 		pmportinfo->pmport_state &= ~(SATA_STATE_PROBED |
11877 		    SATA_STATE_PROBING);
11878 	}
11879 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11880 
11881 	/* Just let HBA driver to deactivate port */
11882 	sata_device->satadev_addr.qual = qual;
11883 	rval = (*SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst))
11884 	    (SATA_DIP(sata_hba_inst), sata_device);
11885 
11886 	/*
11887 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
11888 	 * without the hint
11889 	 */
11890 	sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
11891 	    SE_NO_HINT);
11892 
11893 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11894 	sata_update_port_info(sata_hba_inst, sata_device);
11895 	if (qual == SATA_ADDR_CPORT) {
11896 		if (rval != SATA_SUCCESS) {
11897 			/*
11898 			 * Port deactivation failure - do not change port state
11899 			 * unless the state returned by HBA indicates a port
11900 			 * failure.
11901 			 */
11902 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
11903 				SATA_CPORT_STATE(sata_hba_inst, cport) =
11904 				    SATA_PSTATE_FAILED;
11905 			}
11906 			SATA_LOG_D((sata_hba_inst, CE_WARN,
11907 			    "sata_hba_ioctl: port deactivate: "
11908 			    "cannot deactivate SATA port %d", cport));
11909 			rv = EIO;
11910 		} else {
11911 			cportinfo->cport_state |= SATA_PSTATE_SHUTDOWN;
11912 		}
11913 	} else {
11914 		if (rval != SATA_SUCCESS) {
11915 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
11916 				SATA_PMPORT_STATE(sata_hba_inst, cport,
11917 				    pmport) = SATA_PSTATE_FAILED;
11918 			}
11919 			SATA_LOG_D((sata_hba_inst, CE_WARN,
11920 			    "sata_hba_ioctl: port deactivate: "
11921 			    "cannot deactivate SATA port %d:%d",
11922 			    cport, pmport));
11923 			rv = EIO;
11924 		} else {
11925 			pmportinfo->pmport_state |= SATA_PSTATE_SHUTDOWN;
11926 		}
11927 	}
11928 
11929 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11930 
11931 	return (rv);
11932 }
11933 
11934 /*
11935  * Process ioctl port activate request.
11936  *
11937  * NOTE: Port multiplier code is not completed nor tested.
11938  */
11939 static int
11940 sata_ioctl_activate(sata_hba_inst_t *sata_hba_inst,
11941     sata_device_t *sata_device)
11942 {
11943 	int cport, pmport, qual;
11944 	sata_cport_info_t *cportinfo;
11945 	sata_pmport_info_t *pmportinfo = NULL;
11946 	boolean_t dev_existed = TRUE;
11947 
11948 	/* Sanity check */
11949 	if (SATA_PORT_ACTIVATE_FUNC(sata_hba_inst) == NULL)
11950 		return (ENOTSUP);
11951 
11952 	cport = sata_device->satadev_addr.cport;
11953 	pmport = sata_device->satadev_addr.pmport;
11954 	qual = sata_device->satadev_addr.qual;
11955 
11956 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11957 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
11958 	if (qual == SATA_ADDR_PMPORT) {
11959 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
11960 		if (pmportinfo->pmport_state & SATA_PSTATE_SHUTDOWN ||
11961 		    pmportinfo->pmport_dev_type == SATA_DTYPE_NONE)
11962 			dev_existed = FALSE;
11963 	} else { /* cport */
11964 		if (cportinfo->cport_state & SATA_PSTATE_SHUTDOWN ||
11965 		    cportinfo->cport_dev_type == SATA_DTYPE_NONE)
11966 			dev_existed = FALSE;
11967 	}
11968 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11969 
11970 	/* Just let HBA driver to activate port, if necessary */
11971 	if ((*SATA_PORT_ACTIVATE_FUNC(sata_hba_inst))
11972 	    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
11973 		/*
11974 		 * Port activation failure - do not change port state unless
11975 		 * the state returned by HBA indicates a port failure.
11976 		 */
11977 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
11978 		    cport)->cport_mutex);
11979 		sata_update_port_info(sata_hba_inst, sata_device);
11980 		if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
11981 			if (qual == SATA_ADDR_PMPORT)
11982 				pmportinfo->pmport_state = SATA_PSTATE_FAILED;
11983 			else
11984 				cportinfo->cport_state = SATA_PSTATE_FAILED;
11985 
11986 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
11987 			    cport)->cport_mutex);
11988 			SATA_LOG_D((sata_hba_inst, CE_WARN,
11989 			    "sata_hba_ioctl: port activate: cannot activate "
11990 			    "SATA port %d:%d", cport, pmport));
11991 			return (EIO);
11992 		}
11993 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11994 	}
11995 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11996 	if (qual == SATA_ADDR_PMPORT)
11997 		pmportinfo->pmport_state &= ~SATA_PSTATE_SHUTDOWN;
11998 	else
11999 		cportinfo->cport_state &= ~SATA_PSTATE_SHUTDOWN;
12000 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
12001 
12002 	/*
12003 	 * Re-probe port to find its current state and possibly attached device.
12004 	 * Port re-probing may change the cportinfo device type if device is
12005 	 * found attached.
12006 	 * If port probing failed, the device type would be set to
12007 	 * SATA_DTYPE_NONE.
12008 	 */
12009 	(void) sata_reprobe_port(sata_hba_inst, sata_device,
12010 	    SATA_DEV_IDENTIFY_RETRY);
12011 
12012 	/*
12013 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
12014 	 * without the hint.
12015 	 */
12016 	sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
12017 	    SE_NO_HINT);
12018 
12019 	if (dev_existed == FALSE) {
12020 		if (qual == SATA_ADDR_PMPORT &&
12021 		    pmportinfo->pmport_dev_type != SATA_DTYPE_NONE) {
12022 			/*
12023 			 * That's the transition from the "inactive" port state
12024 			 * or the active port without a device attached to the
12025 			 * active port state with a device attached.
12026 			 */
12027 			sata_log(sata_hba_inst, CE_WARN,
12028 			    "SATA device detected at port %d:%d",
12029 			    cport, pmport);
12030 		} else if (qual == SATA_ADDR_CPORT &&
12031 		    cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
12032 			/*
12033 			 * That's the transition from the "inactive" port state
12034 			 * or the active port without a device attached to the
12035 			 * active port state with a device attached.
12036 			 */
12037 			if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
12038 				sata_log(sata_hba_inst, CE_WARN,
12039 				    "SATA device detected at port %d", cport);
12040 			} else {
12041 				sata_log(sata_hba_inst, CE_WARN,
12042 				    "SATA port multiplier detected at port %d",
12043 				    cport);
12044 				/*
12045 				 * Because the detected device is a port
12046 				 * multiplier, we need to reprobe every device
12047 				 * port on the port multiplier and show every
12048 				 * device found attached.
12049 				 * Add this code here.
12050 				 */
12051 			}
12052 		}
12053 	}
12054 	return (0);
12055 }
12056 
12057 
12058 
12059 /*
12060  * Process ioctl reset port request.
12061  *
12062  * NOTE: Port multiplier code is not completed nor tested.
12063  */
12064 static int
12065 sata_ioctl_reset_port(sata_hba_inst_t *sata_hba_inst,
12066     sata_device_t *sata_device)
12067 {
12068 	int cport, pmport, qual;
12069 	int rv = 0;
12070 
12071 	cport = sata_device->satadev_addr.cport;
12072 	pmport = sata_device->satadev_addr.pmport;
12073 	qual = sata_device->satadev_addr.qual;
12074 
12075 	/* Sanity check */
12076 	if (SATA_RESET_DPORT_FUNC(sata_hba_inst) == NULL) {
12077 		SATA_LOG_D((sata_hba_inst, CE_WARN,
12078 		    "sata_hba_ioctl: sata_hba_tran missing required "
12079 		    "function sata_tran_reset_dport"));
12080 		return (ENOTSUP);
12081 	}
12082 
12083 	/* Ask HBA to reset port */
12084 	if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst),
12085 	    sata_device) != SATA_SUCCESS) {
12086 		SATA_LOG_D((sata_hba_inst, CE_WARN,
12087 		    "sata_hba_ioctl: reset port: failed %d:%d",
12088 		    cport, pmport));
12089 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
12090 		    cport_mutex);
12091 		sata_update_port_info(sata_hba_inst, sata_device);
12092 		if (qual == SATA_ADDR_CPORT)
12093 			SATA_CPORT_STATE(sata_hba_inst, cport) =
12094 			    SATA_PSTATE_FAILED;
12095 		else
12096 			SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) =
12097 			    SATA_PSTATE_FAILED;
12098 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
12099 		    cport_mutex);
12100 		rv = EIO;
12101 	}
12102 	/*
12103 	 * Beacuse the port was reset, it should be probed and
12104 	 * attached device reinitialized. At this point the
12105 	 * port state is unknown - it's state is HBA-specific.
12106 	 * Re-probe port to get its state.
12107 	 */
12108 	if (sata_reprobe_port(sata_hba_inst, sata_device,
12109 	    SATA_DEV_IDENTIFY_RETRY) != SATA_SUCCESS) {
12110 		rv = EIO;
12111 	}
12112 	return (rv);
12113 }
12114 
12115 /*
12116  * Process ioctl reset device request.
12117  *
12118  * NOTE: Port multiplier code is not completed nor tested.
12119  */
12120 static int
12121 sata_ioctl_reset_device(sata_hba_inst_t *sata_hba_inst,
12122     sata_device_t *sata_device)
12123 {
12124 	sata_drive_info_t *sdinfo;
12125 	int cport, pmport;
12126 	int rv = 0;
12127 
12128 	/* Sanity check */
12129 	if (SATA_RESET_DPORT_FUNC(sata_hba_inst) == NULL) {
12130 		SATA_LOG_D((sata_hba_inst, CE_WARN,
12131 		    "sata_hba_ioctl: sata_hba_tran missing required "
12132 		    "function sata_tran_reset_dport"));
12133 		return (ENOTSUP);
12134 	}
12135 
12136 	cport = sata_device->satadev_addr.cport;
12137 	pmport = sata_device->satadev_addr.pmport;
12138 
12139 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
12140 	if (sata_device->satadev_addr.qual == SATA_ADDR_CPORT) {
12141 		sata_device->satadev_addr.qual = SATA_ADDR_DCPORT;
12142 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
12143 		    sata_device->satadev_addr.cport);
12144 	} else { /* port multiplier */
12145 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
12146 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst,
12147 		    sata_device->satadev_addr.cport,
12148 		    sata_device->satadev_addr.pmport);
12149 	}
12150 	if (sdinfo == NULL) {
12151 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
12152 		return (EINVAL);
12153 	}
12154 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
12155 
12156 	/* Ask HBA to reset device */
12157 	if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))
12158 	    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
12159 		SATA_LOG_D((sata_hba_inst, CE_WARN,
12160 		    "sata_hba_ioctl: reset device: failed at port %d:%d",
12161 		    cport, pmport));
12162 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
12163 		    cport_mutex);
12164 		sata_update_port_info(sata_hba_inst, sata_device);
12165 		/*
12166 		 * Device info structure remains attached. Another device reset
12167 		 * or port disconnect/connect and re-probing is
12168 		 * needed to change it's state
12169 		 */
12170 		sdinfo->satadrv_state &= ~SATA_STATE_READY;
12171 		sdinfo->satadrv_state |= SATA_DSTATE_FAILED;
12172 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
12173 		rv = EIO;
12174 	}
12175 	/*
12176 	 * If attached device was a port multiplier, some extra processing
12177 	 * may be needed, to bring it back (if port re-probing did not handle
12178 	 * it). Add such code here.
12179 	 */
12180 	return (rv);
12181 }
12182 
12183 
12184 /*
12185  * Process ioctl reset all request.
12186  *
12187  * NOTE: Port multiplier code is not completed nor tested.
12188  */
12189 static int
12190 sata_ioctl_reset_all(sata_hba_inst_t *sata_hba_inst)
12191 {
12192 	sata_device_t sata_device;
12193 	int rv = 0;
12194 	int tcport;
12195 	int tpmport = 0;
12196 
12197 	sata_device.satadev_rev = SATA_DEVICE_REV;
12198 
12199 	/*
12200 	 * There is no protection here for configured devices.
12201 	 */
12202 	/* Sanity check */
12203 	if (SATA_RESET_DPORT_FUNC(sata_hba_inst) == NULL) {
12204 		SATA_LOG_D((sata_hba_inst, CE_WARN,
12205 		    "sata_hba_ioctl: sata_hba_tran missing required "
12206 		    "function sata_tran_reset_dport"));
12207 		return (ENOTSUP);
12208 	}
12209 
12210 	/*
12211 	 * Need to lock all ports, not just one.
12212 	 * If any port is locked by event processing, fail the whole operation.
12213 	 * One port is already locked, but for simplicity lock it again.
12214 	 */
12215 	for (tcport = 0; tcport < SATA_NUM_CPORTS(sata_hba_inst); tcport++) {
12216 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
12217 		    cport_mutex);
12218 		if (((SATA_CPORT_INFO(sata_hba_inst, tcport)->
12219 		    cport_event_flags) & SATA_EVNT_LOCK_PORT_BUSY) != 0) {
12220 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
12221 			    cport_mutex);
12222 			rv = EBUSY;
12223 			break;
12224 		} else {
12225 			SATA_CPORT_INFO(sata_hba_inst, tcport)->
12226 			    cport_event_flags |= SATA_APCTL_LOCK_PORT_BUSY;
12227 			/*
12228 			 * If there is a port multiplier attached, we may need
12229 			 * to lock its port as well. If so, add such code here.
12230 			 */
12231 		}
12232 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
12233 		    cport_mutex);
12234 	}
12235 
12236 	if (rv == 0) {
12237 		/*
12238 		 * All cports were successfully locked.
12239 		 * Reset main SATA controller only for now - no PMult.
12240 		 * Set the device address to port 0, to have a valid device
12241 		 * address.
12242 		 */
12243 		sata_device.satadev_addr.qual = SATA_ADDR_CNTRL;
12244 		sata_device.satadev_addr.cport = 0;
12245 		sata_device.satadev_addr.pmport = 0;
12246 
12247 		if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))
12248 		    (SATA_DIP(sata_hba_inst), &sata_device) != SATA_SUCCESS) {
12249 			SATA_LOG_D((sata_hba_inst, CE_WARN,
12250 			    "sata_hba_ioctl: reset controller failed"));
12251 			return (EIO);
12252 		}
12253 		/*
12254 		 * Because ports were reset, port states are unknown.
12255 		 * They should be re-probed to get their state and
12256 		 * attached devices should be reinitialized.
12257 		 * Add code here to re-probe port multiplier device ports.
12258 		 */
12259 		for (tcport = 0; tcport < SATA_NUM_CPORTS(sata_hba_inst);
12260 		    tcport++) {
12261 			sata_device.satadev_addr.cport = tcport;
12262 			sata_device.satadev_addr.pmport = tpmport;
12263 			sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
12264 
12265 			if (sata_reprobe_port(sata_hba_inst, &sata_device,
12266 			    SATA_DEV_IDENTIFY_RETRY) != SATA_SUCCESS)
12267 				rv = EIO;
12268 		}
12269 	}
12270 	/*
12271 	 * Unlock all ports
12272 	 */
12273 	for (tcport = 0; tcport < SATA_NUM_CPORTS(sata_hba_inst); tcport++) {
12274 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
12275 		    cport_mutex);
12276 		SATA_CPORT_INFO(sata_hba_inst, tcport)->
12277 		    cport_event_flags &= ~SATA_APCTL_LOCK_PORT_BUSY;
12278 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
12279 		    cport_mutex);
12280 	}
12281 
12282 	/*
12283 	 * This operation returns EFAULT if either reset
12284 	 * controller failed or a re-probing of any port failed.
12285 	 */
12286 	return (rv);
12287 }
12288 
12289 
12290 /*
12291  * Process ioctl port self test request.
12292  *
12293  * NOTE: Port multiplier code is not completed nor tested.
12294  */
12295 static int
12296 sata_ioctl_port_self_test(sata_hba_inst_t *sata_hba_inst,
12297     sata_device_t *sata_device)
12298 {
12299 	int cport, pmport, qual;
12300 	int rv = 0;
12301 
12302 	/* Sanity check */
12303 	if (SATA_SELFTEST_FUNC(sata_hba_inst) == NULL)
12304 		return (ENOTSUP);
12305 
12306 	cport = sata_device->satadev_addr.cport;
12307 	pmport = sata_device->satadev_addr.pmport;
12308 	qual = sata_device->satadev_addr.qual;
12309 
12310 	/*
12311 	 * There is no protection here for a configured
12312 	 * device attached to this port.
12313 	 */
12314 
12315 	if ((*SATA_SELFTEST_FUNC(sata_hba_inst))
12316 	    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
12317 		SATA_LOG_D((sata_hba_inst, CE_WARN,
12318 		    "sata_hba_ioctl: port selftest: "
12319 		    "failed port %d:%d", cport, pmport));
12320 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
12321 		    cport_mutex);
12322 		sata_update_port_info(sata_hba_inst, sata_device);
12323 		if (qual == SATA_ADDR_CPORT)
12324 			SATA_CPORT_STATE(sata_hba_inst, cport) =
12325 			    SATA_PSTATE_FAILED;
12326 		else /* port ultiplier device port */
12327 			SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) =
12328 			    SATA_PSTATE_FAILED;
12329 
12330 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
12331 		    cport_mutex);
12332 		return (EIO);
12333 	}
12334 	/*
12335 	 * Beacuse the port was reset in the course of testing, it should be
12336 	 * re-probed and attached device state should be restored. At this
12337 	 * point the port state is unknown - it's state is HBA-specific.
12338 	 * Force port re-probing to get it into a known state.
12339 	 */
12340 	if (sata_reprobe_port(sata_hba_inst, sata_device,
12341 	    SATA_DEV_IDENTIFY_RETRY) != SATA_SUCCESS)
12342 		rv = EIO;
12343 	return (rv);
12344 }
12345 
12346 
12347 /*
12348  * sata_cfgadm_state:
12349  * Use the sata port state and state of the target node to figure out
12350  * the cfgadm_state.
12351  *
12352  * The port argument is a value with encoded cport,
12353  * pmport and address qualifier, in the same manner as a scsi target number.
12354  * SCSI_TO_SATA_CPORT macro extracts cport number,
12355  * SCSI_TO_SATA_PMPORT extracts pmport number and
12356  * SCSI_TO_SATA_ADDR_QUAL extracts port mulitplier qualifier flag.
12357  *
12358  * For now, support is for cports only - no port multiplier device ports.
12359  */
12360 
12361 static void
12362 sata_cfgadm_state(sata_hba_inst_t *sata_hba_inst, int32_t port,
12363     devctl_ap_state_t *ap_state)
12364 {
12365 	uint16_t	cport;
12366 	int		port_state;
12367 	sata_drive_info_t *sdinfo;
12368 
12369 	/* Cport only */
12370 	cport = SCSI_TO_SATA_CPORT(port);
12371 
12372 	port_state = SATA_CPORT_STATE(sata_hba_inst, cport);
12373 	if (port_state & SATA_PSTATE_SHUTDOWN ||
12374 	    port_state & SATA_PSTATE_FAILED) {
12375 		ap_state->ap_rstate = AP_RSTATE_DISCONNECTED;
12376 		ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
12377 		if (port_state & SATA_PSTATE_FAILED)
12378 			ap_state->ap_condition = AP_COND_FAILED;
12379 		else
12380 			ap_state->ap_condition = AP_COND_UNKNOWN;
12381 
12382 		return;
12383 	}
12384 
12385 	/* Need to check pmult device port here as well, when supported */
12386 
12387 	/* Port is enabled and ready */
12388 
12389 	switch (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport)) {
12390 	case SATA_DTYPE_NONE:
12391 	{
12392 		ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
12393 		ap_state->ap_condition = AP_COND_OK;
12394 		/* No device attached */
12395 		ap_state->ap_rstate = AP_RSTATE_EMPTY;
12396 		break;
12397 	}
12398 	case SATA_DTYPE_UNKNOWN:
12399 	case SATA_DTYPE_PMULT:	/* Until PMult is supported */
12400 	case SATA_DTYPE_ATADISK:
12401 	case SATA_DTYPE_ATAPICD:
12402 	case SATA_DTYPE_ATAPITAPE:
12403 	case SATA_DTYPE_ATAPIDISK:
12404 	{
12405 		dev_info_t *tdip = NULL;
12406 		dev_info_t *dip = NULL;
12407 		int circ;
12408 
12409 		dip = SATA_DIP(sata_hba_inst);
12410 		tdip = sata_get_target_dip(dip, port);
12411 		ap_state->ap_rstate = AP_RSTATE_CONNECTED;
12412 		if (tdip != NULL) {
12413 			ndi_devi_enter(dip, &circ);
12414 			mutex_enter(&(DEVI(tdip)->devi_lock));
12415 			if (DEVI_IS_DEVICE_REMOVED(tdip)) {
12416 				/*
12417 				 * There could be the case where previously
12418 				 * configured and opened device was removed
12419 				 * and unknown device was plugged.
12420 				 * In such case we want to show a device, and
12421 				 * its configured or unconfigured state but
12422 				 * indicate unusable condition untill the
12423 				 * old target node is released and removed.
12424 				 */
12425 				ap_state->ap_condition = AP_COND_UNUSABLE;
12426 			} else {
12427 				mutex_enter(&SATA_CPORT_MUTEX(sata_hba_inst,
12428 				    cport));
12429 				sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
12430 				    cport);
12431 				if (sdinfo != NULL) {
12432 					if ((sdinfo->satadrv_state &
12433 					    SATA_DSTATE_FAILED) != 0)
12434 						ap_state->ap_condition =
12435 						    AP_COND_FAILED;
12436 					else
12437 						ap_state->ap_condition =
12438 						    AP_COND_OK;
12439 				} else {
12440 					ap_state->ap_condition =
12441 					    AP_COND_UNKNOWN;
12442 				}
12443 				mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst,
12444 				    cport));
12445 			}
12446 			if ((DEVI_IS_DEVICE_OFFLINE(tdip)) ||
12447 			    (DEVI_IS_DEVICE_DOWN(tdip))) {
12448 				ap_state->ap_ostate =
12449 				    AP_OSTATE_UNCONFIGURED;
12450 			} else {
12451 				ap_state->ap_ostate =
12452 				    AP_OSTATE_CONFIGURED;
12453 			}
12454 			mutex_exit(&(DEVI(tdip)->devi_lock));
12455 			ndi_devi_exit(dip, circ);
12456 		} else {
12457 			ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
12458 			ap_state->ap_condition = AP_COND_UNKNOWN;
12459 		}
12460 		break;
12461 	}
12462 	default:
12463 		ap_state->ap_rstate = AP_RSTATE_CONNECTED;
12464 		ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
12465 		ap_state->ap_condition = AP_COND_UNKNOWN;
12466 		/*
12467 		 * This is actually internal error condition (non fatal),
12468 		 * because we have already checked all defined device types.
12469 		 */
12470 		SATA_LOG_D((sata_hba_inst, CE_WARN,
12471 		    "sata_cfgadm_state: Internal error: "
12472 		    "unknown device type"));
12473 		break;
12474 	}
12475 }
12476 
12477 
12478 /*
12479  * Process ioctl get device path request.
12480  *
12481  * NOTE: Port multiplier code is not completed nor tested.
12482  */
12483 static int
12484 sata_ioctl_get_device_path(sata_hba_inst_t *sata_hba_inst,
12485     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
12486 {
12487 	char path[MAXPATHLEN];
12488 	uint32_t size;
12489 	dev_info_t *tdip;
12490 
12491 	(void) strcpy(path, "/devices");
12492 	if ((tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
12493 	    &sata_device->satadev_addr)) == NULL) {
12494 		/*
12495 		 * No such device. If this is a request for a size, do not
12496 		 * return EINVAL for non-existing target, because cfgadm
12497 		 * will then indicate a meaningless ioctl failure.
12498 		 * If this is a request for a path, indicate invalid
12499 		 * argument.
12500 		 */
12501 		if (ioc->get_size == 0)
12502 			return (EINVAL);
12503 	} else {
12504 		(void) ddi_pathname(tdip, path + strlen(path));
12505 	}
12506 	size = strlen(path) + 1;
12507 
12508 	if (ioc->get_size != 0) {
12509 		if (ddi_copyout((void *)&size, ioc->buf, ioc->bufsiz,
12510 		    mode) != 0)
12511 			return (EFAULT);
12512 	} else {
12513 		if (ioc->bufsiz != size)
12514 			return (EINVAL);
12515 
12516 		else if (ddi_copyout((void *)&path, ioc->buf, ioc->bufsiz,
12517 		    mode) != 0)
12518 			return (EFAULT);
12519 	}
12520 	return (0);
12521 }
12522 
12523 /*
12524  * Process ioctl get attachment point type request.
12525  *
12526  * NOTE: Port multiplier code is not completed nor tested.
12527  */
12528 static	int
12529 sata_ioctl_get_ap_type(sata_hba_inst_t *sata_hba_inst,
12530     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
12531 {
12532 	uint32_t	type_len;
12533 	const char	*ap_type;
12534 	int		dev_type;
12535 
12536 	if (sata_device->satadev_addr.qual == SATA_ADDR_CPORT)
12537 		dev_type = SATA_CPORT_DEV_TYPE(sata_hba_inst,
12538 		    sata_device->satadev_addr.cport);
12539 	else /* pmport */
12540 		dev_type = SATA_PMPORT_DEV_TYPE(sata_hba_inst,
12541 		    sata_device->satadev_addr.cport,
12542 		    sata_device->satadev_addr.pmport);
12543 
12544 	switch (dev_type) {
12545 	case SATA_DTYPE_NONE:
12546 		ap_type = "port";
12547 		break;
12548 
12549 	case SATA_DTYPE_ATADISK:
12550 	case SATA_DTYPE_ATAPIDISK:
12551 		ap_type = "disk";
12552 		break;
12553 
12554 	case SATA_DTYPE_ATAPICD:
12555 		ap_type = "cd/dvd";
12556 		break;
12557 
12558 	case SATA_DTYPE_ATAPITAPE:
12559 		ap_type = "tape";
12560 		break;
12561 
12562 	case SATA_DTYPE_PMULT:
12563 		ap_type = "pmult";
12564 		break;
12565 
12566 	case SATA_DTYPE_UNKNOWN:
12567 		ap_type = "unknown";
12568 		break;
12569 
12570 	default:
12571 		ap_type = "unsupported";
12572 		break;
12573 
12574 	} /* end of dev_type switch */
12575 
12576 	type_len = strlen(ap_type) + 1;
12577 
12578 	if (ioc->get_size) {
12579 		if (ddi_copyout((void *)&type_len, ioc->buf, ioc->bufsiz,
12580 		    mode) != 0)
12581 			return (EFAULT);
12582 	} else {
12583 		if (ioc->bufsiz != type_len)
12584 			return (EINVAL);
12585 
12586 		if (ddi_copyout((void *)ap_type, ioc->buf,
12587 		    ioc->bufsiz, mode) != 0)
12588 			return (EFAULT);
12589 	}
12590 	return (0);
12591 
12592 }
12593 
12594 /*
12595  * Process ioctl get device model info request.
12596  * This operation should return to cfgadm the device model
12597  * information string
12598  *
12599  * NOTE: Port multiplier code is not completed nor tested.
12600  */
12601 static	int
12602 sata_ioctl_get_model_info(sata_hba_inst_t *sata_hba_inst,
12603     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
12604 {
12605 	sata_drive_info_t *sdinfo;
12606 	uint32_t info_len;
12607 	char ap_info[SATA_ID_MODEL_LEN + 1];
12608 
12609 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
12610 	    sata_device->satadev_addr.cport)->cport_mutex);
12611 	if (sata_device->satadev_addr.qual == SATA_ADDR_CPORT)
12612 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
12613 		    sata_device->satadev_addr.cport);
12614 	else /* port multiplier */
12615 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst,
12616 		    sata_device->satadev_addr.cport,
12617 		    sata_device->satadev_addr.pmport);
12618 	if (sdinfo == NULL) {
12619 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
12620 		    sata_device->satadev_addr.cport)->cport_mutex);
12621 		return (EINVAL);
12622 	}
12623 
12624 #ifdef	_LITTLE_ENDIAN
12625 	swab(sdinfo->satadrv_id.ai_model, ap_info, SATA_ID_MODEL_LEN);
12626 #else	/* _LITTLE_ENDIAN */
12627 	bcopy(sdinfo->satadrv_id.ai_model, ap_info, SATA_ID_MODEL_LEN);
12628 #endif	/* _LITTLE_ENDIAN */
12629 
12630 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
12631 	    sata_device->satadev_addr.cport)->cport_mutex);
12632 
12633 	ap_info[SATA_ID_MODEL_LEN] = '\0';
12634 
12635 	info_len = strlen(ap_info) + 1;
12636 
12637 	if (ioc->get_size) {
12638 		if (ddi_copyout((void *)&info_len, ioc->buf, ioc->bufsiz,
12639 		    mode) != 0)
12640 			return (EFAULT);
12641 	} else {
12642 		if (ioc->bufsiz < info_len)
12643 			return (EINVAL);
12644 		if (ddi_copyout((void *)ap_info, ioc->buf, ioc->bufsiz,
12645 		    mode) != 0)
12646 			return (EFAULT);
12647 	}
12648 	return (0);
12649 }
12650 
12651 
12652 /*
12653  * Process ioctl get device firmware revision info request.
12654  * This operation should return to cfgadm the device firmware revision
12655  * information string
12656  *
12657  * NOTE: Port multiplier code is not completed nor tested.
12658  */
12659 static	int
12660 sata_ioctl_get_revfirmware_info(sata_hba_inst_t *sata_hba_inst,
12661     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
12662 {
12663 	sata_drive_info_t *sdinfo;
12664 	uint32_t info_len;
12665 	char ap_info[SATA_ID_FW_LEN + 1];
12666 
12667 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
12668 	    sata_device->satadev_addr.cport)->cport_mutex);
12669 	if (sata_device->satadev_addr.qual == SATA_ADDR_CPORT)
12670 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
12671 		    sata_device->satadev_addr.cport);
12672 	else /* port multiplier */
12673 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst,
12674 		    sata_device->satadev_addr.cport,
12675 		    sata_device->satadev_addr.pmport);
12676 	if (sdinfo == NULL) {
12677 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
12678 		    sata_device->satadev_addr.cport)->cport_mutex);
12679 		return (EINVAL);
12680 	}
12681 
12682 #ifdef	_LITTLE_ENDIAN
12683 	swab(sdinfo->satadrv_id.ai_fw, ap_info, SATA_ID_FW_LEN);
12684 #else	/* _LITTLE_ENDIAN */
12685 	bcopy(sdinfo->satadrv_id.ai_fw, ap_info, SATA_ID_FW_LEN);
12686 #endif	/* _LITTLE_ENDIAN */
12687 
12688 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
12689 	    sata_device->satadev_addr.cport)->cport_mutex);
12690 
12691 	ap_info[SATA_ID_FW_LEN] = '\0';
12692 
12693 	info_len = strlen(ap_info) + 1;
12694 
12695 	if (ioc->get_size) {
12696 		if (ddi_copyout((void *)&info_len, ioc->buf, ioc->bufsiz,
12697 		    mode) != 0)
12698 			return (EFAULT);
12699 	} else {
12700 		if (ioc->bufsiz < info_len)
12701 			return (EINVAL);
12702 		if (ddi_copyout((void *)ap_info, ioc->buf, ioc->bufsiz,
12703 		    mode) != 0)
12704 			return (EFAULT);
12705 	}
12706 	return (0);
12707 }
12708 
12709 
12710 /*
12711  * Process ioctl get device serial number info request.
12712  * This operation should return to cfgadm the device serial number string.
12713  *
12714  * NOTE: Port multiplier code is not completed nor tested.
12715  */
12716 static	int
12717 sata_ioctl_get_serialnumber_info(sata_hba_inst_t *sata_hba_inst,
12718     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
12719 {
12720 	sata_drive_info_t *sdinfo;
12721 	uint32_t info_len;
12722 	char ap_info[SATA_ID_SERIAL_LEN + 1];
12723 
12724 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
12725 	    sata_device->satadev_addr.cport)->cport_mutex);
12726 	if (sata_device->satadev_addr.qual == SATA_ADDR_CPORT)
12727 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
12728 		    sata_device->satadev_addr.cport);
12729 	else /* port multiplier */
12730 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst,
12731 		    sata_device->satadev_addr.cport,
12732 		    sata_device->satadev_addr.pmport);
12733 	if (sdinfo == NULL) {
12734 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
12735 		    sata_device->satadev_addr.cport)->cport_mutex);
12736 		return (EINVAL);
12737 	}
12738 
12739 #ifdef	_LITTLE_ENDIAN
12740 	swab(sdinfo->satadrv_id.ai_drvser, ap_info, SATA_ID_SERIAL_LEN);
12741 #else	/* _LITTLE_ENDIAN */
12742 	bcopy(sdinfo->satadrv_id.ai_drvser, ap_info, SATA_ID_SERIAL_LEN);
12743 #endif	/* _LITTLE_ENDIAN */
12744 
12745 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
12746 	    sata_device->satadev_addr.cport)->cport_mutex);
12747 
12748 	ap_info[SATA_ID_SERIAL_LEN] = '\0';
12749 
12750 	info_len = strlen(ap_info) + 1;
12751 
12752 	if (ioc->get_size) {
12753 		if (ddi_copyout((void *)&info_len, ioc->buf, ioc->bufsiz,
12754 		    mode) != 0)
12755 			return (EFAULT);
12756 	} else {
12757 		if (ioc->bufsiz < info_len)
12758 			return (EINVAL);
12759 		if (ddi_copyout((void *)ap_info, ioc->buf, ioc->bufsiz,
12760 		    mode) != 0)
12761 			return (EFAULT);
12762 	}
12763 	return (0);
12764 }
12765 
12766 
12767 /*
12768  * Preset scsi extended sense data (to NO SENSE)
12769  * First 18 bytes of the sense data are preset to current valid sense
12770  * with a key NO SENSE data.
12771  *
12772  * Returns void
12773  */
12774 static void
12775 sata_fixed_sense_data_preset(struct scsi_extended_sense *sense)
12776 {
12777 	sense->es_valid = 1;		/* Valid sense */
12778 	sense->es_class = CLASS_EXTENDED_SENSE;	/* 0x70 - current err */
12779 	sense->es_key = KEY_NO_SENSE;
12780 	sense->es_info_1 = 0;
12781 	sense->es_info_2 = 0;
12782 	sense->es_info_3 = 0;
12783 	sense->es_info_4 = 0;
12784 	sense->es_add_len = 10;	/* Additional length - replace with a def */
12785 	sense->es_cmd_info[0] = 0;
12786 	sense->es_cmd_info[1] = 0;
12787 	sense->es_cmd_info[2] = 0;
12788 	sense->es_cmd_info[3] = 0;
12789 	sense->es_add_code = 0;
12790 	sense->es_qual_code = 0;
12791 }
12792 
12793 /*
12794  * Register a legacy cmdk-style devid for the target (disk) device.
12795  *
12796  * Note: This function is called only when the HBA devinfo node has the
12797  * property "use-cmdk-devid-format" set. This property indicates that
12798  * devid compatible with old cmdk (target) driver is to be generated
12799  * for any target device attached to this controller. This will take
12800  * precedence over the devid generated by sd (target) driver.
12801  * This function is derived from cmdk_devid_setup() function in cmdk.c.
12802  */
12803 static void
12804 sata_target_devid_register(dev_info_t *dip, sata_drive_info_t *sdinfo)
12805 {
12806 	char	*hwid;
12807 	int	modlen;
12808 	int	serlen;
12809 	int	rval;
12810 	ddi_devid_t	devid;
12811 
12812 	/*
12813 	 * device ID is a concatanation of model number, "=", serial number.
12814 	 */
12815 	hwid = kmem_zalloc(LEGACY_HWID_LEN, KM_SLEEP);
12816 	bcopy(&sdinfo->satadrv_id.ai_model, hwid,
12817 	    sizeof (sdinfo->satadrv_id.ai_model));
12818 	swab(hwid, hwid, sizeof (sdinfo->satadrv_id.ai_model));
12819 	modlen = sata_check_modser(hwid, sizeof (sdinfo->satadrv_id.ai_model));
12820 	if (modlen == 0)
12821 		goto err;
12822 	hwid[modlen++] = '=';
12823 	bcopy(&sdinfo->satadrv_id.ai_drvser, &hwid[modlen],
12824 	    sizeof (sdinfo->satadrv_id.ai_drvser));
12825 	swab(&hwid[modlen], &hwid[modlen],
12826 	    sizeof (sdinfo->satadrv_id.ai_drvser));
12827 	serlen = sata_check_modser(&hwid[modlen],
12828 	    sizeof (sdinfo->satadrv_id.ai_drvser));
12829 	if (serlen == 0)
12830 		goto err;
12831 	hwid[modlen + serlen] = 0; /* terminate the hwid string */
12832 
12833 	/* initialize/register devid */
12834 	if ((rval = ddi_devid_init(dip, DEVID_ATA_SERIAL,
12835 	    (ushort_t)(modlen + serlen), hwid, &devid)) == DDI_SUCCESS) {
12836 		rval = ddi_devid_register(dip, devid);
12837 		/*
12838 		 * Free up the allocated devid buffer.
12839 		 * NOTE: This doesn't mean unregistering devid.
12840 		 */
12841 		ddi_devid_free(devid);
12842 	}
12843 
12844 	if (rval != DDI_SUCCESS)
12845 		cmn_err(CE_WARN, "sata: failed to create devid for the disk"
12846 		    " on port %d", sdinfo->satadrv_addr.cport);
12847 err:
12848 	kmem_free(hwid, LEGACY_HWID_LEN);
12849 }
12850 
12851 /*
12852  * valid model/serial string must contain a non-zero non-space characters.
12853  * trim trailing spaces/NULLs.
12854  */
12855 static int
12856 sata_check_modser(char *buf, int buf_len)
12857 {
12858 	boolean_t ret;
12859 	char *s;
12860 	int i;
12861 	int tb;
12862 	char ch;
12863 
12864 	ret = B_FALSE;
12865 	s = buf;
12866 	for (i = 0; i < buf_len; i++) {
12867 		ch = *s++;
12868 		if (ch != ' ' && ch != '\0')
12869 			tb = i + 1;
12870 		if (ch != ' ' && ch != '\0' && ch != '0')
12871 			ret = B_TRUE;
12872 	}
12873 
12874 	if (ret == B_FALSE)
12875 		return (0); /* invalid string */
12876 
12877 	return (tb); /* return length */
12878 }
12879 
12880 /*
12881  * sata_set_drive_features function compares current device features setting
12882  * with the saved device features settings and, if there is a difference,
12883  * it restores device features setting to the previously saved state.
12884  * It also arbitrarily tries to select the highest supported DMA mode.
12885  * Device Identify or Identify Packet Device data has to be current.
12886  * At the moment read ahead and write cache are considered for all devices.
12887  * For atapi devices, Removable Media Status Notification is set in addition
12888  * to common features.
12889  *
12890  * This function cannot be called in the interrupt context (it may sleep).
12891  *
12892  * The input argument sdinfo should point to the drive info structure
12893  * to be updated after features are set. Note, that only
12894  * device (packet) identify data is updated, not the flags indicating the
12895  * supported features.
12896  *
12897  * Returns SATA_SUCCESS if successful or there was nothing to do.
12898  * Device Identify data in the drive info structure pointed to by the sdinfo
12899  * arguments is updated even when no features were set or changed.
12900  *
12901  * Returns SATA_FAILURE if device features could not be set or DMA mode
12902  * for a disk cannot be set and device identify data cannot be fetched.
12903  *
12904  * Returns SATA_RETRY if device features could not be set (other than disk
12905  * DMA mode) but the device identify data was fetched successfully.
12906  *
12907  * Note: This function may fail the port, making it inaccessible.
12908  * In such case the explicit port disconnect/connect or physical device
12909  * detach/attach is required to re-evaluate port state again.
12910  */
12911 
12912 static int
12913 sata_set_drive_features(sata_hba_inst_t *sata_hba_inst,
12914     sata_drive_info_t *sdinfo, int restore)
12915 {
12916 	int rval = SATA_SUCCESS;
12917 	int rval_set;
12918 	sata_drive_info_t new_sdinfo;
12919 	char *finfo = "sata_set_drive_features: cannot";
12920 	char *finfox;
12921 	int cache_op;
12922 
12923 	bzero(&new_sdinfo, sizeof (sata_drive_info_t));
12924 	new_sdinfo.satadrv_addr = sdinfo->satadrv_addr;
12925 	new_sdinfo.satadrv_type = sdinfo->satadrv_type;
12926 	if (sata_fetch_device_identify_data(sata_hba_inst, &new_sdinfo) != 0) {
12927 		/*
12928 		 * Cannot get device identification - caller may retry later
12929 		 */
12930 		SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
12931 		    "%s fetch device identify data\n", finfo);
12932 		return (SATA_FAILURE);
12933 	}
12934 	finfox = (restore != 0) ? " restore device features" :
12935 	    " initialize device features\n";
12936 
12937 	switch (sdinfo->satadrv_type) {
12938 	case SATA_DTYPE_ATADISK:
12939 		/* Arbitrarily set UDMA mode */
12940 		if (sata_set_dma_mode(sata_hba_inst, &new_sdinfo) !=
12941 		    SATA_SUCCESS) {
12942 			SATA_LOG_D((sata_hba_inst, CE_WARN,
12943 			    "%s set UDMA mode\n", finfo));
12944 			return (SATA_FAILURE);
12945 		}
12946 		break;
12947 	case SATA_DTYPE_ATAPICD:
12948 	case SATA_DTYPE_ATAPITAPE:
12949 	case SATA_DTYPE_ATAPIDISK:
12950 		/*  Set Removable Media Status Notification, if necessary */
12951 		if (SATA_RM_NOTIFIC_SUPPORTED(new_sdinfo.satadrv_id) &&
12952 		    restore != 0) {
12953 			if (((sdinfo->satadrv_settings & SATA_DEV_RMSN) &&
12954 			    (!SATA_RM_NOTIFIC_ENABLED(new_sdinfo.satadrv_id)))||
12955 			    ((!(sdinfo->satadrv_settings & SATA_DEV_RMSN)) &&
12956 			    SATA_RM_NOTIFIC_ENABLED(new_sdinfo.satadrv_id))) {
12957 				/* Current setting does not match saved one */
12958 				if (sata_set_rmsn(sata_hba_inst, sdinfo,
12959 				    sdinfo->satadrv_settings &
12960 				    SATA_DEV_RMSN) != SATA_SUCCESS)
12961 					rval = SATA_FAILURE;
12962 			}
12963 		}
12964 		/*
12965 		 * We have to set Multiword DMA or UDMA, if it is supported, as
12966 		 * we want to use DMA transfer mode whenever possible.
12967 		 * Some devices require explicit setting of the DMA mode.
12968 		 */
12969 		if (new_sdinfo.satadrv_id.ai_cap & SATA_DMA_SUPPORT) {
12970 			/* Set highest supported DMA mode */
12971 			if (sata_set_dma_mode(sata_hba_inst, &new_sdinfo) !=
12972 			    SATA_SUCCESS) {
12973 				SATA_LOG_D((sata_hba_inst, CE_WARN,
12974 				    "%s set UDMA mode\n", finfo));
12975 				rval = SATA_FAILURE;
12976 			}
12977 		}
12978 		break;
12979 	}
12980 
12981 	if (!SATA_READ_AHEAD_SUPPORTED(new_sdinfo.satadrv_id) &&
12982 	    !SATA_WRITE_CACHE_SUPPORTED(new_sdinfo.satadrv_id)) {
12983 		/*
12984 		 * neither READ AHEAD nor WRITE CACHE is supported
12985 		 * - do nothing
12986 		 */
12987 		SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
12988 		    "settable features not supported\n", NULL);
12989 		goto update_sdinfo;
12990 	}
12991 
12992 	if ((SATA_READ_AHEAD_ENABLED(new_sdinfo.satadrv_id) &&
12993 	    (sdinfo->satadrv_settings & SATA_DEV_READ_AHEAD)) &&
12994 	    (SATA_WRITE_CACHE_ENABLED(new_sdinfo.satadrv_id) &&
12995 	    (sdinfo->satadrv_settings & SATA_DEV_WRITE_CACHE))) {
12996 		/*
12997 		 * both READ AHEAD and WRITE CACHE are enabled
12998 		 * - Nothing to do
12999 		 */
13000 		SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
13001 		    "no device features to set\n", NULL);
13002 		goto update_sdinfo;
13003 	}
13004 
13005 	cache_op = 0;
13006 
13007 	if (SATA_READ_AHEAD_SUPPORTED(new_sdinfo.satadrv_id)) {
13008 		if ((sdinfo->satadrv_settings & SATA_DEV_READ_AHEAD) &&
13009 		    !SATA_READ_AHEAD_ENABLED(new_sdinfo.satadrv_id)) {
13010 			/* Enable read ahead / read cache */
13011 			cache_op = SATAC_SF_ENABLE_READ_AHEAD;
13012 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
13013 			    "enabling read cache\n", NULL);
13014 		} else if (!(sdinfo->satadrv_settings & SATA_DEV_READ_AHEAD) &&
13015 		    SATA_READ_AHEAD_ENABLED(new_sdinfo.satadrv_id)) {
13016 			/* Disable read ahead  / read cache */
13017 			cache_op = SATAC_SF_DISABLE_READ_AHEAD;
13018 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
13019 			    "disabling read cache\n", NULL);
13020 		}
13021 
13022 		if (cache_op != 0) {
13023 			/* Try to set read cache mode */
13024 			rval_set = sata_set_cache_mode(sata_hba_inst,
13025 			    &new_sdinfo, cache_op);
13026 			if (rval != SATA_FAILURE && rval_set != SATA_SUCCESS)
13027 				rval = rval_set;
13028 		}
13029 	}
13030 
13031 	cache_op = 0;
13032 
13033 	if (SATA_WRITE_CACHE_SUPPORTED(new_sdinfo.satadrv_id)) {
13034 		if ((sdinfo->satadrv_settings & SATA_DEV_WRITE_CACHE) &&
13035 		    !SATA_WRITE_CACHE_ENABLED(new_sdinfo.satadrv_id)) {
13036 			/* Enable write cache */
13037 			cache_op = SATAC_SF_ENABLE_WRITE_CACHE;
13038 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
13039 			    "enabling write cache\n", NULL);
13040 		} else if (!(sdinfo->satadrv_settings & SATA_DEV_WRITE_CACHE) &&
13041 		    SATA_WRITE_CACHE_ENABLED(new_sdinfo.satadrv_id)) {
13042 			/* Disable write cache */
13043 			cache_op = SATAC_SF_DISABLE_WRITE_CACHE;
13044 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
13045 			    "disabling write cache\n", NULL);
13046 		}
13047 
13048 		if (cache_op != 0) {
13049 			/* Try to set write cache mode */
13050 			rval_set = sata_set_cache_mode(sata_hba_inst,
13051 			    &new_sdinfo, cache_op);
13052 			if (rval != SATA_FAILURE && rval_set != SATA_SUCCESS)
13053 				rval = rval_set;
13054 		}
13055 	}
13056 	if (rval != SATA_SUCCESS)
13057 		SATA_LOG_D((sata_hba_inst, CE_WARN,
13058 		    "%s %s", finfo, finfox));
13059 
13060 update_sdinfo:
13061 	/*
13062 	 * We need to fetch Device Identify data again
13063 	 */
13064 	if (sata_fetch_device_identify_data(sata_hba_inst, &new_sdinfo) != 0) {
13065 		/*
13066 		 * Cannot get device identification - retry later
13067 		 */
13068 		SATA_LOG_D((sata_hba_inst, CE_WARN,
13069 		    "%s re-fetch device identify data\n", finfo));
13070 		rval = SATA_FAILURE;
13071 	}
13072 	/* Copy device sata info. */
13073 	sdinfo->satadrv_id = new_sdinfo.satadrv_id;
13074 
13075 	return (rval);
13076 }
13077 
13078 
13079 /*
13080  *
13081  * Returns 1 if threshold exceeded, 0 if threshold not exceeded, -1 if
13082  * unable to determine.
13083  *
13084  * Cannot be called in an interrupt context.
13085  *
13086  * Called by sata_build_lsense_page_2f()
13087  */
13088 
13089 static int
13090 sata_fetch_smart_return_status(sata_hba_inst_t *sata_hba_inst,
13091     sata_drive_info_t *sdinfo)
13092 {
13093 	sata_pkt_t *spkt;
13094 	sata_cmd_t *scmd;
13095 	sata_pkt_txlate_t *spx;
13096 	int rval;
13097 
13098 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
13099 	spx->txlt_sata_hba_inst = sata_hba_inst;
13100 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
13101 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
13102 	if (spkt == NULL) {
13103 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
13104 		return (-1);
13105 	}
13106 	/* address is needed now */
13107 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13108 
13109 
13110 	/* Fill sata_pkt */
13111 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13112 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
13113 	/* Synchronous mode, no callback */
13114 	spkt->satapkt_comp = NULL;
13115 	/* Timeout 30s */
13116 	spkt->satapkt_time = sata_default_pkt_time;
13117 
13118 	scmd = &spkt->satapkt_cmd;
13119 	scmd->satacmd_flags.sata_special_regs = B_TRUE;
13120 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
13121 
13122 	/* Set up which registers need to be returned */
13123 	scmd->satacmd_flags.sata_copy_out_lba_mid_lsb = B_TRUE;
13124 	scmd->satacmd_flags.sata_copy_out_lba_high_lsb = B_TRUE;
13125 
13126 	/* Build SMART_RETURN_STATUS cmd in the sata_pkt */
13127 	scmd->satacmd_addr_type = 0;		/* N/A */
13128 	scmd->satacmd_sec_count_lsb = 0;	/* N/A */
13129 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
13130 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
13131 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
13132 	scmd->satacmd_features_reg = SATA_SMART_RETURN_STATUS;
13133 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
13134 	scmd->satacmd_cmd_reg = SATAC_SMART;
13135 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
13136 	    sdinfo->satadrv_addr.cport)));
13137 
13138 
13139 	/* Send pkt to SATA HBA driver */
13140 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
13141 	    SATA_TRAN_ACCEPTED ||
13142 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
13143 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
13144 		    sdinfo->satadrv_addr.cport)));
13145 		/*
13146 		 * Whoops, no SMART RETURN STATUS
13147 		 */
13148 		rval = -1;
13149 	} else {
13150 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
13151 		    sdinfo->satadrv_addr.cport)));
13152 		if (scmd->satacmd_error_reg & SATA_ERROR_ABORT) {
13153 			rval = -1;
13154 			goto fail;
13155 		}
13156 		if (scmd->satacmd_status_reg & SATA_STATUS_ERR) {
13157 			rval = -1;
13158 			goto fail;
13159 		}
13160 		if ((scmd->satacmd_lba_mid_lsb == SMART_MAGIC_VAL_1) &&
13161 		    (scmd->satacmd_lba_high_lsb == SMART_MAGIC_VAL_2))
13162 			rval = 0;
13163 		else if ((scmd->satacmd_lba_mid_lsb == SMART_MAGIC_VAL_3) &&
13164 		    (scmd->satacmd_lba_high_lsb == SMART_MAGIC_VAL_4))
13165 			rval = 1;
13166 		else {
13167 			rval = -1;
13168 			goto fail;
13169 		}
13170 	}
13171 fail:
13172 	/* Free allocated resources */
13173 	sata_pkt_free(spx);
13174 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
13175 
13176 	return (rval);
13177 }
13178 
13179 /*
13180  *
13181  * Returns 0 if succeeded, -1 otherwise
13182  *
13183  * Cannot be called in an interrupt context.
13184  *
13185  */
13186 static int
13187 sata_fetch_smart_data(
13188 	sata_hba_inst_t *sata_hba_inst,
13189 	sata_drive_info_t *sdinfo,
13190 	struct smart_data *smart_data)
13191 {
13192 	sata_pkt_t *spkt;
13193 	sata_cmd_t *scmd;
13194 	sata_pkt_txlate_t *spx;
13195 	int rval;
13196 
13197 #if ! defined(lint)
13198 	ASSERT(sizeof (struct smart_data) == 512);
13199 #endif
13200 
13201 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
13202 	spx->txlt_sata_hba_inst = sata_hba_inst;
13203 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
13204 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
13205 	if (spkt == NULL) {
13206 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
13207 		return (-1);
13208 	}
13209 	/* address is needed now */
13210 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13211 
13212 
13213 	/* Fill sata_pkt */
13214 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13215 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
13216 	/* Synchronous mode, no callback */
13217 	spkt->satapkt_comp = NULL;
13218 	/* Timeout 30s */
13219 	spkt->satapkt_time = sata_default_pkt_time;
13220 
13221 	scmd = &spkt->satapkt_cmd;
13222 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
13223 
13224 	/*
13225 	 * Allocate buffer for SMART data
13226 	 */
13227 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
13228 	    sizeof (struct smart_data));
13229 	if (scmd->satacmd_bp == NULL) {
13230 		sata_pkt_free(spx);
13231 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
13232 		SATA_LOG_D((sata_hba_inst, CE_WARN,
13233 		    "sata_fetch_smart_data: "
13234 		    "cannot allocate buffer"));
13235 		return (-1);
13236 	}
13237 
13238 
13239 	/* Build SMART_READ_DATA cmd in the sata_pkt */
13240 	scmd->satacmd_addr_type = 0;		/* N/A */
13241 	scmd->satacmd_sec_count_lsb = 0;	/* N/A */
13242 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
13243 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
13244 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
13245 	scmd->satacmd_features_reg = SATA_SMART_READ_DATA;
13246 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
13247 	scmd->satacmd_cmd_reg = SATAC_SMART;
13248 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
13249 	    sdinfo->satadrv_addr.cport)));
13250 
13251 	/* Send pkt to SATA HBA driver */
13252 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
13253 	    SATA_TRAN_ACCEPTED ||
13254 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
13255 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
13256 		    sdinfo->satadrv_addr.cport)));
13257 		/*
13258 		 * Whoops, no SMART DATA available
13259 		 */
13260 		rval = -1;
13261 		goto fail;
13262 	} else {
13263 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
13264 		    sdinfo->satadrv_addr.cport)));
13265 		if (spx->txlt_buf_dma_handle != NULL) {
13266 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
13267 			    DDI_DMA_SYNC_FORKERNEL);
13268 			ASSERT(rval == DDI_SUCCESS);
13269 		}
13270 		bcopy(scmd->satacmd_bp->b_un.b_addr, (uint8_t *)smart_data,
13271 		    sizeof (struct smart_data));
13272 	}
13273 
13274 fail:
13275 	/* Free allocated resources */
13276 	sata_free_local_buffer(spx);
13277 	sata_pkt_free(spx);
13278 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
13279 
13280 	return (rval);
13281 }
13282 
13283 /*
13284  * Used by LOG SENSE page 0x10
13285  * Reads (in synchronous mode) the self test log data using Read Log Ext cmd.
13286  * Note: cannot be called in the interrupt context.
13287  *
13288  * return 0 for success, -1 otherwise
13289  *
13290  */
13291 static int
13292 sata_ext_smart_selftest_read_log(
13293 	sata_hba_inst_t *sata_hba_inst,
13294 	sata_drive_info_t *sdinfo,
13295 	struct smart_ext_selftest_log *ext_selftest_log,
13296 	uint16_t block_num)
13297 {
13298 	sata_pkt_txlate_t *spx;
13299 	sata_pkt_t *spkt;
13300 	sata_cmd_t *scmd;
13301 	int rval;
13302 
13303 #if ! defined(lint)
13304 	ASSERT(sizeof (struct smart_ext_selftest_log) == 512);
13305 #endif
13306 
13307 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
13308 	spx->txlt_sata_hba_inst = sata_hba_inst;
13309 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
13310 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
13311 	if (spkt == NULL) {
13312 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
13313 		return (-1);
13314 	}
13315 	/* address is needed now */
13316 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13317 
13318 
13319 	/* Fill sata_pkt */
13320 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13321 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
13322 	/* Synchronous mode, no callback */
13323 	spkt->satapkt_comp = NULL;
13324 	/* Timeout 30s */
13325 	spkt->satapkt_time = sata_default_pkt_time;
13326 
13327 	scmd = &spkt->satapkt_cmd;
13328 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
13329 
13330 	/*
13331 	 * Allocate buffer for SMART extended self-test log
13332 	 */
13333 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
13334 	    sizeof (struct smart_ext_selftest_log));
13335 	if (scmd->satacmd_bp == NULL) {
13336 		sata_pkt_free(spx);
13337 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
13338 		SATA_LOG_D((sata_hba_inst, CE_WARN,
13339 		    "sata_ext_smart_selftest_log: "
13340 		    "cannot allocate buffer"));
13341 		return (-1);
13342 	}
13343 
13344 	/* Build READ LOG EXT w/ extended self-test log cmd in the sata_pkt */
13345 	scmd->satacmd_addr_type = ATA_ADDR_LBA48;
13346 	scmd->satacmd_sec_count_lsb = 1;	/* One sector of selftest log */
13347 	scmd->satacmd_sec_count_msb = 0;	/* One sector of selftest log */
13348 	scmd->satacmd_lba_low_lsb = EXT_SMART_SELFTEST_LOG_PAGE;
13349 	scmd->satacmd_lba_low_msb = 0;
13350 	scmd->satacmd_lba_mid_lsb = block_num & 0xff;
13351 	scmd->satacmd_lba_mid_msb = block_num >> 8;
13352 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
13353 	scmd->satacmd_cmd_reg = SATAC_READ_LOG_EXT;
13354 
13355 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
13356 	    sdinfo->satadrv_addr.cport)));
13357 
13358 	/* Send pkt to SATA HBA driver */
13359 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
13360 	    SATA_TRAN_ACCEPTED ||
13361 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
13362 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
13363 		    sdinfo->satadrv_addr.cport)));
13364 
13365 		/*
13366 		 * Whoops, no SMART selftest log info available
13367 		 */
13368 		rval = -1;
13369 		goto fail;
13370 	} else {
13371 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
13372 		    sdinfo->satadrv_addr.cport)));
13373 
13374 		if (spx->txlt_buf_dma_handle != NULL) {
13375 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
13376 			    DDI_DMA_SYNC_FORKERNEL);
13377 			ASSERT(rval == DDI_SUCCESS);
13378 		}
13379 		bcopy(scmd->satacmd_bp->b_un.b_addr,
13380 		    (uint8_t *)ext_selftest_log,
13381 		    sizeof (struct smart_ext_selftest_log));
13382 		rval = 0;
13383 	}
13384 
13385 fail:
13386 	/* Free allocated resources */
13387 	sata_free_local_buffer(spx);
13388 	sata_pkt_free(spx);
13389 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
13390 
13391 	return (rval);
13392 }
13393 
13394 /*
13395  * Returns 0 for success, -1 otherwise
13396  *
13397  * SMART self-test log data is returned in buffer pointed to by selftest_log
13398  */
13399 static int
13400 sata_smart_selftest_log(
13401 	sata_hba_inst_t *sata_hba_inst,
13402 	sata_drive_info_t *sdinfo,
13403 	struct smart_selftest_log *selftest_log)
13404 {
13405 	sata_pkt_t *spkt;
13406 	sata_cmd_t *scmd;
13407 	sata_pkt_txlate_t *spx;
13408 	int rval;
13409 
13410 #if ! defined(lint)
13411 	ASSERT(sizeof (struct smart_selftest_log) == 512);
13412 #endif
13413 
13414 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
13415 	spx->txlt_sata_hba_inst = sata_hba_inst;
13416 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
13417 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
13418 	if (spkt == NULL) {
13419 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
13420 		return (-1);
13421 	}
13422 	/* address is needed now */
13423 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13424 
13425 
13426 	/* Fill sata_pkt */
13427 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13428 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
13429 	/* Synchronous mode, no callback */
13430 	spkt->satapkt_comp = NULL;
13431 	/* Timeout 30s */
13432 	spkt->satapkt_time = sata_default_pkt_time;
13433 
13434 	scmd = &spkt->satapkt_cmd;
13435 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
13436 
13437 	/*
13438 	 * Allocate buffer for SMART SELFTEST LOG
13439 	 */
13440 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
13441 	    sizeof (struct smart_selftest_log));
13442 	if (scmd->satacmd_bp == NULL) {
13443 		sata_pkt_free(spx);
13444 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
13445 		SATA_LOG_D((sata_hba_inst, CE_WARN,
13446 		    "sata_smart_selftest_log: "
13447 		    "cannot allocate buffer"));
13448 		return (-1);
13449 	}
13450 
13451 	/* Build SMART_READ_LOG cmd in the sata_pkt */
13452 	scmd->satacmd_addr_type = 0;		/* N/A */
13453 	scmd->satacmd_sec_count_lsb = 1;	/* One sector of SMART log */
13454 	scmd->satacmd_lba_low_lsb = SMART_SELFTEST_LOG_PAGE;
13455 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
13456 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
13457 	scmd->satacmd_features_reg = SATA_SMART_READ_LOG;
13458 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
13459 	scmd->satacmd_cmd_reg = SATAC_SMART;
13460 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
13461 	    sdinfo->satadrv_addr.cport)));
13462 
13463 	/* Send pkt to SATA HBA driver */
13464 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
13465 	    SATA_TRAN_ACCEPTED ||
13466 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
13467 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
13468 		    sdinfo->satadrv_addr.cport)));
13469 		/*
13470 		 * Whoops, no SMART DATA available
13471 		 */
13472 		rval = -1;
13473 		goto fail;
13474 	} else {
13475 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
13476 		    sdinfo->satadrv_addr.cport)));
13477 		if (spx->txlt_buf_dma_handle != NULL) {
13478 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
13479 			    DDI_DMA_SYNC_FORKERNEL);
13480 			ASSERT(rval == DDI_SUCCESS);
13481 		}
13482 		bcopy(scmd->satacmd_bp->b_un.b_addr, (uint8_t *)selftest_log,
13483 		    sizeof (struct smart_selftest_log));
13484 		rval = 0;
13485 	}
13486 
13487 fail:
13488 	/* Free allocated resources */
13489 	sata_free_local_buffer(spx);
13490 	sata_pkt_free(spx);
13491 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
13492 
13493 	return (rval);
13494 }
13495 
13496 
13497 /*
13498  * Returns 0 for success, -1 otherwise
13499  *
13500  * SMART READ LOG data is returned in buffer pointed to by smart_log
13501  */
13502 static int
13503 sata_smart_read_log(
13504 	sata_hba_inst_t *sata_hba_inst,
13505 	sata_drive_info_t *sdinfo,
13506 	uint8_t *smart_log,		/* where the data should be returned */
13507 	uint8_t which_log,		/* which log should be returned */
13508 	uint8_t log_size)		/* # of 512 bytes in log */
13509 {
13510 	sata_pkt_t *spkt;
13511 	sata_cmd_t *scmd;
13512 	sata_pkt_txlate_t *spx;
13513 	int rval;
13514 
13515 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
13516 	spx->txlt_sata_hba_inst = sata_hba_inst;
13517 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
13518 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
13519 	if (spkt == NULL) {
13520 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
13521 		return (-1);
13522 	}
13523 	/* address is needed now */
13524 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13525 
13526 
13527 	/* Fill sata_pkt */
13528 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13529 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
13530 	/* Synchronous mode, no callback */
13531 	spkt->satapkt_comp = NULL;
13532 	/* Timeout 30s */
13533 	spkt->satapkt_time = sata_default_pkt_time;
13534 
13535 	scmd = &spkt->satapkt_cmd;
13536 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
13537 
13538 	/*
13539 	 * Allocate buffer for SMART READ LOG
13540 	 */
13541 	scmd->satacmd_bp = sata_alloc_local_buffer(spx, log_size * 512);
13542 	if (scmd->satacmd_bp == NULL) {
13543 		sata_pkt_free(spx);
13544 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
13545 		SATA_LOG_D((sata_hba_inst, CE_WARN,
13546 		    "sata_smart_read_log: " "cannot allocate buffer"));
13547 		return (-1);
13548 	}
13549 
13550 	/* Build SMART_READ_LOG cmd in the sata_pkt */
13551 	scmd->satacmd_addr_type = 0;		/* N/A */
13552 	scmd->satacmd_sec_count_lsb = log_size;	/* what the caller asked for */
13553 	scmd->satacmd_lba_low_lsb = which_log;	/* which log page */
13554 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
13555 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
13556 	scmd->satacmd_features_reg = SATA_SMART_READ_LOG;
13557 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
13558 	scmd->satacmd_cmd_reg = SATAC_SMART;
13559 
13560 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
13561 	    sdinfo->satadrv_addr.cport)));
13562 
13563 	/* Send pkt to SATA HBA driver */
13564 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
13565 	    SATA_TRAN_ACCEPTED ||
13566 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
13567 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
13568 		    sdinfo->satadrv_addr.cport)));
13569 
13570 		/*
13571 		 * Whoops, no SMART DATA available
13572 		 */
13573 		rval = -1;
13574 		goto fail;
13575 	} else {
13576 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
13577 		    sdinfo->satadrv_addr.cport)));
13578 
13579 		if (spx->txlt_buf_dma_handle != NULL) {
13580 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
13581 			    DDI_DMA_SYNC_FORKERNEL);
13582 			ASSERT(rval == DDI_SUCCESS);
13583 		}
13584 		bcopy(scmd->satacmd_bp->b_un.b_addr, smart_log, log_size * 512);
13585 		rval = 0;
13586 	}
13587 
13588 fail:
13589 	/* Free allocated resources */
13590 	sata_free_local_buffer(spx);
13591 	sata_pkt_free(spx);
13592 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
13593 
13594 	return (rval);
13595 }
13596 
13597 /*
13598  * Used by LOG SENSE page 0x10
13599  *
13600  * return 0 for success, -1 otherwise
13601  *
13602  */
13603 static int
13604 sata_read_log_ext_directory(
13605 	sata_hba_inst_t *sata_hba_inst,
13606 	sata_drive_info_t *sdinfo,
13607 	struct read_log_ext_directory *logdir)
13608 {
13609 	sata_pkt_txlate_t *spx;
13610 	sata_pkt_t *spkt;
13611 	sata_cmd_t *scmd;
13612 	int rval;
13613 
13614 #if ! defined(lint)
13615 	ASSERT(sizeof (struct read_log_ext_directory) == 512);
13616 #endif
13617 
13618 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
13619 	spx->txlt_sata_hba_inst = sata_hba_inst;
13620 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
13621 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
13622 	if (spkt == NULL) {
13623 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
13624 		return (-1);
13625 	}
13626 
13627 	/* Fill sata_pkt */
13628 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13629 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
13630 	/* Synchronous mode, no callback */
13631 	spkt->satapkt_comp = NULL;
13632 	/* Timeout 30s */
13633 	spkt->satapkt_time = sata_default_pkt_time;
13634 
13635 	scmd = &spkt->satapkt_cmd;
13636 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
13637 
13638 	/*
13639 	 * Allocate buffer for SMART READ LOG EXTENDED command
13640 	 */
13641 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
13642 	    sizeof (struct read_log_ext_directory));
13643 	if (scmd->satacmd_bp == NULL) {
13644 		sata_pkt_free(spx);
13645 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
13646 		SATA_LOG_D((sata_hba_inst, CE_WARN,
13647 		    "sata_read_log_ext_directory: "
13648 		    "cannot allocate buffer"));
13649 		return (-1);
13650 	}
13651 
13652 	/* Build READ LOG EXT w/ log directory cmd in the  sata_pkt */
13653 	scmd->satacmd_addr_type = ATA_ADDR_LBA48;
13654 	scmd->satacmd_sec_count_lsb = 1;	/* One sector of directory */
13655 	scmd->satacmd_sec_count_msb = 0;	/* One sector of directory */
13656 	scmd->satacmd_lba_low_lsb = READ_LOG_EXT_LOG_DIRECTORY;
13657 	scmd->satacmd_lba_low_msb = 0;
13658 	scmd->satacmd_lba_mid_lsb = 0;
13659 	scmd->satacmd_lba_mid_msb = 0;
13660 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
13661 	scmd->satacmd_cmd_reg = SATAC_READ_LOG_EXT;
13662 
13663 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
13664 	    sdinfo->satadrv_addr.cport)));
13665 
13666 	/* Send pkt to SATA HBA driver */
13667 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
13668 	    SATA_TRAN_ACCEPTED ||
13669 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
13670 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
13671 		    sdinfo->satadrv_addr.cport)));
13672 		/*
13673 		 * Whoops, no SMART selftest log info available
13674 		 */
13675 		rval = -1;
13676 		goto fail;
13677 	} else {
13678 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
13679 		    sdinfo->satadrv_addr.cport)));
13680 		if (spx->txlt_buf_dma_handle != NULL) {
13681 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
13682 			    DDI_DMA_SYNC_FORKERNEL);
13683 			ASSERT(rval == DDI_SUCCESS);
13684 		}
13685 		bcopy(scmd->satacmd_bp->b_un.b_addr, (uint8_t *)logdir,
13686 		    sizeof (struct read_log_ext_directory));
13687 		rval = 0;
13688 	}
13689 
13690 fail:
13691 	/* Free allocated resources */
13692 	sata_free_local_buffer(spx);
13693 	sata_pkt_free(spx);
13694 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
13695 
13696 	return (rval);
13697 }
13698 
13699 /*
13700  * Set up error retrieval sata command for NCQ command error data
13701  * recovery.
13702  *
13703  * Returns SATA_SUCCESS when data buffer is allocated and packet set-up,
13704  * returns SATA_FAILURE otherwise.
13705  */
13706 static int
13707 sata_ncq_err_ret_cmd_setup(sata_pkt_txlate_t *spx, sata_drive_info_t *sdinfo)
13708 {
13709 #ifndef __lock_lint
13710 	_NOTE(ARGUNUSED(sdinfo))
13711 #endif
13712 
13713 	sata_pkt_t *spkt = spx->txlt_sata_pkt;
13714 	sata_cmd_t *scmd;
13715 	struct buf *bp;
13716 
13717 	/* Operation modes are up to the caller */
13718 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
13719 
13720 	/* Synchronous mode, no callback - may be changed by the caller */
13721 	spkt->satapkt_comp = NULL;
13722 	spkt->satapkt_time = sata_default_pkt_time;
13723 
13724 	scmd = &spkt->satapkt_cmd;
13725 	bcopy(&sata_rle_cmd, scmd, sizeof (sata_cmd_t));
13726 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
13727 
13728 	/*
13729 	 * Allocate dma_able buffer error data.
13730 	 * Buffer allocation will take care of buffer alignment and other DMA
13731 	 * attributes.
13732 	 */
13733 	bp = sata_alloc_local_buffer(spx,
13734 	    sizeof (struct sata_ncq_error_recovery_page));
13735 	if (bp == NULL)
13736 		return (SATA_FAILURE);
13737 
13738 	bp_mapin(bp); /* make data buffer accessible */
13739 	scmd->satacmd_bp = bp;
13740 
13741 	/*
13742 	 * Set-up pointer to the buffer handle, so HBA can sync buffer
13743 	 * before accessing it. Handle is in usual place in translate struct.
13744 	 */
13745 	scmd->satacmd_err_ret_buf_handle = &spx->txlt_buf_dma_handle;
13746 
13747 	ASSERT(scmd->satacmd_num_dma_cookies != 0);
13748 	ASSERT(scmd->satacmd_dma_cookie_list != NULL);
13749 
13750 	return (SATA_SUCCESS);
13751 }
13752 
13753 /*
13754  * sata_xlate_errors() is used to translate (S)ATA error
13755  * information to SCSI information returned in the SCSI
13756  * packet.
13757  */
13758 static void
13759 sata_xlate_errors(sata_pkt_txlate_t *spx)
13760 {
13761 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
13762 	struct scsi_extended_sense *sense;
13763 
13764 	scsipkt->pkt_reason = CMD_INCOMPLETE;
13765 	*scsipkt->pkt_scbp = STATUS_CHECK;
13766 	sense = sata_arq_sense(spx);
13767 
13768 	switch (spx->txlt_sata_pkt->satapkt_reason) {
13769 	case SATA_PKT_PORT_ERROR:
13770 		/*
13771 		 * We have no device data. Assume no data transfered.
13772 		 */
13773 		sense->es_key = KEY_HARDWARE_ERROR;
13774 		break;
13775 
13776 	case SATA_PKT_DEV_ERROR:
13777 		if (spx->txlt_sata_pkt->satapkt_cmd.satacmd_status_reg &
13778 		    SATA_STATUS_ERR) {
13779 			/*
13780 			 * determine dev error reason from error
13781 			 * reg content
13782 			 */
13783 			sata_decode_device_error(spx, sense);
13784 			break;
13785 		}
13786 		/* No extended sense key - no info available */
13787 		break;
13788 
13789 	case SATA_PKT_TIMEOUT:
13790 		scsipkt->pkt_reason = CMD_TIMEOUT;
13791 		scsipkt->pkt_statistics |= STAT_TIMEOUT | STAT_DEV_RESET;
13792 		/* No extended sense key */
13793 		break;
13794 
13795 	case SATA_PKT_ABORTED:
13796 		scsipkt->pkt_reason = CMD_ABORTED;
13797 		scsipkt->pkt_statistics |= STAT_ABORTED;
13798 		/* No extended sense key */
13799 		break;
13800 
13801 	case SATA_PKT_RESET:
13802 		/*
13803 		 * pkt aborted either by an explicit reset request from
13804 		 * a host, or due to error recovery
13805 		 */
13806 		scsipkt->pkt_reason = CMD_RESET;
13807 		scsipkt->pkt_statistics |= STAT_DEV_RESET;
13808 		break;
13809 
13810 	default:
13811 		scsipkt->pkt_reason = CMD_TRAN_ERR;
13812 		break;
13813 	}
13814 }
13815 
13816 
13817 
13818 
13819 /*
13820  * Log sata message
13821  * dev pathname msg line preceeds the logged message.
13822  */
13823 
13824 static	void
13825 sata_log(sata_hba_inst_t *sata_hba_inst, uint_t level, char *fmt, ...)
13826 {
13827 	char pathname[128];
13828 	dev_info_t *dip;
13829 	va_list ap;
13830 
13831 	mutex_enter(&sata_log_mutex);
13832 
13833 	va_start(ap, fmt);
13834 	(void) vsprintf(sata_log_buf, fmt, ap);
13835 	va_end(ap);
13836 
13837 	if (sata_hba_inst != NULL) {
13838 		dip = SATA_DIP(sata_hba_inst);
13839 		(void) ddi_pathname(dip, pathname);
13840 	} else {
13841 		pathname[0] = 0;
13842 	}
13843 	if (level == CE_CONT) {
13844 		if (sata_debug_flags == 0)
13845 			cmn_err(level, "?%s:\n %s\n", pathname, sata_log_buf);
13846 		else
13847 			cmn_err(level, "%s:\n %s\n", pathname, sata_log_buf);
13848 	} else {
13849 		if (level != CE_NOTE) {
13850 			cmn_err(level, "%s:\n %s", pathname, sata_log_buf);
13851 		} else if (sata_msg) {
13852 			cmn_err(level, "%s:\n %s", pathname,
13853 			    sata_log_buf);
13854 		}
13855 	}
13856 
13857 	mutex_exit(&sata_log_mutex);
13858 }
13859 
13860 
13861 /* ******** Asynchronous HBA events handling & hotplugging support ******** */
13862 
13863 /*
13864  * Start or terminate the thread, depending on flag arg and current state
13865  */
13866 static void
13867 sata_event_thread_control(int startstop)
13868 {
13869 	static 	int sata_event_thread_terminating = 0;
13870 	static 	int sata_event_thread_starting = 0;
13871 	int i;
13872 
13873 	mutex_enter(&sata_event_mutex);
13874 
13875 	if (startstop == 0 && (sata_event_thread_starting == 1 ||
13876 	    sata_event_thread_terminating == 1)) {
13877 		mutex_exit(&sata_event_mutex);
13878 		return;
13879 	}
13880 	if (startstop == 1 && sata_event_thread_starting == 1) {
13881 		mutex_exit(&sata_event_mutex);
13882 		return;
13883 	}
13884 	if (startstop == 1 && sata_event_thread_terminating == 1) {
13885 		sata_event_thread_starting = 1;
13886 		/* wait til terminate operation completes */
13887 		i = SATA_EVNT_DAEMON_TERM_WAIT/SATA_EVNT_DAEMON_TERM_TIMEOUT;
13888 		while (sata_event_thread_terminating == 1) {
13889 			if (i-- <= 0) {
13890 				sata_event_thread_starting = 0;
13891 				mutex_exit(&sata_event_mutex);
13892 #ifdef SATA_DEBUG
13893 				cmn_err(CE_WARN, "sata_event_thread_control: "
13894 				    "timeout waiting for thread to terminate");
13895 #endif
13896 				return;
13897 			}
13898 			mutex_exit(&sata_event_mutex);
13899 			delay(drv_usectohz(SATA_EVNT_DAEMON_TERM_TIMEOUT));
13900 			mutex_enter(&sata_event_mutex);
13901 		}
13902 	}
13903 	if (startstop == 1) {
13904 		if (sata_event_thread == NULL) {
13905 			sata_event_thread = thread_create(NULL, 0,
13906 			    (void (*)())sata_event_daemon,
13907 			    &sata_hba_list, 0, &p0, TS_RUN, minclsyspri);
13908 		}
13909 		sata_event_thread_starting = 0;
13910 		mutex_exit(&sata_event_mutex);
13911 		return;
13912 	}
13913 
13914 	/*
13915 	 * If we got here, thread may need to be terminated
13916 	 */
13917 	if (sata_event_thread != NULL) {
13918 		int i;
13919 		/* Signal event thread to go away */
13920 		sata_event_thread_terminating = 1;
13921 		sata_event_thread_terminate = 1;
13922 		cv_signal(&sata_event_cv);
13923 		/*
13924 		 * Wait til daemon terminates.
13925 		 */
13926 		i = SATA_EVNT_DAEMON_TERM_WAIT/SATA_EVNT_DAEMON_TERM_TIMEOUT;
13927 		while (sata_event_thread_terminate == 1) {
13928 			mutex_exit(&sata_event_mutex);
13929 			if (i-- <= 0) {
13930 				/* Daemon did not go away !!! */
13931 #ifdef SATA_DEBUG
13932 				cmn_err(CE_WARN, "sata_event_thread_control: "
13933 				    "cannot terminate event daemon thread");
13934 #endif
13935 				mutex_enter(&sata_event_mutex);
13936 				break;
13937 			}
13938 			delay(drv_usectohz(SATA_EVNT_DAEMON_TERM_TIMEOUT));
13939 			mutex_enter(&sata_event_mutex);
13940 		}
13941 		sata_event_thread_terminating = 0;
13942 	}
13943 	ASSERT(sata_event_thread_terminating == 0);
13944 	ASSERT(sata_event_thread_starting == 0);
13945 	mutex_exit(&sata_event_mutex);
13946 }
13947 
13948 
13949 /*
13950  * SATA HBA event notification function.
13951  * Events reported by SATA HBA drivers per HBA instance relate to a change in
13952  * a port and/or device state or a controller itself.
13953  * Events for different addresses/addr types cannot be combined.
13954  * A warning message is generated for each event type.
13955  * Events are not processed by this function, so only the
13956  * event flag(s)is set for an affected entity and the event thread is
13957  * waken up. Event daemon thread processes all events.
13958  *
13959  * NOTE: Since more than one event may be reported at the same time, one
13960  * cannot determine a sequence of events when opposite event are reported, eg.
13961  * LINK_LOST and LINK_ESTABLISHED. Actual port status during event processing
13962  * is taking precedence over reported events, i.e. may cause ignoring some
13963  * events.
13964  */
13965 #define	SATA_EVENT_MAX_MSG_LENGTH	79
13966 
13967 void
13968 sata_hba_event_notify(dev_info_t *dip, sata_device_t *sata_device, int event)
13969 {
13970 	sata_hba_inst_t *sata_hba_inst = NULL;
13971 	sata_address_t *saddr;
13972 	sata_drive_info_t *sdinfo;
13973 	sata_port_stats_t *pstats;
13974 	sata_cport_info_t *cportinfo;
13975 	sata_pmport_info_t *pmportinfo;
13976 	int cport, pmport;
13977 	char buf1[SATA_EVENT_MAX_MSG_LENGTH + 1];
13978 	char buf2[SATA_EVENT_MAX_MSG_LENGTH + 1];
13979 	char *lcp;
13980 	static char *err_msg_evnt_1 =
13981 	    "sata_hba_event_notify: invalid port event 0x%x ";
13982 	static char *err_msg_evnt_2 =
13983 	    "sata_hba_event_notify: invalid device event 0x%x ";
13984 	int linkevent;
13985 
13986 	/*
13987 	 * There is a possibility that an event will be generated on HBA
13988 	 * that has not completed attachment or is detaching. We still want
13989 	 * to process events until HBA is detached.
13990 	 */
13991 	mutex_enter(&sata_mutex);
13992 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
13993 	    sata_hba_inst = sata_hba_inst->satahba_next) {
13994 		if (SATA_DIP(sata_hba_inst) == dip)
13995 			if (sata_hba_inst->satahba_attached == 1)
13996 				break;
13997 	}
13998 	mutex_exit(&sata_mutex);
13999 	if (sata_hba_inst == NULL)
14000 		/* HBA not attached */
14001 		return;
14002 
14003 	ASSERT(sata_device != NULL);
14004 
14005 	/*
14006 	 * Validate address before - do not proceed with invalid address.
14007 	 */
14008 	saddr = &sata_device->satadev_addr;
14009 	if (saddr->cport >= SATA_NUM_CPORTS(sata_hba_inst))
14010 		return;
14011 	if (saddr->qual == SATA_ADDR_PMPORT ||
14012 	    saddr->qual == SATA_ADDR_DPMPORT)
14013 		/* Port Multiplier not supported yet */
14014 		return;
14015 
14016 	cport = saddr->cport;
14017 	pmport = saddr->pmport;
14018 
14019 	buf1[0] = buf2[0] = '\0';
14020 
14021 	/*
14022 	 * If event relates to port or device, check port state.
14023 	 * Port has to be initialized, or we cannot accept an event.
14024 	 */
14025 	if ((saddr->qual & (SATA_ADDR_CPORT | SATA_ADDR_PMPORT |
14026 	    SATA_ADDR_DCPORT | SATA_ADDR_DPMPORT)) != 0) {
14027 		if ((saddr->qual & (SATA_ADDR_CPORT | SATA_ADDR_DCPORT)) != 0) {
14028 			mutex_enter(&sata_hba_inst->satahba_mutex);
14029 			cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
14030 			mutex_exit(&sata_hba_inst->satahba_mutex);
14031 			if (cportinfo == NULL || cportinfo->cport_state == 0)
14032 				return;
14033 		} else {
14034 			mutex_enter(&sata_hba_inst->satahba_mutex);
14035 			pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
14036 			    cport, pmport);
14037 			mutex_exit(&sata_hba_inst->satahba_mutex);
14038 			if (pmportinfo == NULL || pmportinfo->pmport_state == 0)
14039 				return;
14040 		}
14041 	}
14042 
14043 	/*
14044 	 * Events refer to devices, ports and controllers - each has
14045 	 * unique address. Events for different addresses cannot be combined.
14046 	 */
14047 	if (saddr->qual & (SATA_ADDR_CPORT | SATA_ADDR_PMPORT)) {
14048 
14049 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
14050 
14051 		/* qualify this event(s) */
14052 		if ((event & SATA_EVNT_PORT_EVENTS) == 0) {
14053 			/* Invalid event for the device port */
14054 			(void) sprintf(buf2, err_msg_evnt_1,
14055 			    event & SATA_EVNT_PORT_EVENTS);
14056 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
14057 			goto event_info;
14058 		}
14059 		if (saddr->qual == SATA_ADDR_CPORT) {
14060 			/* Controller's device port event */
14061 
14062 			(SATA_CPORT_INFO(sata_hba_inst, cport))->
14063 			    cport_event_flags |=
14064 			    event & SATA_EVNT_PORT_EVENTS;
14065 			pstats =
14066 			    &(SATA_CPORT_INFO(sata_hba_inst, cport))->
14067 			    cport_stats;
14068 		} else {
14069 			/* Port multiplier's device port event */
14070 			(SATA_PMPORT_INFO(sata_hba_inst, cport, pmport))->
14071 			    pmport_event_flags |=
14072 			    event & SATA_EVNT_PORT_EVENTS;
14073 			pstats =
14074 			    &(SATA_PMPORT_INFO(sata_hba_inst, cport, pmport))->
14075 			    pmport_stats;
14076 		}
14077 
14078 		/*
14079 		 * Add to statistics and log the message. We have to do it
14080 		 * here rather than in the event daemon, because there may be
14081 		 * multiple events occuring before they are processed.
14082 		 */
14083 		linkevent = event &
14084 		    (SATA_EVNT_LINK_LOST | SATA_EVNT_LINK_ESTABLISHED);
14085 		if (linkevent) {
14086 			if (linkevent == (SATA_EVNT_LINK_LOST |
14087 			    SATA_EVNT_LINK_ESTABLISHED)) {
14088 				/* This is likely event combination */
14089 				(void) strlcat(buf1, "link lost/established, ",
14090 				    SATA_EVENT_MAX_MSG_LENGTH);
14091 
14092 				if (pstats->link_lost < 0xffffffffffffffffULL)
14093 					pstats->link_lost++;
14094 				if (pstats->link_established <
14095 				    0xffffffffffffffffULL)
14096 					pstats->link_established++;
14097 				linkevent = 0;
14098 			} else if (linkevent & SATA_EVNT_LINK_LOST) {
14099 				(void) strlcat(buf1, "link lost, ",
14100 				    SATA_EVENT_MAX_MSG_LENGTH);
14101 
14102 				if (pstats->link_lost < 0xffffffffffffffffULL)
14103 					pstats->link_lost++;
14104 			} else {
14105 				(void) strlcat(buf1, "link established, ",
14106 				    SATA_EVENT_MAX_MSG_LENGTH);
14107 				if (pstats->link_established <
14108 				    0xffffffffffffffffULL)
14109 					pstats->link_established++;
14110 			}
14111 		}
14112 		if (event & SATA_EVNT_DEVICE_ATTACHED) {
14113 			(void) strlcat(buf1, "device attached, ",
14114 			    SATA_EVENT_MAX_MSG_LENGTH);
14115 			if (pstats->device_attached < 0xffffffffffffffffULL)
14116 				pstats->device_attached++;
14117 		}
14118 		if (event & SATA_EVNT_DEVICE_DETACHED) {
14119 			(void) strlcat(buf1, "device detached, ",
14120 			    SATA_EVENT_MAX_MSG_LENGTH);
14121 			if (pstats->device_detached < 0xffffffffffffffffULL)
14122 				pstats->device_detached++;
14123 		}
14124 		if (event & SATA_EVNT_PWR_LEVEL_CHANGED) {
14125 			SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
14126 			    "port %d power level changed", cport);
14127 			if (pstats->port_pwr_changed < 0xffffffffffffffffULL)
14128 				pstats->port_pwr_changed++;
14129 		}
14130 
14131 		if ((event & ~SATA_EVNT_PORT_EVENTS) != 0) {
14132 			/* There should be no other events for this address */
14133 			(void) sprintf(buf2, err_msg_evnt_1,
14134 			    event & ~SATA_EVNT_PORT_EVENTS);
14135 		}
14136 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
14137 
14138 	} else if (saddr->qual & (SATA_ADDR_DCPORT | SATA_ADDR_DPMPORT)) {
14139 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
14140 
14141 		/* qualify this event */
14142 		if ((event & SATA_EVNT_DEVICE_RESET) == 0) {
14143 			/* Invalid event for a device */
14144 			(void) sprintf(buf2, err_msg_evnt_2,
14145 			    event & SATA_EVNT_DEVICE_RESET);
14146 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
14147 			goto event_info;
14148 		}
14149 		/* drive event */
14150 		sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
14151 		if (sdinfo != NULL) {
14152 			if (event & SATA_EVNT_DEVICE_RESET) {
14153 				(void) strlcat(buf1, "device reset, ",
14154 				    SATA_EVENT_MAX_MSG_LENGTH);
14155 				if (sdinfo->satadrv_stats.drive_reset <
14156 				    0xffffffffffffffffULL)
14157 					sdinfo->satadrv_stats.drive_reset++;
14158 				sdinfo->satadrv_event_flags |=
14159 				    SATA_EVNT_DEVICE_RESET;
14160 			}
14161 		}
14162 		if ((event & ~SATA_EVNT_DEVICE_RESET) != 0) {
14163 			/* Invalid event for a device */
14164 			(void) sprintf(buf2, err_msg_evnt_2,
14165 			    event & ~SATA_EVNT_DRIVE_EVENTS);
14166 		}
14167 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
14168 	} else {
14169 		if (saddr->qual != SATA_ADDR_NULL) {
14170 			/* Wrong address qualifier */
14171 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14172 			    "sata_hba_event_notify: invalid address 0x%x",
14173 			    *(uint32_t *)saddr));
14174 			return;
14175 		}
14176 		if ((event & SATA_EVNT_CONTROLLER_EVENTS) == 0 ||
14177 		    (event & ~SATA_EVNT_CONTROLLER_EVENTS) != 0) {
14178 			/* Invalid event for the controller */
14179 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14180 			    "sata_hba_event_notify: invalid event 0x%x for "
14181 			    "controller",
14182 			    event & SATA_EVNT_CONTROLLER_EVENTS));
14183 			return;
14184 		}
14185 		buf1[0] = '\0';
14186 		/* This may be a frequent and not interesting event */
14187 		SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
14188 		    "controller power level changed\n", NULL);
14189 
14190 		mutex_enter(&sata_hba_inst->satahba_mutex);
14191 		if (sata_hba_inst->satahba_stats.ctrl_pwr_change <
14192 		    0xffffffffffffffffULL)
14193 			sata_hba_inst->satahba_stats.ctrl_pwr_change++;
14194 
14195 		sata_hba_inst->satahba_event_flags |=
14196 		    SATA_EVNT_PWR_LEVEL_CHANGED;
14197 		mutex_exit(&sata_hba_inst->satahba_mutex);
14198 	}
14199 	/*
14200 	 * If we got here, there is something to do with this HBA
14201 	 * instance.
14202 	 */
14203 	mutex_enter(&sata_hba_inst->satahba_mutex);
14204 	sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
14205 	mutex_exit(&sata_hba_inst->satahba_mutex);
14206 	mutex_enter(&sata_mutex);
14207 	sata_event_pending |= SATA_EVNT_MAIN;	/* global event indicator */
14208 	mutex_exit(&sata_mutex);
14209 
14210 	/* Tickle event thread */
14211 	mutex_enter(&sata_event_mutex);
14212 	if (sata_event_thread_active == 0)
14213 		cv_signal(&sata_event_cv);
14214 	mutex_exit(&sata_event_mutex);
14215 
14216 event_info:
14217 	if (buf1[0] != '\0') {
14218 		lcp = strrchr(buf1, ',');
14219 		if (lcp != NULL)
14220 			*lcp = '\0';
14221 	}
14222 	if (saddr->qual == SATA_ADDR_CPORT ||
14223 	    saddr->qual == SATA_ADDR_DCPORT) {
14224 		if (buf1[0] != '\0') {
14225 			sata_log(sata_hba_inst, CE_NOTE, "port %d: %s\n",
14226 			    cport, buf1);
14227 		}
14228 		if (buf2[0] != '\0') {
14229 			sata_log(sata_hba_inst, CE_NOTE, "port %d: %s\n",
14230 			    cport, buf2);
14231 		}
14232 	} else if (saddr->qual == SATA_ADDR_PMPORT ||
14233 	    saddr->qual == SATA_ADDR_DPMPORT) {
14234 		if (buf1[0] != '\0') {
14235 			sata_log(sata_hba_inst, CE_NOTE,
14236 			    "port %d pmport %d: %s\n", cport, pmport, buf1);
14237 		}
14238 		if (buf2[0] != '\0') {
14239 			sata_log(sata_hba_inst, CE_NOTE,
14240 			    "port %d pmport %d: %s\n", cport, pmport, buf2);
14241 		}
14242 	}
14243 }
14244 
14245 
14246 /*
14247  * Event processing thread.
14248  * Arg is a pointer to the sata_hba_list pointer.
14249  * It is not really needed, because sata_hba_list is global and static
14250  */
14251 static void
14252 sata_event_daemon(void *arg)
14253 {
14254 #ifndef __lock_lint
14255 	_NOTE(ARGUNUSED(arg))
14256 #endif
14257 	sata_hba_inst_t *sata_hba_inst;
14258 	clock_t lbolt;
14259 
14260 	SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
14261 	    "SATA event daemon started\n", NULL);
14262 loop:
14263 	/*
14264 	 * Process events here. Walk through all registered HBAs
14265 	 */
14266 	mutex_enter(&sata_mutex);
14267 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
14268 	    sata_hba_inst = sata_hba_inst->satahba_next) {
14269 		ASSERT(sata_hba_inst != NULL);
14270 		mutex_enter(&sata_hba_inst->satahba_mutex);
14271 		if (sata_hba_inst->satahba_attached == 0 ||
14272 		    (sata_hba_inst->satahba_event_flags &
14273 		    SATA_EVNT_SKIP) != 0) {
14274 			mutex_exit(&sata_hba_inst->satahba_mutex);
14275 			continue;
14276 		}
14277 		if (sata_hba_inst->satahba_event_flags & SATA_EVNT_MAIN) {
14278 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_SKIP;
14279 			mutex_exit(&sata_hba_inst->satahba_mutex);
14280 			mutex_exit(&sata_mutex);
14281 			/* Got the controller with pending event */
14282 			sata_process_controller_events(sata_hba_inst);
14283 			/*
14284 			 * Since global mutex was released, there is a
14285 			 * possibility that HBA list has changed, so start
14286 			 * over from the top. Just processed controller
14287 			 * will be passed-over because of the SKIP flag.
14288 			 */
14289 			goto loop;
14290 		}
14291 		mutex_exit(&sata_hba_inst->satahba_mutex);
14292 	}
14293 	/* Clear SKIP flag in all controllers */
14294 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
14295 	    sata_hba_inst = sata_hba_inst->satahba_next) {
14296 		mutex_enter(&sata_hba_inst->satahba_mutex);
14297 		sata_hba_inst->satahba_event_flags &= ~SATA_EVNT_SKIP;
14298 		mutex_exit(&sata_hba_inst->satahba_mutex);
14299 	}
14300 	mutex_exit(&sata_mutex);
14301 
14302 	SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
14303 	    "SATA EVENT DAEMON suspending itself", NULL);
14304 
14305 #ifdef SATA_DEBUG
14306 	if ((sata_func_enable & SATA_ENABLE_PROCESS_EVENTS) == 0) {
14307 		sata_log(sata_hba_inst, CE_WARN,
14308 		    "SATA EVENTS PROCESSING DISABLED\n");
14309 		thread_exit(); /* Daemon will not run again */
14310 	}
14311 #endif
14312 	mutex_enter(&sata_event_mutex);
14313 	sata_event_thread_active = 0;
14314 	mutex_exit(&sata_event_mutex);
14315 	/*
14316 	 * Go to sleep/suspend itself and wake up either because new event or
14317 	 * wait timeout. Exit if there is a termination request (driver
14318 	 * unload).
14319 	 */
14320 	do {
14321 		lbolt = ddi_get_lbolt();
14322 		lbolt += drv_usectohz(SATA_EVNT_DAEMON_SLEEP_TIME);
14323 		mutex_enter(&sata_event_mutex);
14324 		(void) cv_timedwait(&sata_event_cv, &sata_event_mutex, lbolt);
14325 
14326 		if (sata_event_thread_active != 0) {
14327 			mutex_exit(&sata_event_mutex);
14328 			continue;
14329 		}
14330 
14331 		/* Check if it is time to go away */
14332 		if (sata_event_thread_terminate == 1) {
14333 			/*
14334 			 * It is up to the thread setting above flag to make
14335 			 * sure that this thread is not killed prematurely.
14336 			 */
14337 			sata_event_thread_terminate = 0;
14338 			sata_event_thread = NULL;
14339 			mutex_exit(&sata_event_mutex);
14340 			SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
14341 			    "SATA_EVENT_DAEMON_TERMINATING", NULL);
14342 			thread_exit();  { _NOTE(NOT_REACHED) }
14343 		}
14344 		mutex_exit(&sata_event_mutex);
14345 	} while (!(sata_event_pending & SATA_EVNT_MAIN));
14346 
14347 	mutex_enter(&sata_event_mutex);
14348 	sata_event_thread_active = 1;
14349 	mutex_exit(&sata_event_mutex);
14350 
14351 	mutex_enter(&sata_mutex);
14352 	sata_event_pending &= ~SATA_EVNT_MAIN;
14353 	mutex_exit(&sata_mutex);
14354 
14355 	SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
14356 	    "SATA EVENT DAEMON READY TO PROCESS EVENT", NULL);
14357 
14358 	goto loop;
14359 }
14360 
14361 /*
14362  * Specific HBA instance event processing.
14363  *
14364  * NOTE: At the moment, device event processing is limited to hard disks
14365  * only.
14366  * cports only are supported - no pmports.
14367  */
14368 static void
14369 sata_process_controller_events(sata_hba_inst_t *sata_hba_inst)
14370 {
14371 	int ncport;
14372 	uint32_t event_flags;
14373 	sata_address_t *saddr;
14374 	sata_cport_info_t *cportinfo;
14375 
14376 	SATADBG1(SATA_DBG_EVENTS_CNTRL, sata_hba_inst,
14377 	    "Processing controller %d event(s)",
14378 	    ddi_get_instance(SATA_DIP(sata_hba_inst)));
14379 
14380 	mutex_enter(&sata_hba_inst->satahba_mutex);
14381 	sata_hba_inst->satahba_event_flags &= ~SATA_EVNT_MAIN;
14382 	event_flags = sata_hba_inst->satahba_event_flags;
14383 	mutex_exit(&sata_hba_inst->satahba_mutex);
14384 	/*
14385 	 * Process controller power change first
14386 	 * HERE
14387 	 */
14388 	if (event_flags & SATA_EVNT_PWR_LEVEL_CHANGED)
14389 		sata_process_cntrl_pwr_level_change(sata_hba_inst);
14390 
14391 	/*
14392 	 * Search through ports/devices to identify affected port/device.
14393 	 * We may have to process events for more than one port/device.
14394 	 */
14395 	for (ncport = 0; ncport < SATA_NUM_CPORTS(sata_hba_inst); ncport++) {
14396 		/*
14397 		 * Not all ports may be processed in attach by the time we
14398 		 * get an event. Check if port info is initialized.
14399 		 */
14400 		mutex_enter(&sata_hba_inst->satahba_mutex);
14401 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, ncport);
14402 		mutex_exit(&sata_hba_inst->satahba_mutex);
14403 		if (cportinfo == NULL || cportinfo->cport_state == NULL)
14404 			continue;
14405 
14406 		/* We have initialized controller port info */
14407 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
14408 		event_flags = (SATA_CPORT_INFO(sata_hba_inst, ncport))->
14409 		    cport_event_flags;
14410 		/* Check if port was locked by IOCTL processing */
14411 		if (event_flags & SATA_APCTL_LOCK_PORT_BUSY) {
14412 			/*
14413 			 * We ignore port events because port is busy
14414 			 * with AP control processing. Set again
14415 			 * controller and main event flag, so that
14416 			 * events may be processed by the next daemon
14417 			 * run.
14418 			 */
14419 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
14420 			mutex_enter(&sata_hba_inst->satahba_mutex);
14421 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
14422 			mutex_exit(&sata_hba_inst->satahba_mutex);
14423 			mutex_enter(&sata_mutex);
14424 			sata_event_pending |= SATA_EVNT_MAIN;
14425 			mutex_exit(&sata_mutex);
14426 			SATADBG1(SATA_DBG_EVENTS_PROCPST, sata_hba_inst,
14427 			    "Event processing postponed until "
14428 			    "AP control processing completes",
14429 			    NULL);
14430 			/* Check other ports */
14431 			continue;
14432 		} else {
14433 			/*
14434 			 * Set BSY flag so that AP control would not
14435 			 * interfere with events processing for
14436 			 * this port.
14437 			 */
14438 			(SATA_CPORT_INFO(sata_hba_inst, ncport))->
14439 			    cport_event_flags |= SATA_EVNT_LOCK_PORT_BUSY;
14440 		}
14441 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
14442 
14443 		saddr = &(SATA_CPORT_INFO(sata_hba_inst, ncport))->cport_addr;
14444 
14445 		if ((event_flags &
14446 		    (SATA_EVNT_PORT_EVENTS | SATA_EVNT_DRIVE_EVENTS)) != 0) {
14447 			/*
14448 			 * Got port event.
14449 			 * We need some hierarchy of event processing as they
14450 			 * are affecting each other:
14451 			 * 1. port failed
14452 			 * 2. device detached/attached
14453 			 * 3. link events - link events may trigger device
14454 			 *    detached or device attached events in some
14455 			 *    circumstances.
14456 			 * 4. port power level changed
14457 			 */
14458 			if (event_flags & SATA_EVNT_PORT_FAILED) {
14459 				sata_process_port_failed_event(sata_hba_inst,
14460 				    saddr);
14461 			}
14462 			if (event_flags & SATA_EVNT_DEVICE_DETACHED) {
14463 				sata_process_device_detached(sata_hba_inst,
14464 				    saddr);
14465 			}
14466 			if (event_flags & SATA_EVNT_DEVICE_ATTACHED) {
14467 				sata_process_device_attached(sata_hba_inst,
14468 				    saddr);
14469 			}
14470 			if (event_flags &
14471 			    (SATA_EVNT_LINK_ESTABLISHED |
14472 			    SATA_EVNT_LINK_LOST)) {
14473 				sata_process_port_link_events(sata_hba_inst,
14474 				    saddr);
14475 			}
14476 			if (event_flags & SATA_EVNT_PWR_LEVEL_CHANGED) {
14477 				sata_process_port_pwr_change(sata_hba_inst,
14478 				    saddr);
14479 			}
14480 			if (event_flags & SATA_EVNT_TARGET_NODE_CLEANUP) {
14481 				sata_process_target_node_cleanup(
14482 				    sata_hba_inst, saddr);
14483 			}
14484 			if (event_flags & SATA_EVNT_AUTOONLINE_DEVICE) {
14485 				sata_process_device_autoonline(
14486 				    sata_hba_inst, saddr);
14487 			}
14488 		}
14489 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
14490 		if ((SATA_CPORT_DEV_TYPE(sata_hba_inst, ncport) !=
14491 		    SATA_DTYPE_NONE) &&
14492 		    (SATA_CPORT_DRV_INFO(sata_hba_inst, ncport) != NULL)) {
14493 			if (SATA_CPORT_DRV_INFO(sata_hba_inst, ncport)->
14494 			    satadrv_event_flags &
14495 			    (SATA_EVNT_DEVICE_RESET |
14496 			    SATA_EVNT_INPROC_DEVICE_RESET)) {
14497 				/* Have device event */
14498 				sata_process_device_reset(sata_hba_inst,
14499 				    saddr);
14500 			}
14501 		}
14502 		/* Release PORT_BUSY flag */
14503 		(SATA_CPORT_INFO(sata_hba_inst, ncport))->
14504 		    cport_event_flags &= ~SATA_EVNT_LOCK_PORT_BUSY;
14505 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
14506 
14507 	} /* End of loop through the controller SATA ports */
14508 }
14509 
14510 /*
14511  * Process HBA power level change reported by HBA driver.
14512  * Not implemented at this time - event is ignored.
14513  */
14514 static void
14515 sata_process_cntrl_pwr_level_change(sata_hba_inst_t *sata_hba_inst)
14516 {
14517 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
14518 	    "Processing controller power level change", NULL);
14519 
14520 	/* Ignoring it for now */
14521 	mutex_enter(&sata_hba_inst->satahba_mutex);
14522 	sata_hba_inst->satahba_event_flags &= ~SATA_EVNT_PWR_LEVEL_CHANGED;
14523 	mutex_exit(&sata_hba_inst->satahba_mutex);
14524 }
14525 
14526 /*
14527  * Process port power level change reported by HBA driver.
14528  * Not implemented at this time - event is ignored.
14529  */
14530 static void
14531 sata_process_port_pwr_change(sata_hba_inst_t *sata_hba_inst,
14532     sata_address_t *saddr)
14533 {
14534 	sata_cport_info_t *cportinfo;
14535 
14536 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
14537 	    "Processing port power level change", NULL);
14538 
14539 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
14540 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
14541 	/* Reset event flag */
14542 	cportinfo->cport_event_flags &= ~SATA_EVNT_PWR_LEVEL_CHANGED;
14543 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
14544 }
14545 
14546 /*
14547  * Process port failure reported by HBA driver.
14548  * cports support only - no pmports.
14549  */
14550 static void
14551 sata_process_port_failed_event(sata_hba_inst_t *sata_hba_inst,
14552     sata_address_t *saddr)
14553 {
14554 	sata_cport_info_t *cportinfo;
14555 
14556 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
14557 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
14558 	/* Reset event flag first */
14559 	cportinfo->cport_event_flags &= ~SATA_EVNT_PORT_FAILED;
14560 	/* If the port is in SHUTDOWN or FAILED state, ignore this event. */
14561 	if ((cportinfo->cport_state &
14562 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) == 0) {
14563 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
14564 		    cport_mutex);
14565 		return;
14566 	}
14567 	/* Fail the port */
14568 	cportinfo->cport_state = SATA_PSTATE_FAILED;
14569 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
14570 	sata_log(sata_hba_inst, CE_WARN, "SATA port %d failed", saddr->cport);
14571 }
14572 
14573 /*
14574  * Device Reset Event processing.
14575  * The seqeunce is managed by 3 stage flags:
14576  * - reset event reported,
14577  * - reset event being processed,
14578  * - request to clear device reset state.
14579  *
14580  * NOTE: This function has to be entered with cport mutex held. It exits with
14581  * mutex held as well, but can release mutex during the processing.
14582  */
14583 static void
14584 sata_process_device_reset(sata_hba_inst_t *sata_hba_inst,
14585     sata_address_t *saddr)
14586 {
14587 	sata_drive_info_t old_sdinfo; /* local copy of the drive info */
14588 	sata_drive_info_t *sdinfo;
14589 	sata_cport_info_t *cportinfo;
14590 	sata_device_t sata_device;
14591 	int rval_probe, rval_set;
14592 
14593 	/* We only care about host sata cport for now */
14594 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
14595 	sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst, saddr->cport);
14596 	/*
14597 	 * If the port is in SHUTDOWN or FAILED state, or device is in FAILED
14598 	 * state, ignore reset event.
14599 	 */
14600 	if (((cportinfo->cport_state &
14601 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) ||
14602 	    (sdinfo->satadrv_state & SATA_DSTATE_FAILED) != 0) {
14603 		sdinfo->satadrv_event_flags &=
14604 		    ~(SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET);
14605 		return;
14606 	}
14607 
14608 	if ((SATA_CPORT_DEV_TYPE(sata_hba_inst, saddr->cport) &
14609 	    SATA_VALID_DEV_TYPE) == 0) {
14610 		/*
14611 		 * This should not happen - coding error.
14612 		 * But we can recover, so do not panic, just clean up
14613 		 * and if in debug mode, log the message.
14614 		 */
14615 #ifdef SATA_DEBUG
14616 		sata_log(sata_hba_inst, CE_WARN,
14617 		    "sata_process_device_reset: "
14618 		    "Invalid device type with sdinfo!", NULL);
14619 #endif
14620 		sdinfo->satadrv_event_flags = 0;
14621 		return;
14622 	}
14623 
14624 #ifdef SATA_DEBUG
14625 	if ((sdinfo->satadrv_event_flags &
14626 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) == 0) {
14627 		/* Nothing to do */
14628 		/* Something is weird - why we are processing dev reset? */
14629 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
14630 		    "No device reset event!!!!", NULL);
14631 
14632 		return;
14633 	}
14634 	if ((sdinfo->satadrv_event_flags &
14635 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) ==
14636 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) {
14637 		/* Something is weird - new device reset event */
14638 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
14639 		    "Overlapping device reset events!", NULL);
14640 	}
14641 #endif
14642 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
14643 	    "Processing port %d device reset", saddr->cport);
14644 
14645 	/* Clear event flag */
14646 	sdinfo->satadrv_event_flags &= ~SATA_EVNT_DEVICE_RESET;
14647 
14648 	/* It seems that we always need to check the port state first */
14649 	sata_device.satadev_rev = SATA_DEVICE_REV;
14650 	sata_device.satadev_addr = *saddr;
14651 	/*
14652 	 * We have to exit mutex, because the HBA probe port function may
14653 	 * block on its own mutex.
14654 	 */
14655 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
14656 	rval_probe = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
14657 	    (SATA_DIP(sata_hba_inst), &sata_device);
14658 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
14659 	sata_update_port_info(sata_hba_inst, &sata_device);
14660 	if (rval_probe != SATA_SUCCESS) {
14661 		/* Something went wrong? Fail the port */
14662 		cportinfo->cport_state = SATA_PSTATE_FAILED;
14663 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst, saddr->cport);
14664 		if (sdinfo != NULL)
14665 			sdinfo->satadrv_event_flags = 0;
14666 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
14667 		    cport_mutex);
14668 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14669 		    "SATA port %d probing failed",
14670 		    saddr->cport));
14671 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14672 		    saddr->cport)->cport_mutex);
14673 		return;
14674 	}
14675 	if ((sata_device.satadev_scr.sstatus  &
14676 	    SATA_PORT_DEVLINK_UP_MASK) !=
14677 	    SATA_PORT_DEVLINK_UP ||
14678 	    sata_device.satadev_type == SATA_DTYPE_NONE) {
14679 		/*
14680 		 * No device to process, anymore. Some other event processing
14681 		 * would or have already performed port info cleanup.
14682 		 * To be safe (HBA may need it), request clearing device
14683 		 * reset condition.
14684 		 */
14685 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst, saddr->cport);
14686 		if (sdinfo != NULL) {
14687 			sdinfo->satadrv_event_flags &=
14688 			    ~SATA_EVNT_INPROC_DEVICE_RESET;
14689 			sdinfo->satadrv_event_flags |=
14690 			    SATA_EVNT_CLEAR_DEVICE_RESET;
14691 		}
14692 		return;
14693 	}
14694 
14695 	sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst, saddr->cport);
14696 	if (sdinfo == NULL) {
14697 		return;
14698 	}
14699 	if ((sdinfo->satadrv_event_flags &
14700 	    SATA_EVNT_INPROC_DEVICE_RESET) == 0) {
14701 		/*
14702 		 * Start tracking time for device feature restoration and
14703 		 * identification. Save current time (lbolt value).
14704 		 */
14705 		sdinfo->satadrv_reset_time = ddi_get_lbolt();
14706 	}
14707 	/* Mark device reset processing as active */
14708 	sdinfo->satadrv_event_flags |= SATA_EVNT_INPROC_DEVICE_RESET;
14709 
14710 	old_sdinfo = *sdinfo;	/* local copy of the drive info */
14711 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
14712 
14713 	rval_set = sata_set_drive_features(sata_hba_inst, &old_sdinfo, 1);
14714 
14715 	if (rval_set  != SATA_SUCCESS) {
14716 		/*
14717 		 * Restoring drive setting failed.
14718 		 * Probe the port first, to check if the port state has changed
14719 		 */
14720 		sata_device.satadev_rev = SATA_DEVICE_REV;
14721 		sata_device.satadev_addr = *saddr;
14722 		sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
14723 		/* probe port */
14724 		rval_probe = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
14725 		    (SATA_DIP(sata_hba_inst), &sata_device);
14726 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
14727 		    cport_mutex);
14728 		if (rval_probe == SATA_SUCCESS &&
14729 		    (sata_device.satadev_state &
14730 		    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) == 0 &&
14731 		    (sata_device.satadev_scr.sstatus  &
14732 		    SATA_PORT_DEVLINK_UP_MASK) == SATA_PORT_DEVLINK_UP &&
14733 		    sata_device.satadev_type != SATA_DTYPE_NONE) {
14734 			/*
14735 			 * We may retry this a bit later - in-process reset
14736 			 * condition should be already set.
14737 			 * Track retry time for device identification.
14738 			 */
14739 			if ((cportinfo->cport_dev_type &
14740 			    SATA_VALID_DEV_TYPE) != 0 &&
14741 			    SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL &&
14742 			    sdinfo->satadrv_reset_time != 0) {
14743 				clock_t cur_time = ddi_get_lbolt();
14744 				/*
14745 				 * If the retry time limit was not
14746 				 * exceeded, retry.
14747 				 */
14748 				if ((cur_time - sdinfo->satadrv_reset_time) <
14749 				    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
14750 					mutex_enter(
14751 					    &sata_hba_inst->satahba_mutex);
14752 					sata_hba_inst->satahba_event_flags |=
14753 					    SATA_EVNT_MAIN;
14754 					mutex_exit(
14755 					    &sata_hba_inst->satahba_mutex);
14756 					mutex_enter(&sata_mutex);
14757 					sata_event_pending |= SATA_EVNT_MAIN;
14758 					mutex_exit(&sata_mutex);
14759 					return;
14760 				}
14761 				if (rval_set == SATA_RETRY) {
14762 					/*
14763 					 * Setting drive features failed, but
14764 					 * the drive is still accessible,
14765 					 * so emit a warning message before
14766 					 * return.
14767 					 */
14768 					mutex_exit(&SATA_CPORT_INFO(
14769 					    sata_hba_inst,
14770 					    saddr->cport)->cport_mutex);
14771 					goto done;
14772 				}
14773 			}
14774 			/* Fail the drive */
14775 			sdinfo->satadrv_state = SATA_DSTATE_FAILED;
14776 
14777 			sata_log(sata_hba_inst, CE_WARN,
14778 			    "SATA device at port %d - device failed",
14779 			    saddr->cport);
14780 		}
14781 		/*
14782 		 * No point of retrying - device failed or some other event
14783 		 * processing or already did or will do port info cleanup.
14784 		 * To be safe (HBA may need it),
14785 		 * request clearing device reset condition.
14786 		 */
14787 		sdinfo->satadrv_event_flags |= SATA_EVNT_CLEAR_DEVICE_RESET;
14788 		sdinfo->satadrv_event_flags &= ~SATA_EVNT_INPROC_DEVICE_RESET;
14789 		sdinfo->satadrv_reset_time = 0;
14790 		return;
14791 	}
14792 done:
14793 	/*
14794 	 * If setting of drive features failed, but the drive is still
14795 	 * accessible, emit a warning message.
14796 	 */
14797 	if (rval_set == SATA_RETRY) {
14798 		sata_log(sata_hba_inst, CE_WARN,
14799 		    "SATA device at port %d - desired setting could not be "
14800 		    "restored after reset. Device may not operate as expected.",
14801 		    saddr->cport);
14802 	}
14803 	/*
14804 	 * Raise the flag indicating that the next sata command could
14805 	 * be sent with SATA_CLEAR_DEV_RESET_STATE flag, if no new device
14806 	 * reset is reported.
14807 	 */
14808 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
14809 	if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
14810 		sdinfo->satadrv_reset_time = 0;
14811 		if ((cportinfo->cport_dev_type & SATA_VALID_DEV_TYPE) != 0) {
14812 			sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
14813 			sdinfo->satadrv_event_flags &=
14814 			    ~SATA_EVNT_INPROC_DEVICE_RESET;
14815 			sdinfo->satadrv_event_flags |=
14816 			    SATA_EVNT_CLEAR_DEVICE_RESET;
14817 		}
14818 	}
14819 }
14820 
14821 
14822 /*
14823  * Port Link Events processing.
14824  * Every link established event may involve device reset (due to
14825  * COMRESET signal, equivalent of the hard reset) so arbitrarily
14826  * set device reset event for an attached device (if any).
14827  * If the port is in SHUTDOWN or FAILED state, ignore link events.
14828  *
14829  * The link established event processing varies, depending on the state
14830  * of the target node, HBA hotplugging capabilities, state of the port.
14831  * If the link is not active, the link established event is ignored.
14832  * If HBA cannot detect device attachment and there is no target node,
14833  * the link established event triggers device attach event processing.
14834  * Else, link established event triggers device reset event processing.
14835  *
14836  * The link lost event processing varies, depending on a HBA hotplugging
14837  * capability and the state of the port (link active or not active).
14838  * If the link is active, the lost link event is ignored.
14839  * If HBA cannot detect device removal, the lost link event triggers
14840  * device detached event processing after link lost timeout.
14841  * Else, the event is ignored.
14842  *
14843  * NOTE: Only cports are processed for now, i.e. no port multiplier ports
14844  */
14845 static void
14846 sata_process_port_link_events(sata_hba_inst_t *sata_hba_inst,
14847     sata_address_t *saddr)
14848 {
14849 	sata_device_t sata_device;
14850 	sata_cport_info_t *cportinfo;
14851 	sata_drive_info_t *sdinfo;
14852 	uint32_t event_flags;
14853 	int rval;
14854 
14855 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
14856 	    "Processing port %d link event(s)", saddr->cport);
14857 
14858 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
14859 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
14860 	event_flags = cportinfo->cport_event_flags;
14861 
14862 	/* Reset event flags first */
14863 	cportinfo->cport_event_flags &=
14864 	    ~(SATA_EVNT_LINK_ESTABLISHED | SATA_EVNT_LINK_LOST);
14865 
14866 	/* If the port is in SHUTDOWN or FAILED state, ignore link events. */
14867 	if ((cportinfo->cport_state &
14868 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
14869 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
14870 		    cport_mutex);
14871 		return;
14872 	}
14873 
14874 	/*
14875 	 * For the sanity sake get current port state.
14876 	 * Set device address only. Other sata_device fields should be
14877 	 * set by HBA driver.
14878 	 */
14879 	sata_device.satadev_rev = SATA_DEVICE_REV;
14880 	sata_device.satadev_addr = *saddr;
14881 	/*
14882 	 * We have to exit mutex, because the HBA probe port function may
14883 	 * block on its own mutex.
14884 	 */
14885 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
14886 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
14887 	    (SATA_DIP(sata_hba_inst), &sata_device);
14888 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
14889 	sata_update_port_info(sata_hba_inst, &sata_device);
14890 	if (rval != SATA_SUCCESS) {
14891 		/* Something went wrong? Fail the port */
14892 		cportinfo->cport_state = SATA_PSTATE_FAILED;
14893 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
14894 		    cport_mutex);
14895 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14896 		    "SATA port %d probing failed",
14897 		    saddr->cport));
14898 		/*
14899 		 * We may want to release device info structure, but
14900 		 * it is not necessary.
14901 		 */
14902 		return;
14903 	} else {
14904 		/* port probed successfully */
14905 		cportinfo->cport_state |= SATA_STATE_PROBED | SATA_STATE_READY;
14906 	}
14907 	if (event_flags & SATA_EVNT_LINK_ESTABLISHED) {
14908 
14909 		if ((sata_device.satadev_scr.sstatus &
14910 		    SATA_PORT_DEVLINK_UP_MASK) != SATA_PORT_DEVLINK_UP) {
14911 			/* Ignore event */
14912 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
14913 			    "Ignoring port %d link established event - "
14914 			    "link down",
14915 			    saddr->cport);
14916 			goto linklost;
14917 		}
14918 
14919 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
14920 		    "Processing port %d link established event",
14921 		    saddr->cport);
14922 
14923 		/*
14924 		 * For the sanity sake check if a device is attached - check
14925 		 * return state of a port probing.
14926 		 */
14927 		if (sata_device.satadev_type != SATA_DTYPE_NONE &&
14928 		    sata_device.satadev_type != SATA_DTYPE_PMULT) {
14929 			/*
14930 			 * HBA port probe indicated that there is a device
14931 			 * attached. Check if the framework had device info
14932 			 * structure attached for this device.
14933 			 */
14934 			if (cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
14935 				ASSERT(SATA_CPORTINFO_DRV_INFO(cportinfo) !=
14936 				    NULL);
14937 
14938 				sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
14939 				if ((sdinfo->satadrv_type &
14940 				    SATA_VALID_DEV_TYPE) != 0) {
14941 					/*
14942 					 * Dev info structure is present.
14943 					 * If dev_type is set to known type in
14944 					 * the framework's drive info struct
14945 					 * then the device existed before and
14946 					 * the link was probably lost
14947 					 * momentarily - in such case
14948 					 * we may want to check device
14949 					 * identity.
14950 					 * Identity check is not supported now.
14951 					 *
14952 					 * Link established event
14953 					 * triggers device reset event.
14954 					 */
14955 					(SATA_CPORTINFO_DRV_INFO(cportinfo))->
14956 					    satadrv_event_flags |=
14957 					    SATA_EVNT_DEVICE_RESET;
14958 				}
14959 			} else if (cportinfo->cport_dev_type ==
14960 			    SATA_DTYPE_NONE) {
14961 				/*
14962 				 * We got new device attached! If HBA does not
14963 				 * generate device attached events, trigger it
14964 				 * here.
14965 				 */
14966 				if (!(SATA_FEATURES(sata_hba_inst) &
14967 				    SATA_CTLF_HOTPLUG)) {
14968 					cportinfo->cport_event_flags |=
14969 					    SATA_EVNT_DEVICE_ATTACHED;
14970 				}
14971 			}
14972 			/* Reset link lost timeout */
14973 			cportinfo->cport_link_lost_time = 0;
14974 		}
14975 	}
14976 linklost:
14977 	if (event_flags & SATA_EVNT_LINK_LOST) {
14978 		if ((sata_device.satadev_scr.sstatus &
14979 		    SATA_PORT_DEVLINK_UP_MASK) == SATA_PORT_DEVLINK_UP) {
14980 			/* Ignore event */
14981 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
14982 			    "Ignoring port %d link lost event - link is up",
14983 			    saddr->cport);
14984 			goto done;
14985 		}
14986 #ifdef SATA_DEBUG
14987 		if (cportinfo->cport_link_lost_time == 0) {
14988 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
14989 			    "Processing port %d link lost event",
14990 			    saddr->cport);
14991 		}
14992 #endif
14993 		/*
14994 		 * When HBA cannot generate device attached/detached events,
14995 		 * we need to track link lost time and eventually generate
14996 		 * device detach event.
14997 		 */
14998 		if (!(SATA_FEATURES(sata_hba_inst) & SATA_CTLF_HOTPLUG)) {
14999 			/* We are tracking link lost time */
15000 			if (cportinfo->cport_link_lost_time == 0) {
15001 				/* save current time (lbolt value) */
15002 				cportinfo->cport_link_lost_time =
15003 				    ddi_get_lbolt();
15004 				/* just keep link lost event */
15005 				cportinfo->cport_event_flags |=
15006 				    SATA_EVNT_LINK_LOST;
15007 			} else {
15008 				clock_t cur_time = ddi_get_lbolt();
15009 				if ((cur_time -
15010 				    cportinfo->cport_link_lost_time) >=
15011 				    drv_usectohz(
15012 				    SATA_EVNT_LINK_LOST_TIMEOUT)) {
15013 					/* trigger device detach event */
15014 					cportinfo->cport_event_flags |=
15015 					    SATA_EVNT_DEVICE_DETACHED;
15016 					cportinfo->cport_link_lost_time = 0;
15017 					SATADBG1(SATA_DBG_EVENTS,
15018 					    sata_hba_inst,
15019 					    "Triggering port %d "
15020 					    "device detached event",
15021 					    saddr->cport);
15022 				} else {
15023 					/* keep link lost event */
15024 					cportinfo->cport_event_flags |=
15025 					    SATA_EVNT_LINK_LOST;
15026 				}
15027 			}
15028 		}
15029 		/*
15030 		 * We could change port state to disable/delay access to
15031 		 * the attached device until the link is recovered.
15032 		 */
15033 	}
15034 done:
15035 	event_flags = cportinfo->cport_event_flags;
15036 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
15037 	if (event_flags != 0) {
15038 		mutex_enter(&sata_hba_inst->satahba_mutex);
15039 		sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
15040 		mutex_exit(&sata_hba_inst->satahba_mutex);
15041 		mutex_enter(&sata_mutex);
15042 		sata_event_pending |= SATA_EVNT_MAIN;
15043 		mutex_exit(&sata_mutex);
15044 	}
15045 }
15046 
15047 /*
15048  * Device Detached Event processing.
15049  * Port is probed to find if a device is really gone. If so,
15050  * the device info structure is detached from the SATA port info structure
15051  * and released.
15052  * Port status is updated.
15053  *
15054  * NOTE: Process cports event only, no port multiplier ports.
15055  */
15056 static void
15057 sata_process_device_detached(sata_hba_inst_t *sata_hba_inst,
15058     sata_address_t *saddr)
15059 {
15060 	sata_cport_info_t *cportinfo;
15061 	sata_drive_info_t *sdevinfo;
15062 	sata_device_t sata_device;
15063 	dev_info_t *tdip;
15064 	int rval;
15065 
15066 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
15067 	    "Processing port %d device detached", saddr->cport);
15068 
15069 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
15070 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
15071 	/* Clear event flag */
15072 	cportinfo->cport_event_flags &= ~SATA_EVNT_DEVICE_DETACHED;
15073 
15074 	/* If the port is in SHUTDOWN or FAILED state, ignore detach event. */
15075 	if ((cportinfo->cport_state &
15076 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
15077 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
15078 		    cport_mutex);
15079 		return;
15080 	}
15081 	/* For sanity, re-probe the port */
15082 	sata_device.satadev_rev = SATA_DEVICE_REV;
15083 	sata_device.satadev_addr = *saddr;
15084 
15085 	/*
15086 	 * We have to exit mutex, because the HBA probe port function may
15087 	 * block on its own mutex.
15088 	 */
15089 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
15090 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
15091 	    (SATA_DIP(sata_hba_inst), &sata_device);
15092 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
15093 	sata_update_port_info(sata_hba_inst, &sata_device);
15094 	if (rval != SATA_SUCCESS) {
15095 		/* Something went wrong? Fail the port */
15096 		cportinfo->cport_state = SATA_PSTATE_FAILED;
15097 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
15098 		    cport_mutex);
15099 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15100 		    "SATA port %d probing failed",
15101 		    saddr->cport));
15102 		/*
15103 		 * We may want to release device info structure, but
15104 		 * it is not necessary.
15105 		 */
15106 		return;
15107 	} else {
15108 		/* port probed successfully */
15109 		cportinfo->cport_state |= SATA_STATE_PROBED | SATA_STATE_READY;
15110 	}
15111 	/*
15112 	 * Check if a device is still attached. For sanity, check also
15113 	 * link status - if no link, there is no device.
15114 	 */
15115 	if ((sata_device.satadev_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) ==
15116 	    SATA_PORT_DEVLINK_UP && sata_device.satadev_type !=
15117 	    SATA_DTYPE_NONE) {
15118 		/*
15119 		 * Device is still attached - ignore detach event.
15120 		 */
15121 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
15122 		    cport_mutex);
15123 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
15124 		    "Ignoring detach - device still attached to port %d",
15125 		    sata_device.satadev_addr.cport);
15126 		return;
15127 	}
15128 	/*
15129 	 * We need to detach and release device info structure here
15130 	 */
15131 	if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
15132 		sdevinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
15133 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
15134 		(void) kmem_free((void *)sdevinfo,
15135 		    sizeof (sata_drive_info_t));
15136 	}
15137 	cportinfo->cport_dev_type = SATA_DTYPE_NONE;
15138 	/*
15139 	 * Device cannot be reached anymore, even if the target node may be
15140 	 * still present.
15141 	 */
15142 
15143 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
15144 	sata_log(sata_hba_inst, CE_WARN, "SATA device detached at port %d",
15145 	    sata_device.satadev_addr.cport);
15146 
15147 	/*
15148 	 * Try to offline a device and remove target node if it still exists
15149 	 */
15150 	tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst), saddr->cport);
15151 	if (tdip != NULL) {
15152 		/*
15153 		 * Target node exists.  Unconfigure device then remove
15154 		 * the target node (one ndi operation).
15155 		 */
15156 		if (ndi_devi_offline(tdip, NDI_DEVI_REMOVE) != NDI_SUCCESS) {
15157 			/*
15158 			 * PROBLEM - no device, but target node remained
15159 			 * This happens when the file was open or node was
15160 			 * waiting for resources.
15161 			 */
15162 			SATA_LOG_D((sata_hba_inst, CE_WARN,
15163 			    "sata_process_device_detached: "
15164 			    "Failed to remove target node for "
15165 			    "detached SATA device."));
15166 			/*
15167 			 * Set target node state to DEVI_DEVICE_REMOVED.
15168 			 * But re-check first that the node still exists.
15169 			 */
15170 			tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst),
15171 			    saddr->cport);
15172 			if (tdip != NULL) {
15173 				sata_set_device_removed(tdip);
15174 				/*
15175 				 * Instruct event daemon to retry the
15176 				 * cleanup later.
15177 				 */
15178 				sata_set_target_node_cleanup(sata_hba_inst,
15179 				    &sata_device.satadev_addr);
15180 			}
15181 		}
15182 	}
15183 	/*
15184 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
15185 	 * with the hint: SE_HINT_REMOVE
15186 	 */
15187 	sata_gen_sysevent(sata_hba_inst, saddr, SE_HINT_REMOVE);
15188 }
15189 
15190 
15191 /*
15192  * Device Attached Event processing.
15193  * Port state is checked to verify that a device is really attached. If so,
15194  * the device info structure is created and attached to the SATA port info
15195  * structure.
15196  *
15197  * If attached device cannot be identified or set-up, the retry for the
15198  * attach processing is set-up. Subsequent daemon run would try again to
15199  * identify the device, until the time limit is reached
15200  * (SATA_DEV_IDENTIFY_TIMEOUT).
15201  *
15202  * This function cannot be called in interrupt context (it may sleep).
15203  *
15204  * NOTE: Process cports event only, no port multiplier ports.
15205  */
15206 static void
15207 sata_process_device_attached(sata_hba_inst_t *sata_hba_inst,
15208     sata_address_t *saddr)
15209 {
15210 	sata_cport_info_t *cportinfo;
15211 	sata_drive_info_t *sdevinfo;
15212 	sata_device_t sata_device;
15213 	dev_info_t *tdip;
15214 	uint32_t event_flags;
15215 	int rval;
15216 
15217 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
15218 	    "Processing port %d device attached", saddr->cport);
15219 
15220 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
15221 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
15222 
15223 	/* Clear attach event flag first */
15224 	cportinfo->cport_event_flags &= ~SATA_EVNT_DEVICE_ATTACHED;
15225 
15226 	/* If the port is in SHUTDOWN or FAILED state, ignore event. */
15227 	if ((cportinfo->cport_state &
15228 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
15229 		cportinfo->cport_dev_attach_time = 0;
15230 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
15231 		    cport_mutex);
15232 		return;
15233 	}
15234 
15235 	/*
15236 	 * If the sata_drive_info structure is found attached to the port info,
15237 	 * despite the fact the device was removed and now it is re-attached,
15238 	 * the old drive info structure was not removed.
15239 	 * Arbitrarily release device info structure.
15240 	 */
15241 	if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
15242 		sdevinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
15243 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
15244 		(void) kmem_free((void *)sdevinfo,
15245 		    sizeof (sata_drive_info_t));
15246 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
15247 		    "Arbitrarily detaching old device info.", NULL);
15248 	}
15249 	cportinfo->cport_dev_type = SATA_DTYPE_NONE;
15250 
15251 	/* For sanity, re-probe the port */
15252 	sata_device.satadev_rev = SATA_DEVICE_REV;
15253 	sata_device.satadev_addr = *saddr;
15254 
15255 	/*
15256 	 * We have to exit mutex, because the HBA probe port function may
15257 	 * block on its own mutex.
15258 	 */
15259 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
15260 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
15261 	    (SATA_DIP(sata_hba_inst), &sata_device);
15262 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
15263 	sata_update_port_info(sata_hba_inst, &sata_device);
15264 	if (rval != SATA_SUCCESS) {
15265 		/* Something went wrong? Fail the port */
15266 		cportinfo->cport_state = SATA_PSTATE_FAILED;
15267 		cportinfo->cport_dev_attach_time = 0;
15268 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
15269 		    cport_mutex);
15270 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15271 		    "SATA port %d probing failed",
15272 		    saddr->cport));
15273 		return;
15274 	} else {
15275 		/* port probed successfully */
15276 		cportinfo->cport_state |= SATA_STATE_PROBED | SATA_STATE_READY;
15277 	}
15278 	/*
15279 	 * Check if a device is still attached. For sanity, check also
15280 	 * link status - if no link, there is no device.
15281 	 */
15282 	if ((sata_device.satadev_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
15283 	    SATA_PORT_DEVLINK_UP || sata_device.satadev_type ==
15284 	    SATA_DTYPE_NONE) {
15285 		/*
15286 		 * No device - ignore attach event.
15287 		 */
15288 		cportinfo->cport_dev_attach_time = 0;
15289 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
15290 		    cport_mutex);
15291 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
15292 		    "Ignoring attach - no device connected to port %d",
15293 		    sata_device.satadev_addr.cport);
15294 		return;
15295 	}
15296 
15297 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
15298 	/*
15299 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
15300 	 * with the hint: SE_HINT_INSERT
15301 	 */
15302 	sata_gen_sysevent(sata_hba_inst, saddr, SE_HINT_INSERT);
15303 
15304 	/*
15305 	 * Port reprobing will take care of the creation of the device
15306 	 * info structure and determination of the device type.
15307 	 */
15308 	sata_device.satadev_addr = *saddr;
15309 	(void) sata_reprobe_port(sata_hba_inst, &sata_device,
15310 	    SATA_DEV_IDENTIFY_NORETRY);
15311 
15312 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
15313 	    cport_mutex);
15314 	if ((cportinfo->cport_state & SATA_STATE_READY) &&
15315 	    (cportinfo->cport_dev_type != SATA_DTYPE_NONE)) {
15316 		/* Some device is attached to the port */
15317 		if (cportinfo->cport_dev_type == SATA_DTYPE_UNKNOWN) {
15318 			/*
15319 			 * A device was not successfully attached.
15320 			 * Track retry time for device identification.
15321 			 */
15322 			if (cportinfo->cport_dev_attach_time != 0) {
15323 				clock_t cur_time = ddi_get_lbolt();
15324 				/*
15325 				 * If the retry time limit was not exceeded,
15326 				 * reinstate attach event.
15327 				 */
15328 				if ((cur_time -
15329 				    cportinfo->cport_dev_attach_time) <
15330 				    drv_usectohz(
15331 				    SATA_DEV_IDENTIFY_TIMEOUT)) {
15332 					/* OK, restore attach event */
15333 					cportinfo->cport_event_flags |=
15334 					    SATA_EVNT_DEVICE_ATTACHED;
15335 				} else {
15336 					/* Timeout - cannot identify device */
15337 					cportinfo->cport_dev_attach_time = 0;
15338 					sata_log(sata_hba_inst,
15339 					    CE_WARN,
15340 					    "Could not identify SATA device "
15341 					    "at port %d",
15342 					    saddr->cport);
15343 				}
15344 			} else {
15345 				/*
15346 				 * Start tracking time for device
15347 				 * identification.
15348 				 * Save current time (lbolt value).
15349 				 */
15350 				cportinfo->cport_dev_attach_time =
15351 				    ddi_get_lbolt();
15352 				/* Restore attach event */
15353 				cportinfo->cport_event_flags |=
15354 				    SATA_EVNT_DEVICE_ATTACHED;
15355 			}
15356 		} else {
15357 			/*
15358 			 * If device was successfully attached, the subsequent
15359 			 * action depends on a state of the
15360 			 * sata_auto_online variable. If it is set to zero.
15361 			 * an explicit 'configure' command will be needed to
15362 			 * configure it. If its value is non-zero, we will
15363 			 * attempt to online (configure) the device.
15364 			 * First, log the message indicating that a device
15365 			 * was attached.
15366 			 */
15367 			cportinfo->cport_dev_attach_time = 0;
15368 			sata_log(sata_hba_inst, CE_WARN,
15369 			    "SATA device detected at port %d", saddr->cport);
15370 
15371 			if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
15372 				sata_drive_info_t new_sdinfo;
15373 
15374 				/* Log device info data */
15375 				new_sdinfo = *(SATA_CPORTINFO_DRV_INFO(
15376 				    cportinfo));
15377 				sata_show_drive_info(sata_hba_inst,
15378 				    &new_sdinfo);
15379 			}
15380 
15381 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15382 			    saddr->cport)->cport_mutex);
15383 
15384 			/*
15385 			 * Make sure that there is no target node for that
15386 			 * device. If so, release it. It should not happen,
15387 			 * unless we had problem removing the node when
15388 			 * device was detached.
15389 			 */
15390 			tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst),
15391 			    saddr->cport);
15392 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
15393 			    saddr->cport)->cport_mutex);
15394 			if (tdip != NULL) {
15395 
15396 #ifdef SATA_DEBUG
15397 				if ((cportinfo->cport_event_flags &
15398 				    SATA_EVNT_TARGET_NODE_CLEANUP) == 0)
15399 					sata_log(sata_hba_inst, CE_WARN,
15400 					    "sata_process_device_attached: "
15401 					    "old device target node exists!");
15402 #endif
15403 				/*
15404 				 * target node exists - try to unconfigure
15405 				 * device and remove the node.
15406 				 */
15407 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15408 				    saddr->cport)->cport_mutex);
15409 				rval = ndi_devi_offline(tdip,
15410 				    NDI_DEVI_REMOVE);
15411 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
15412 				    saddr->cport)->cport_mutex);
15413 
15414 				if (rval == NDI_SUCCESS) {
15415 					cportinfo->cport_event_flags &=
15416 					    ~SATA_EVNT_TARGET_NODE_CLEANUP;
15417 					cportinfo->cport_tgtnode_clean = B_TRUE;
15418 				} else {
15419 					/*
15420 					 * PROBLEM - the target node remained
15421 					 * and it belongs to a previously
15422 					 * attached device.
15423 					 * This happens when the file was open
15424 					 * or the node was waiting for
15425 					 * resources at the time the
15426 					 * associated device was removed.
15427 					 * Instruct event daemon to retry the
15428 					 * cleanup later.
15429 					 */
15430 					sata_log(sata_hba_inst,
15431 					    CE_WARN,
15432 					    "Application(s) accessing "
15433 					    "previously attached SATA "
15434 					    "device have to release "
15435 					    "it before newly inserted "
15436 					    "device can be made accessible.",
15437 					    saddr->cport);
15438 					cportinfo->cport_event_flags |=
15439 					    SATA_EVNT_TARGET_NODE_CLEANUP;
15440 					cportinfo->cport_tgtnode_clean =
15441 					    B_FALSE;
15442 				}
15443 			}
15444 			if (sata_auto_online != 0) {
15445 				cportinfo->cport_event_flags |=
15446 				    SATA_EVNT_AUTOONLINE_DEVICE;
15447 			}
15448 
15449 		}
15450 	} else {
15451 		cportinfo->cport_dev_attach_time = 0;
15452 	}
15453 
15454 	event_flags = cportinfo->cport_event_flags;
15455 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
15456 	if (event_flags != 0) {
15457 		mutex_enter(&sata_hba_inst->satahba_mutex);
15458 		sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
15459 		mutex_exit(&sata_hba_inst->satahba_mutex);
15460 		mutex_enter(&sata_mutex);
15461 		sata_event_pending |= SATA_EVNT_MAIN;
15462 		mutex_exit(&sata_mutex);
15463 	}
15464 }
15465 
15466 
15467 /*
15468  * Device Target Node Cleanup Event processing.
15469  * If the target node associated with a sata port device is in
15470  * DEVI_DEVICE_REMOVED state, an attempt is made to remove it.
15471  * If the target node cannot be removed, the event flag is left intact,
15472  * so that event daemon may re-run this function later.
15473  *
15474  * This function cannot be called in interrupt context (it may sleep).
15475  *
15476  * NOTE: Processes cport events only, not port multiplier ports.
15477  */
15478 static void
15479 sata_process_target_node_cleanup(sata_hba_inst_t *sata_hba_inst,
15480     sata_address_t *saddr)
15481 {
15482 	sata_cport_info_t *cportinfo;
15483 	dev_info_t *tdip;
15484 
15485 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
15486 	    "Processing port %d device target node cleanup", saddr->cport);
15487 
15488 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
15489 
15490 	/*
15491 	 * Check if there is target node for that device and it is in the
15492 	 * DEVI_DEVICE_REMOVED state. If so, release it.
15493 	 */
15494 	tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst), saddr->cport);
15495 	if (tdip != NULL) {
15496 		/*
15497 		 * target node exists - check if it is target node of
15498 		 * a removed device.
15499 		 */
15500 		if (sata_check_device_removed(tdip) == B_TRUE) {
15501 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
15502 			    "sata_process_target_node_cleanup: "
15503 			    "old device target node exists!", NULL);
15504 			/*
15505 			 * Unconfigure and remove the target node
15506 			 */
15507 			if (ndi_devi_offline(tdip, NDI_DEVI_REMOVE) ==
15508 			    NDI_SUCCESS) {
15509 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
15510 				    saddr->cport)->cport_mutex);
15511 				cportinfo->cport_event_flags &=
15512 				    ~SATA_EVNT_TARGET_NODE_CLEANUP;
15513 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15514 				    saddr->cport)->cport_mutex);
15515 				return;
15516 			}
15517 			/*
15518 			 * Event daemon will retry the cleanup later.
15519 			 */
15520 			mutex_enter(&sata_hba_inst->satahba_mutex);
15521 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
15522 			mutex_exit(&sata_hba_inst->satahba_mutex);
15523 			mutex_enter(&sata_mutex);
15524 			sata_event_pending |= SATA_EVNT_MAIN;
15525 			mutex_exit(&sata_mutex);
15526 		}
15527 	} else {
15528 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
15529 		    saddr->cport)->cport_mutex);
15530 		cportinfo->cport_event_flags &=
15531 		    ~SATA_EVNT_TARGET_NODE_CLEANUP;
15532 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15533 		    saddr->cport)->cport_mutex);
15534 	}
15535 }
15536 
15537 /*
15538  * Device AutoOnline Event processing.
15539  * If attached device is to be onlined, an attempt is made to online this
15540  * device, but only if there is no lingering (old) target node present.
15541  * If the device cannot be onlined, the event flag is left intact,
15542  * so that event daemon may re-run this function later.
15543  *
15544  * This function cannot be called in interrupt context (it may sleep).
15545  *
15546  * NOTE: Processes cport events only, not port multiplier ports.
15547  */
15548 static void
15549 sata_process_device_autoonline(sata_hba_inst_t *sata_hba_inst,
15550     sata_address_t *saddr)
15551 {
15552 	sata_cport_info_t *cportinfo;
15553 	sata_drive_info_t *sdinfo;
15554 	sata_device_t sata_device;
15555 	dev_info_t *tdip;
15556 
15557 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
15558 	    "Processing port %d attached device auto-onlining", saddr->cport);
15559 
15560 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
15561 
15562 	/*
15563 	 * Check if device is present and recognized. If not, reset event.
15564 	 */
15565 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
15566 	if ((cportinfo->cport_dev_type & SATA_VALID_DEV_TYPE) == 0) {
15567 		/* Nothing to online */
15568 		cportinfo->cport_event_flags &= ~SATA_EVNT_AUTOONLINE_DEVICE;
15569 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15570 		    saddr->cport)->cport_mutex);
15571 		return;
15572 	}
15573 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
15574 
15575 	/*
15576 	 * Check if there is target node for this device and if it is in the
15577 	 * DEVI_DEVICE_REMOVED state. If so, abort onlining but keep
15578 	 * the event for later processing.
15579 	 */
15580 	tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst), saddr->cport);
15581 	if (tdip != NULL) {
15582 		/*
15583 		 * target node exists - check if it is target node of
15584 		 * a removed device.
15585 		 */
15586 		if (sata_check_device_removed(tdip) == B_TRUE) {
15587 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
15588 			    "sata_process_device_autoonline: "
15589 			    "old device target node exists!", NULL);
15590 			/*
15591 			 * Event daemon will retry device onlining later.
15592 			 */
15593 			mutex_enter(&sata_hba_inst->satahba_mutex);
15594 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
15595 			mutex_exit(&sata_hba_inst->satahba_mutex);
15596 			mutex_enter(&sata_mutex);
15597 			sata_event_pending |= SATA_EVNT_MAIN;
15598 			mutex_exit(&sata_mutex);
15599 			return;
15600 		}
15601 		/*
15602 		 * If the target node is not in the 'removed" state, assume
15603 		 * that it belongs to this device. There is nothing more to do,
15604 		 * but reset the event.
15605 		 */
15606 	} else {
15607 
15608 		/*
15609 		 * Try to online the device
15610 		 * If there is any reset-related event, remove it. We are
15611 		 * configuring the device and no state restoring is needed.
15612 		 */
15613 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
15614 		    saddr->cport)->cport_mutex);
15615 		sata_device.satadev_addr = *saddr;
15616 		if (saddr->qual == SATA_ADDR_CPORT)
15617 			sata_device.satadev_addr.qual = SATA_ADDR_DCPORT;
15618 		else
15619 			sata_device.satadev_addr.qual = SATA_ADDR_DPMPORT;
15620 		sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
15621 		if (sdinfo != NULL) {
15622 			if (sdinfo->satadrv_event_flags &
15623 			    (SATA_EVNT_DEVICE_RESET |
15624 			    SATA_EVNT_INPROC_DEVICE_RESET))
15625 				sdinfo->satadrv_event_flags = 0;
15626 			sdinfo->satadrv_event_flags |=
15627 			    SATA_EVNT_CLEAR_DEVICE_RESET;
15628 
15629 			/* Need to create a new target node. */
15630 			cportinfo->cport_tgtnode_clean = B_TRUE;
15631 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15632 			    saddr->cport)->cport_mutex);
15633 			tdip = sata_create_target_node(SATA_DIP(sata_hba_inst),
15634 			    sata_hba_inst, &sata_device.satadev_addr);
15635 			if (tdip == NULL) {
15636 				/*
15637 				 * Configure (onlining) failed.
15638 				 * We will NOT retry
15639 				 */
15640 				SATA_LOG_D((sata_hba_inst, CE_WARN,
15641 				    "sata_process_device_autoonline: "
15642 				    "configuring SATA device at port %d failed",
15643 				    saddr->cport));
15644 			}
15645 		} else {
15646 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15647 			    saddr->cport)->cport_mutex);
15648 		}
15649 
15650 	}
15651 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
15652 	cportinfo->cport_event_flags &= ~SATA_EVNT_AUTOONLINE_DEVICE;
15653 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15654 	    saddr->cport)->cport_mutex);
15655 }
15656 
15657 
15658 static void
15659 sata_gen_sysevent(sata_hba_inst_t *sata_hba_inst, sata_address_t *saddr,
15660     int hint)
15661 {
15662 	char ap[MAXPATHLEN];
15663 	nvlist_t *ev_attr_list = NULL;
15664 	int err;
15665 
15666 	/* Allocate and build sysevent attribute list */
15667 	err = nvlist_alloc(&ev_attr_list, NV_UNIQUE_NAME_TYPE, DDI_NOSLEEP);
15668 	if (err != 0) {
15669 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15670 		    "sata_gen_sysevent: "
15671 		    "cannot allocate memory for sysevent attributes\n"));
15672 		return;
15673 	}
15674 	/* Add hint attribute */
15675 	err = nvlist_add_string(ev_attr_list, DR_HINT, SE_HINT2STR(hint));
15676 	if (err != 0) {
15677 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15678 		    "sata_gen_sysevent: "
15679 		    "failed to add DR_HINT attr for sysevent"));
15680 		nvlist_free(ev_attr_list);
15681 		return;
15682 	}
15683 	/*
15684 	 * Add AP attribute.
15685 	 * Get controller pathname and convert it into AP pathname by adding
15686 	 * a target number.
15687 	 */
15688 	(void) snprintf(ap, MAXPATHLEN, "/devices");
15689 	(void) ddi_pathname(SATA_DIP(sata_hba_inst), ap + strlen(ap));
15690 	(void) snprintf(ap + strlen(ap), MAXPATHLEN - strlen(ap), ":%d",
15691 	    SATA_MAKE_AP_NUMBER(saddr->cport, saddr->pmport, saddr->qual));
15692 
15693 	err = nvlist_add_string(ev_attr_list, DR_AP_ID, ap);
15694 	if (err != 0) {
15695 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15696 		    "sata_gen_sysevent: "
15697 		    "failed to add DR_AP_ID attr for sysevent"));
15698 		nvlist_free(ev_attr_list);
15699 		return;
15700 	}
15701 
15702 	/* Generate/log sysevent */
15703 	err = ddi_log_sysevent(SATA_DIP(sata_hba_inst), DDI_VENDOR_SUNW, EC_DR,
15704 	    ESC_DR_AP_STATE_CHANGE, ev_attr_list, NULL, DDI_NOSLEEP);
15705 	if (err != DDI_SUCCESS) {
15706 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15707 		    "sata_gen_sysevent: "
15708 		    "cannot log sysevent, err code %x\n", err));
15709 	}
15710 
15711 	nvlist_free(ev_attr_list);
15712 }
15713 
15714 
15715 
15716 
15717 /*
15718  * Set DEVI_DEVICE_REMOVED state in the SATA device target node.
15719  */
15720 static void
15721 sata_set_device_removed(dev_info_t *tdip)
15722 {
15723 	int circ;
15724 
15725 	ASSERT(tdip != NULL);
15726 
15727 	ndi_devi_enter(tdip, &circ);
15728 	mutex_enter(&DEVI(tdip)->devi_lock);
15729 	DEVI_SET_DEVICE_REMOVED(tdip);
15730 	mutex_exit(&DEVI(tdip)->devi_lock);
15731 	ndi_devi_exit(tdip, circ);
15732 }
15733 
15734 
15735 /*
15736  * Set internal event instructing event daemon to try
15737  * to perform the target node cleanup.
15738  */
15739 static void
15740 sata_set_target_node_cleanup(sata_hba_inst_t *sata_hba_inst,
15741     sata_address_t *saddr)
15742 {
15743 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
15744 	SATA_CPORT_EVENT_FLAGS(sata_hba_inst, saddr->cport) |=
15745 	    SATA_EVNT_TARGET_NODE_CLEANUP;
15746 	SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_tgtnode_clean =
15747 	    B_FALSE;
15748 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
15749 	mutex_enter(&sata_hba_inst->satahba_mutex);
15750 	sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
15751 	mutex_exit(&sata_hba_inst->satahba_mutex);
15752 	mutex_enter(&sata_mutex);
15753 	sata_event_pending |= SATA_EVNT_MAIN;
15754 	mutex_exit(&sata_mutex);
15755 }
15756 
15757 
15758 /*
15759  * Check if the SATA device target node is in DEVI_DEVICE_REMOVED state,
15760  * i.e. check if the target node state indicates that it belongs to a removed
15761  * device.
15762  *
15763  * Returns B_TRUE if the target node is in DEVI_DEVICE_REMOVED state,
15764  * B_FALSE otherwise.
15765  *
15766  * NOTE: No port multiplier support.
15767  */
15768 static boolean_t
15769 sata_check_device_removed(dev_info_t *tdip)
15770 {
15771 	ASSERT(tdip != NULL);
15772 
15773 	if (DEVI_IS_DEVICE_REMOVED(tdip))
15774 		return (B_TRUE);
15775 	else
15776 		return (B_FALSE);
15777 }
15778 
15779 /* ************************ FAULT INJECTTION **************************** */
15780 
15781 #ifdef SATA_INJECT_FAULTS
15782 
15783 static	uint32_t sata_fault_count = 0;
15784 static	uint32_t sata_fault_suspend_count = 0;
15785 
15786 /*
15787  * Inject sata pkt fault
15788  * It modifies returned values of the sata packet.
15789  * It returns immediately if:
15790  * pkt fault injection is not enabled (via sata_inject_fault,
15791  * sata_inject_fault_count), or invalid fault is specified (sata_fault_type),
15792  * or pkt does not contain command to be faulted (set in sata_fault_cmd), or
15793  * pkt is not directed to specified fault controller/device
15794  * (sata_fault_ctrl_dev and sata_fault_device).
15795  * If fault controller is not specified, fault injection applies to all
15796  * controllers and devices.
15797  *
15798  * First argument is the pointer to the executed sata packet.
15799  * Second argument is a pointer to a value returned by the HBA tran_start
15800  * function.
15801  * Third argument specifies injected error. Injected sata packet faults
15802  * are the satapkt_reason values.
15803  * SATA_PKT_BUSY		-1	Not completed, busy
15804  * SATA_PKT_DEV_ERROR		1	Device reported error
15805  * SATA_PKT_QUEUE_FULL		2	Not accepted, queue full
15806  * SATA_PKT_PORT_ERROR		3	Not completed, port error
15807  * SATA_PKT_CMD_UNSUPPORTED	4	Cmd unsupported
15808  * SATA_PKT_ABORTED		5	Aborted by request
15809  * SATA_PKT_TIMEOUT		6	Operation timeut
15810  * SATA_PKT_RESET		7	Aborted by reset request
15811  *
15812  * Additional global variables affecting the execution:
15813  *
15814  * sata_inject_fault_count variable specifies number of times in row the
15815  * error is injected. Value of -1 specifies permanent fault, ie. every time
15816  * the fault injection point is reached, the fault is injected and a pause
15817  * between fault injection specified by sata_inject_fault_pause_count is
15818  * ignored). Fault injection routine decrements sata_inject_fault_count
15819  * (if greater than zero) until it reaches 0. No fault is injected when
15820  * sata_inject_fault_count is 0 (zero).
15821  *
15822  * sata_inject_fault_pause_count variable specifies number of times a fault
15823  * injection is bypassed (pause between fault injections).
15824  * If set to 0, a fault is injected only a number of times specified by
15825  * sata_inject_fault_count.
15826  *
15827  * The fault counts are static, so for periodic errors they have to be manually
15828  * reset to start repetition sequence from scratch.
15829  * If the original value returned by the HBA tran_start function is not
15830  * SATA_TRAN_ACCEPTED and pkt reason is not SATA_PKT_COMPLETED, no error
15831  * is injected (to avoid masking real problems);
15832  *
15833  * NOTE: In its current incarnation, this function should be invoked only for
15834  * commands executed in SYNCHRONOUS mode.
15835  */
15836 
15837 
15838 static	void
15839 sata_inject_pkt_fault(sata_pkt_t *spkt, int *rval, int fault)
15840 {
15841 
15842 	if (sata_inject_fault != SATA_INJECT_PKT_FAULT)
15843 		return;
15844 
15845 	if (sata_inject_fault_count == 0)
15846 		return;
15847 
15848 	if (fault == 0)
15849 		return;
15850 
15851 	if (sata_fault_cmd != spkt->satapkt_cmd.satacmd_cmd_reg)
15852 		return;
15853 
15854 	if (sata_fault_ctrl != NULL) {
15855 		sata_pkt_txlate_t *spx =
15856 		    (sata_pkt_txlate_t *)spkt->satapkt_framework_private;
15857 
15858 		if (sata_fault_ctrl != NULL && sata_fault_ctrl !=
15859 		    spx->txlt_sata_hba_inst->satahba_dip)
15860 			return;
15861 
15862 		if (sata_fault_device.satadev_addr.cport !=
15863 		    spkt->satapkt_device.satadev_addr.cport ||
15864 		    sata_fault_device.satadev_addr.pmport !=
15865 		    spkt->satapkt_device.satadev_addr.pmport ||
15866 		    sata_fault_device.satadev_addr.qual !=
15867 		    spkt->satapkt_device.satadev_addr.qual)
15868 			return;
15869 	}
15870 
15871 	/* Modify pkt return parameters */
15872 	if (*rval != SATA_TRAN_ACCEPTED ||
15873 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
15874 		sata_fault_count = 0;
15875 		sata_fault_suspend_count = 0;
15876 		return;
15877 	}
15878 	if (sata_fault_count == 0 && sata_fault_suspend_count != 0) {
15879 		/* Pause in the injection */
15880 		sata_fault_suspend_count -= 1;
15881 		return;
15882 	}
15883 
15884 	if (sata_fault_count == 0 && sata_fault_suspend_count == 0) {
15885 		/*
15886 		 * Init inject fault cycle. If fault count is set to -1,
15887 		 * it is a permanent fault.
15888 		 */
15889 		if (sata_inject_fault_count != -1) {
15890 			sata_fault_count = sata_inject_fault_count;
15891 			sata_fault_suspend_count =
15892 			    sata_inject_fault_pause_count;
15893 			if (sata_fault_suspend_count == 0)
15894 				sata_inject_fault_count = 0;
15895 		}
15896 	}
15897 
15898 	if (sata_fault_count != 0)
15899 		sata_fault_count -= 1;
15900 
15901 	switch (fault) {
15902 	case SATA_PKT_BUSY:
15903 		*rval = SATA_TRAN_BUSY;
15904 		spkt->satapkt_reason = SATA_PKT_BUSY;
15905 		break;
15906 
15907 	case SATA_PKT_QUEUE_FULL:
15908 		*rval = SATA_TRAN_QUEUE_FULL;
15909 		spkt->satapkt_reason = SATA_PKT_QUEUE_FULL;
15910 		break;
15911 
15912 	case SATA_PKT_CMD_UNSUPPORTED:
15913 		*rval = SATA_TRAN_CMD_UNSUPPORTED;
15914 		spkt->satapkt_reason = SATA_PKT_CMD_UNSUPPORTED;
15915 		break;
15916 
15917 	case SATA_PKT_PORT_ERROR:
15918 		/* This is "rejected" command */
15919 		*rval = SATA_TRAN_PORT_ERROR;
15920 		spkt->satapkt_reason = SATA_PKT_PORT_ERROR;
15921 		/* Additional error setup could be done here - port state */
15922 		break;
15923 
15924 	case SATA_PKT_DEV_ERROR:
15925 		spkt->satapkt_reason = SATA_PKT_DEV_ERROR;
15926 		/*
15927 		 * Additional error setup could be done here
15928 		 */
15929 		break;
15930 
15931 	case SATA_PKT_ABORTED:
15932 		spkt->satapkt_reason = SATA_PKT_ABORTED;
15933 		break;
15934 
15935 	case SATA_PKT_TIMEOUT:
15936 		spkt->satapkt_reason = SATA_PKT_TIMEOUT;
15937 		/* Additional error setup could be done here */
15938 		break;
15939 
15940 	case SATA_PKT_RESET:
15941 		spkt->satapkt_reason = SATA_PKT_RESET;
15942 		/*
15943 		 * Additional error setup could be done here - device reset
15944 		 */
15945 		break;
15946 
15947 	default:
15948 		break;
15949 	}
15950 }
15951 
15952 #endif
15953