Print this page
Code reconciliation with other base.
hg changesets 607a5b46a793..b706c96317c3
Fix ncpus for early boot config
Purge the ack to the interrupt before exiting mptsas_intr()
Changes from code review
Optimise slot alocation through rotor and the use
of per target mutex in start path.
Update tx waitq's code.
Create 2 threads, divide the workflow and deliver
to the hardware from the threads.
Optimise mutex's and code paths.
Split out offline target code.
Test timeouts code
Add support for more than 8 MSI-X interrupts.
Tidy up interrupt assignement and card ID messages.
Enable Fast Path for capable devices.
Merge fixes for Illumos issue 4819, fix mpt_sas command timeout handling.
Tweeks debug flags.
Default to process done commands all in threads if only 1 interrupt.
Lint and cstyle fixes.
Fix problem with running against 64bit msgaddr attributes for DMA.
Default is now to run like this.
Don't take tx_waiq_mutex if draining isn't set.
Fixes for Illumos issue 4682.
Fix hang bug to do with tx_wq.
Re-arrange mptsas_poll() to disable interrupts before issuing the
command.
Improve the tx_waitq code path.
Major rework of mutexes.
During normal operation do not grab m_mutex during interrupt.
Use reply post queues instead.
Make a few variable non static so you can change in /etc/system.
Fixes to some address arithmetic using 32bit values.
Distribute command done processing around the threads.
Improved auto-request sense memory usage.
Fix for Nexenta commit 36c74113a21
OS-91 mptsas does inquiry without setting pkt_time
Add comment about testing.
Test firmware version of 2008 controllers for MSI-X Compatibility.
Re-arrange mptsas_intr() to reduce number of spurious interrupts.
Fix bug in mptsas_free_post_queue().
Change mptsas_doneq_mv() to not loop.
Should not need m_in_callback flag. It prevents concurrent
command completion processing.
Added code to support using MSI-X interrupts across multiple
reply queues. Not tested with anything other than 3008 yet.
Change output "mptsas%d" -> "mptsas3%d".
Add SAS3 specific messages (12.0Gb).
Allow over-ride for interrupt type.
Restrict pre MPI2.5 to MSI interrupts.
Allow watchdog timout to work for mptsas_smhba_setup() in attach().
Merge fixes for "4403 mpt_sas panic when pulling a drive", commit f7d0d869a9ae78d
Use MSI-X interrupts, just one for now.
Pre-allocate array for request sense buffers, similar to command frames.
No more messing about with scsi_alloc_consistent_buf().
Add rolling buffer for *all* debug messages.
Improve mdb module and seperate out into mpt_sas3.
Initial modifications using the code changes present between
the LSI source code for FreeBSD drivers. Specifically the changes
between from mpslsi-source-17.00.00.00 -> mpslsi-source-03.00.00.00.
This mainly involves using a different scatter/gather element in
frame setup.
Change some obvious references sas -> sas3.
Changes to enable driver to compile.
Header paths, object lists, etc.


   4  * The contents of this file are subject to the terms of the
   5  * Common Development and Distribution License (the "License").
   6  * You may not use this file except in compliance with the License.
   7  *
   8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
   9  * or http://www.opensolaris.org/os/licensing.
  10  * See the License for the specific language governing permissions
  11  * and limitations under the License.
  12  *
  13  * When distributing Covered Code, include this CDDL HEADER in each
  14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
  15  * If applicable, add the following below this CDDL HEADER, with the
  16  * fields enclosed by brackets "[]" replaced with your own identifying
  17  * information: Portions Copyright [yyyy] [name of copyright owner]
  18  *
  19  * CDDL HEADER END
  20  */
  21 
  22 /*
  23  * Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
  24  * Copyright 2012 Nexenta Systems, Inc. All rights reserved.
  25  * Copyright (c) 2014, Joyent, Inc. All rights reserved.


  26  */
  27 
  28 /*
  29  * Copyright (c) 2000 to 2010, LSI Corporation.
  30  * All rights reserved.
  31  *
  32  * Redistribution and use in source and binary forms of all code within
  33  * this file that is exclusively owned by LSI, with or without
  34  * modification, is permitted provided that, in addition to the CDDL 1.0
  35  * License requirements, the following conditions are met:
  36  *
  37  *    Neither the name of the author nor the names of its contributors may be
  38  *    used to endorse or promote products derived from this software without
  39  *    specific prior written permission.
  40  *
  41  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  42  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  43  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  44  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  45  * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  46  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  47  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
  48  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
  49  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  50  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  51  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
  52  * DAMAGE.
  53  */
  54 
  55 /*
  56  * mptsas - This is a driver based on LSI Logic's MPT2.0 interface.
  57  *
  58  */
  59 
  60 #if defined(lint) || defined(DEBUG)
  61 #define MPTSAS_DEBUG
  62 #endif
  63 
  64 /*
  65  * standard header files.
  66  */
  67 #include <sys/note.h>
  68 #include <sys/scsi/scsi.h>
  69 #include <sys/pci.h>
  70 #include <sys/file.h>
  71 #include <sys/policy.h>
  72 #include <sys/model.h>
  73 #include <sys/sysevent.h>
  74 #include <sys/sysevent/eventdefs.h>
  75 #include <sys/sysevent/dr.h>
  76 #include <sys/sata/sata_defs.h>
  77 #include <sys/scsi/generic/sas.h>
  78 #include <sys/scsi/impl/scsi_sas.h>
  79 
  80 #pragma pack(1)
  81 #include <sys/scsi/adapters/mpt_sas/mpi/mpi2_type.h>
  82 #include <sys/scsi/adapters/mpt_sas/mpi/mpi2.h>
  83 #include <sys/scsi/adapters/mpt_sas/mpi/mpi2_cnfg.h>
  84 #include <sys/scsi/adapters/mpt_sas/mpi/mpi2_init.h>
  85 #include <sys/scsi/adapters/mpt_sas/mpi/mpi2_ioc.h>
  86 #include <sys/scsi/adapters/mpt_sas/mpi/mpi2_sas.h>
  87 #include <sys/scsi/adapters/mpt_sas/mpi/mpi2_tool.h>
  88 #include <sys/scsi/adapters/mpt_sas/mpi/mpi2_raid.h>
  89 #pragma pack()
  90 
  91 /*
  92  * private header files.
  93  *
  94  */
  95 #include <sys/scsi/impl/scsi_reset_notify.h>
  96 #include <sys/scsi/adapters/mpt_sas/mptsas_var.h>
  97 #include <sys/scsi/adapters/mpt_sas/mptsas_ioctl.h>
  98 #include <sys/scsi/adapters/mpt_sas/mptsas_smhba.h>
  99 #include <sys/scsi/adapters/mpt_sas/mptsas_hash.h>
 100 #include <sys/raidioctl.h>
 101 
 102 #include <sys/fs/dv_node.h>       /* devfs_clean */
 103 
 104 /*
 105  * FMA header files
 106  */
 107 #include <sys/ddifm.h>
 108 #include <sys/fm/protocol.h>
 109 #include <sys/fm/util.h>
 110 #include <sys/fm/io/ddi.h>
 111 
 112 /*
 113  * autoconfiguration data and routines.
 114  */
 115 static int mptsas_attach(dev_info_t *dip, ddi_attach_cmd_t cmd);
 116 static int mptsas_detach(dev_info_t *devi, ddi_detach_cmd_t cmd);
 117 static int mptsas_power(dev_info_t *dip, int component, int level);
 118 
 119 /*


 127 static int mptsas_quiesce(dev_info_t *devi);
 128 #endif  /* __sparc */
 129 
 130 /*
 131  * Resource initilaization for hardware
 132  */
 133 static void mptsas_setup_cmd_reg(mptsas_t *mpt);
 134 static void mptsas_disable_bus_master(mptsas_t *mpt);
 135 static void mptsas_hba_fini(mptsas_t *mpt);
 136 static void mptsas_cfg_fini(mptsas_t *mptsas_blkp);
 137 static int mptsas_hba_setup(mptsas_t *mpt);
 138 static void mptsas_hba_teardown(mptsas_t *mpt);
 139 static int mptsas_config_space_init(mptsas_t *mpt);
 140 static void mptsas_config_space_fini(mptsas_t *mpt);
 141 static void mptsas_iport_register(mptsas_t *mpt);
 142 static int mptsas_smp_setup(mptsas_t *mpt);
 143 static void mptsas_smp_teardown(mptsas_t *mpt);
 144 static int mptsas_cache_create(mptsas_t *mpt);
 145 static void mptsas_cache_destroy(mptsas_t *mpt);
 146 static int mptsas_alloc_request_frames(mptsas_t *mpt);

 147 static int mptsas_alloc_reply_frames(mptsas_t *mpt);
 148 static int mptsas_alloc_free_queue(mptsas_t *mpt);
 149 static int mptsas_alloc_post_queue(mptsas_t *mpt);

 150 static void mptsas_alloc_reply_args(mptsas_t *mpt);
 151 static int mptsas_alloc_extra_sgl_frame(mptsas_t *mpt, mptsas_cmd_t *cmd);
 152 static void mptsas_free_extra_sgl_frame(mptsas_t *mpt, mptsas_cmd_t *cmd);
 153 static int mptsas_init_chip(mptsas_t *mpt, int first_time);
 154 
 155 /*
 156  * SCSA function prototypes
 157  */
 158 static int mptsas_scsi_start(struct scsi_address *ap, struct scsi_pkt *pkt);
 159 static int mptsas_scsi_reset(struct scsi_address *ap, int level);
 160 static int mptsas_scsi_abort(struct scsi_address *ap, struct scsi_pkt *pkt);
 161 static int mptsas_scsi_getcap(struct scsi_address *ap, char *cap, int tgtonly);
 162 static int mptsas_scsi_setcap(struct scsi_address *ap, char *cap, int value,
 163     int tgtonly);
 164 static void mptsas_scsi_dmafree(struct scsi_address *ap, struct scsi_pkt *pkt);
 165 static struct scsi_pkt *mptsas_scsi_init_pkt(struct scsi_address *ap,
 166     struct scsi_pkt *pkt, struct buf *bp, int cmdlen, int statuslen,
 167         int tgtlen, int flags, int (*callback)(), caddr_t arg);
 168 static void mptsas_scsi_sync_pkt(struct scsi_address *ap, struct scsi_pkt *pkt);
 169 static void mptsas_scsi_destroy_pkt(struct scsi_address *ap,


 184 /*
 185  * SMP functions
 186  */
 187 static int mptsas_smp_start(struct smp_pkt *smp_pkt);
 188 
 189 /*
 190  * internal function prototypes.
 191  */
 192 static void mptsas_list_add(mptsas_t *mpt);
 193 static void mptsas_list_del(mptsas_t *mpt);
 194 
 195 static int mptsas_quiesce_bus(mptsas_t *mpt);
 196 static int mptsas_unquiesce_bus(mptsas_t *mpt);
 197 
 198 static int mptsas_alloc_handshake_msg(mptsas_t *mpt, size_t alloc_size);
 199 static void mptsas_free_handshake_msg(mptsas_t *mpt);
 200 
 201 static void mptsas_ncmds_checkdrain(void *arg);
 202 
 203 static int mptsas_prepare_pkt(mptsas_cmd_t *cmd);
 204 static int mptsas_accept_pkt(mptsas_t *mpt, mptsas_cmd_t *sp);
 205 static int mptsas_accept_txwq_and_pkt(mptsas_t *mpt, mptsas_cmd_t *sp);
 206 static void mptsas_accept_tx_waitq(mptsas_t *mpt);





 207 
 208 static int mptsas_do_detach(dev_info_t *dev);
 209 static int mptsas_do_scsi_reset(mptsas_t *mpt, uint16_t devhdl);
 210 static int mptsas_do_scsi_abort(mptsas_t *mpt, int target, int lun,
 211     struct scsi_pkt *pkt);
 212 static int mptsas_scsi_capchk(char *cap, int tgtonly, int *cidxp);
 213 
 214 static void mptsas_handle_qfull(mptsas_t *mpt, mptsas_cmd_t *cmd);
 215 static void mptsas_handle_event(void *args);
 216 static int mptsas_handle_event_sync(void *args);
 217 static void mptsas_handle_dr(void *args);
 218 static void mptsas_handle_topo_change(mptsas_topo_change_list_t *topo_node,
 219     dev_info_t *pdip);
 220 
 221 static void mptsas_restart_cmd(void *);
 222 
 223 static void mptsas_flush_hba(mptsas_t *mpt);
 224 static void mptsas_flush_target(mptsas_t *mpt, ushort_t target, int lun,
 225         uint8_t tasktype);
 226 static void mptsas_set_pkt_reason(mptsas_t *mpt, mptsas_cmd_t *cmd,
 227     uchar_t reason, uint_t stat);
 228 
 229 static uint_t mptsas_intr(caddr_t arg1, caddr_t arg2);
 230 static void mptsas_process_intr(mptsas_t *mpt,
 231     pMpi2ReplyDescriptorsUnion_t reply_desc_union);
 232 static void mptsas_handle_scsi_io_success(mptsas_t *mpt,
 233     pMpi2ReplyDescriptorsUnion_t reply_desc);
 234 static void mptsas_handle_address_reply(mptsas_t *mpt,
 235     pMpi2ReplyDescriptorsUnion_t reply_desc);
 236 static int mptsas_wait_intr(mptsas_t *mpt, int polltime);
 237 static void mptsas_sge_setup(mptsas_t *mpt, mptsas_cmd_t *cmd,
 238     uint32_t *control, pMpi2SCSIIORequest_t frame, ddi_acc_handle_t acc_hdl);
 239 
 240 static void mptsas_watch(void *arg);
 241 static void mptsas_watchsubr(mptsas_t *mpt);
 242 static void mptsas_cmd_timeout(mptsas_t *mpt, uint16_t devhdl);
 243 
 244 static void mptsas_start_passthru(mptsas_t *mpt, mptsas_cmd_t *cmd);
 245 static int mptsas_do_passthru(mptsas_t *mpt, uint8_t *request, uint8_t *reply,
 246     uint8_t *data, uint32_t request_size, uint32_t reply_size,
 247     uint32_t data_size, uint32_t direction, uint8_t *dataout,
 248     uint32_t dataout_size, short timeout, int mode);
 249 static int mptsas_free_devhdl(mptsas_t *mpt, uint16_t devhdl);
 250 
 251 static uint8_t mptsas_get_fw_diag_buffer_number(mptsas_t *mpt,
 252     uint32_t unique_id);
 253 static void mptsas_start_diag(mptsas_t *mpt, mptsas_cmd_t *cmd);
 254 static int mptsas_post_fw_diag_buffer(mptsas_t *mpt,
 255     mptsas_fw_diagnostic_buffer_t *pBuffer, uint32_t *return_code);
 256 static int mptsas_release_fw_diag_buffer(mptsas_t *mpt,
 257     mptsas_fw_diagnostic_buffer_t *pBuffer, uint32_t *return_code,
 258     uint32_t diag_type);
 259 static int mptsas_diag_register(mptsas_t *mpt,
 260     mptsas_fw_diag_register_t *diag_register, uint32_t *return_code);
 261 static int mptsas_diag_unregister(mptsas_t *mpt,
 262     mptsas_fw_diag_unregister_t *diag_unregister, uint32_t *return_code);
 263 static int mptsas_diag_query(mptsas_t *mpt, mptsas_fw_diag_query_t *diag_query,
 264     uint32_t *return_code);
 265 static int mptsas_diag_read_buffer(mptsas_t *mpt,
 266     mptsas_diag_read_buffer_t *diag_read_buffer, uint8_t *ioctl_buf,
 267     uint32_t *return_code, int ioctl_mode);


 282 
 283 static int mptsas_cache_frames_constructor(void *buf, void *cdrarg,
 284     int kmflags);
 285 static void mptsas_cache_frames_destructor(void *buf, void *cdrarg);
 286 
 287 static void mptsas_check_scsi_io_error(mptsas_t *mpt, pMpi2SCSIIOReply_t reply,
 288     mptsas_cmd_t *cmd);
 289 static void mptsas_check_task_mgt(mptsas_t *mpt,
 290     pMpi2SCSIManagementReply_t reply, mptsas_cmd_t *cmd);
 291 static int mptsas_send_scsi_cmd(mptsas_t *mpt, struct scsi_address *ap,
 292     mptsas_target_t *ptgt, uchar_t *cdb, int cdblen, struct buf *data_bp,
 293     int *resid);
 294 
 295 static int mptsas_alloc_active_slots(mptsas_t *mpt, int flag);
 296 static void mptsas_free_active_slots(mptsas_t *mpt);
 297 static int mptsas_start_cmd(mptsas_t *mpt, mptsas_cmd_t *cmd);
 298 
 299 static void mptsas_restart_hba(mptsas_t *mpt);
 300 static void mptsas_restart_waitq(mptsas_t *mpt);
 301 
 302 static void mptsas_deliver_doneq_thread(mptsas_t *mpt);

 303 static void mptsas_doneq_add(mptsas_t *mpt, mptsas_cmd_t *cmd);
 304 static void mptsas_doneq_mv(mptsas_t *mpt, uint64_t t);



 305 
 306 static mptsas_cmd_t *mptsas_doneq_thread_rm(mptsas_t *mpt, uint64_t t);
 307 static void mptsas_doneq_empty(mptsas_t *mpt);
 308 static void mptsas_doneq_thread(mptsas_doneq_thread_arg_t *arg);


 309 
 310 static mptsas_cmd_t *mptsas_waitq_rm(mptsas_t *mpt);
 311 static void mptsas_waitq_delete(mptsas_t *mpt, mptsas_cmd_t *cmd);
 312 static mptsas_cmd_t *mptsas_tx_waitq_rm(mptsas_t *mpt);
 313 static void mptsas_tx_waitq_delete(mptsas_t *mpt, mptsas_cmd_t *cmd);
 314 
 315 
 316 static void mptsas_start_watch_reset_delay();
 317 static void mptsas_setup_bus_reset_delay(mptsas_t *mpt);
 318 static void mptsas_watch_reset_delay(void *arg);
 319 static int mptsas_watch_reset_delay_subr(mptsas_t *mpt);





 320 
 321 /*
 322  * helper functions
 323  */
 324 static void mptsas_dump_cmd(mptsas_t *mpt, mptsas_cmd_t *cmd);
 325 
 326 static dev_info_t *mptsas_find_child(dev_info_t *pdip, char *name);
 327 static dev_info_t *mptsas_find_child_phy(dev_info_t *pdip, uint8_t phy);
 328 static dev_info_t *mptsas_find_child_addr(dev_info_t *pdip, uint64_t sasaddr,
 329     int lun);
 330 static mdi_pathinfo_t *mptsas_find_path_addr(dev_info_t *pdip, uint64_t sasaddr,
 331     int lun);
 332 static mdi_pathinfo_t *mptsas_find_path_phy(dev_info_t *pdip, uint8_t phy);
 333 static dev_info_t *mptsas_find_smp_child(dev_info_t *pdip, char *str_wwn);
 334 
 335 static int mptsas_parse_address(char *name, uint64_t *wwid, uint8_t *phy,
 336     int *lun);
 337 static int mptsas_parse_smp_name(char *name, uint64_t *wwn);
 338 
 339 static mptsas_target_t *mptsas_phy_to_tgt(mptsas_t *mpt,


 352 
 353 static int mptsas_send_sep(mptsas_t *mpt, mptsas_target_t *ptgt,
 354     uint32_t *status, uint8_t cmd);
 355 static dev_info_t *mptsas_get_dip_from_dev(dev_t dev,
 356     mptsas_phymask_t *phymask);
 357 static mptsas_target_t *mptsas_addr_to_ptgt(mptsas_t *mpt, char *addr,
 358     mptsas_phymask_t phymask);
 359 static int mptsas_flush_led_status(mptsas_t *mpt, mptsas_target_t *ptgt);
 360 
 361 
 362 /*
 363  * Enumeration / DR functions
 364  */
 365 static void mptsas_config_all(dev_info_t *pdip);
 366 static int mptsas_config_one_addr(dev_info_t *pdip, uint64_t sasaddr, int lun,
 367     dev_info_t **lundip);
 368 static int mptsas_config_one_phy(dev_info_t *pdip, uint8_t phy, int lun,
 369     dev_info_t **lundip);
 370 
 371 static int mptsas_config_target(dev_info_t *pdip, mptsas_target_t *ptgt);
 372 static int mptsas_offline_target(dev_info_t *pdip, char *name);


 373 
 374 static int mptsas_config_raid(dev_info_t *pdip, uint16_t target,
 375     dev_info_t **dip);
 376 
 377 static int mptsas_config_luns(dev_info_t *pdip, mptsas_target_t *ptgt);
 378 static int mptsas_probe_lun(dev_info_t *pdip, int lun,
 379     dev_info_t **dip, mptsas_target_t *ptgt);
 380 
 381 static int mptsas_create_lun(dev_info_t *pdip, struct scsi_inquiry *sd_inq,
 382     dev_info_t **dip, mptsas_target_t *ptgt, int lun);
 383 
 384 static int mptsas_create_phys_lun(dev_info_t *pdip, struct scsi_inquiry *sd,
 385     char *guid, dev_info_t **dip, mptsas_target_t *ptgt, int lun);
 386 static int mptsas_create_virt_lun(dev_info_t *pdip, struct scsi_inquiry *sd,
 387     char *guid, dev_info_t **dip, mdi_pathinfo_t **pip, mptsas_target_t *ptgt,
 388     int lun);
 389 
 390 static void mptsas_offline_missed_luns(dev_info_t *pdip,
 391     uint16_t *repluns, int lun_cnt, mptsas_target_t *ptgt);
 392 static int mptsas_offline_lun(dev_info_t *pdip, dev_info_t *rdip,


 408     int mode);
 409 
 410 mptsas_target_t *mptsas_tgt_alloc(mptsas_t *, uint16_t, uint64_t,
 411     uint32_t, mptsas_phymask_t, uint8_t);
 412 static mptsas_smp_t *mptsas_smp_alloc(mptsas_t *, mptsas_smp_t *);
 413 static int mptsas_online_smp(dev_info_t *pdip, mptsas_smp_t *smp_node,
 414     dev_info_t **smp_dip);
 415 
 416 /*
 417  * Power management functions
 418  */
 419 static int mptsas_get_pci_cap(mptsas_t *mpt);
 420 static int mptsas_init_pm(mptsas_t *mpt);
 421 
 422 /*
 423  * MPT MSI tunable:
 424  *
 425  * By default MSI is enabled on all supported platforms.
 426  */
 427 boolean_t mptsas_enable_msi = B_TRUE;

 428 boolean_t mptsas_physical_bind_failed_page_83 = B_FALSE;
 429 





 430 static int mptsas_register_intrs(mptsas_t *);
 431 static void mptsas_unregister_intrs(mptsas_t *);
 432 static int mptsas_add_intrs(mptsas_t *, int);
 433 static void mptsas_rem_intrs(mptsas_t *);
 434 
 435 /*
 436  * FMA Prototypes
 437  */
 438 static void mptsas_fm_init(mptsas_t *mpt);
 439 static void mptsas_fm_fini(mptsas_t *mpt);
 440 static int mptsas_fm_error_cb(dev_info_t *, ddi_fm_error_t *, const void *);
 441 
 442 extern pri_t minclsyspri, maxclsyspri;








 443 
 444 /*
 445  * This device is created by the SCSI pseudo nexus driver (SCSI vHCI).  It is
 446  * under this device that the paths to a physical device are created when
 447  * MPxIO is used.
 448  */
 449 extern dev_info_t       *scsi_vhci_dip;
 450 
 451 /*
 452  * Tunable timeout value for Inquiry VPD page 0x83
 453  * By default the value is 30 seconds.
 454  */
 455 int mptsas_inq83_retry_timeout = 30;
 456 
 457 /*







 458  * This is used to allocate memory for message frame storage, not for
 459  * data I/O DMA. All message frames must be stored in the first 4G of
 460  * physical memory.
 461  */
 462 ddi_dma_attr_t mptsas_dma_attrs = {
 463         DMA_ATTR_V0,    /* attribute layout version             */
 464         0x0ull,         /* address low - should be 0 (longlong) */
 465         0xffffffffull,  /* address high - 32-bit max range      */
 466         0x00ffffffull,  /* count max - max DMA object size      */
 467         4,              /* allocation alignment requirements    */
 468         0x78,           /* burstsizes - binary encoded values   */
 469         1,              /* minxfer - gran. of DMA engine        */
 470         0x00ffffffull,  /* maxxfer - gran. of DMA engine        */
 471         0xffffffffull,  /* max segment size (DMA boundary)      */
 472         MPTSAS_MAX_DMA_SEGS, /* scatter/gather list length      */
 473         512,            /* granularity - device transfer size   */
 474         0               /* flags, set to 0                      */
 475 };
 476 
 477 /*
 478  * This is used for data I/O DMA memory allocation. (full 64-bit DMA
 479  * physical addresses are supported.)
 480  */
 481 ddi_dma_attr_t mptsas_dma_attrs64 = {
 482         DMA_ATTR_V0,    /* attribute layout version             */
 483         0x0ull,         /* address low - should be 0 (longlong) */
 484         0xffffffffffffffffull,  /* address high - 64-bit max    */
 485         0x00ffffffull,  /* count max - max DMA object size      */
 486         4,              /* allocation alignment requirements    */
 487         0x78,           /* burstsizes - binary encoded values   */
 488         1,              /* minxfer - gran. of DMA engine        */
 489         0x00ffffffull,  /* maxxfer - gran. of DMA engine        */
 490         0xffffffffull,  /* max segment size (DMA boundary)      */
 491         MPTSAS_MAX_DMA_SEGS, /* scatter/gather list length      */
 492         512,            /* granularity - device transfer size   */
 493         DDI_DMA_RELAXED_ORDERING        /* flags, enable relaxed ordering */
 494 };
 495 
 496 ddi_device_acc_attr_t mptsas_dev_attr = {
 497         DDI_DEVICE_ATTR_V1,
 498         DDI_STRUCTURE_LE_ACC,
 499         DDI_STRICTORDER_ACC,
 500         DDI_DEFAULT_ACC
 501 };
 502 
 503 static struct cb_ops mptsas_cb_ops = {
 504         scsi_hba_open,          /* open */
 505         scsi_hba_close,         /* close */
 506         nodev,                  /* strategy */
 507         nodev,                  /* print */
 508         nodev,                  /* dump */
 509         nodev,                  /* read */
 510         nodev,                  /* write */
 511         mptsas_ioctl,           /* ioctl */
 512         nodev,                  /* devmap */
 513         nodev,                  /* mmap */


 528         nulldev,                /* identify */
 529         nulldev,                /* probe */
 530         mptsas_attach,          /* attach */
 531         mptsas_detach,          /* detach */
 532 #ifdef  __sparc
 533         mptsas_reset,
 534 #else
 535         nodev,                  /* reset */
 536 #endif  /* __sparc */
 537         &mptsas_cb_ops,             /* driver operations */
 538         NULL,                   /* bus operations */
 539         mptsas_power,           /* power management */
 540 #ifdef  __sparc
 541         ddi_quiesce_not_needed
 542 #else
 543         mptsas_quiesce          /* quiesce */
 544 #endif  /* __sparc */
 545 };
 546 
 547 
 548 #define MPTSAS_MOD_STRING "MPTSAS HBA Driver 00.00.00.24"
 549 
 550 static struct modldrv modldrv = {
 551         &mod_driverops,     /* Type of module. This one is a driver */
 552         MPTSAS_MOD_STRING, /* Name of the module. */
 553         &mptsas_ops,        /* driver ops */
 554 };
 555 
 556 static struct modlinkage modlinkage = {
 557         MODREV_1, &modldrv, NULL
 558 };
 559 #define TARGET_PROP     "target"
 560 #define LUN_PROP        "lun"
 561 #define LUN64_PROP      "lun64"
 562 #define SAS_PROP        "sas-mpt"
 563 #define MDI_GUID        "wwn"
 564 #define NDI_GUID        "guid"
 565 #define MPTSAS_DEV_GONE "mptsas_dev_gone"
 566 
 567 /*
 568  * Local static data
 569  */
 570 #if defined(MPTSAS_DEBUG)
 571 uint32_t mptsas_debug_flags = 0;







 572 #endif  /* defined(MPTSAS_DEBUG) */
 573 uint32_t mptsas_debug_resets = 0;
 574 
 575 static kmutex_t         mptsas_global_mutex;
 576 static void             *mptsas_state;          /* soft state ptr */
 577 static krwlock_t        mptsas_global_rwlock;
 578 
 579 static kmutex_t         mptsas_log_mutex;
 580 static char             mptsas_log_buf[256];
 581 _NOTE(MUTEX_PROTECTS_DATA(mptsas_log_mutex, mptsas_log_buf))
 582 
 583 static mptsas_t *mptsas_head, *mptsas_tail;
 584 static clock_t mptsas_scsi_watchdog_tick;
 585 static clock_t mptsas_tick;
 586 static timeout_id_t mptsas_reset_watch;
 587 static timeout_id_t mptsas_timeout_id;
 588 static int mptsas_timeouts_enabled = 0;





























 589 /*
 590  * warlock directives
 591  */
 592 _NOTE(SCHEME_PROTECTS_DATA("unique per pkt", scsi_pkt \
 593         mptsas_cmd NcrTableIndirect buf scsi_cdb scsi_status))
 594 _NOTE(SCHEME_PROTECTS_DATA("unique per pkt", smp_pkt))
 595 _NOTE(SCHEME_PROTECTS_DATA("stable data", scsi_device scsi_address))
 596 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", mptsas_tgt_private))
 597 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", scsi_hba_tran::tran_tgt_private))
 598 
 599 /*
 600  * SM - HBA statics
 601  */
 602 char    *mptsas_driver_rev = MPTSAS_MOD_STRING;
 603 
 604 #ifdef MPTSAS_DEBUG
 605 void debug_enter(char *);
 606 #endif
 607 
 608 /*
 609  * Notes:
 610  *      - scsi_hba_init(9F) initializes SCSI HBA modules
 611  *      - must call scsi_hba_fini(9F) if modload() fails
 612  */
 613 int
 614 _init(void)
 615 {
 616         int status;
 617         /* CONSTCOND */
 618         ASSERT(NO_COMPETING_THREADS);
 619 
 620         NDBG0(("_init"));
 621 
 622         status = ddi_soft_state_init(&mptsas_state, MPTSAS_SIZE,
 623             MPTSAS_INITIAL_SOFT_SPACE);
 624         if (status != 0) {
 625                 return (status);
 626         }
 627 
 628         if ((status = scsi_hba_init(&modlinkage)) != 0) {
 629                 ddi_soft_state_fini(&mptsas_state);
 630                 return (status);
 631         }
 632 
 633         mutex_init(&mptsas_global_mutex, NULL, MUTEX_DRIVER, NULL);
 634         rw_init(&mptsas_global_rwlock, NULL, RW_DRIVER, NULL);
 635         mutex_init(&mptsas_log_mutex, NULL, MUTEX_DRIVER, NULL);
 636 
 637         if ((status = mod_install(&modlinkage)) != 0) {
 638                 mutex_destroy(&mptsas_log_mutex);
 639                 rw_destroy(&mptsas_global_rwlock);
 640                 mutex_destroy(&mptsas_global_mutex);
 641                 ddi_soft_state_fini(&mptsas_state);
 642                 scsi_hba_fini(&modlinkage);
 643         }
 644 
 645         return (status);
 646 }
 647 
 648 /*
 649  * Notes:
 650  *      - scsi_hba_fini(9F) uninitializes SCSI HBA modules
 651  */
 652 int
 653 _fini(void)
 654 {
 655         int     status;
 656         /* CONSTCOND */
 657         ASSERT(NO_COMPETING_THREADS);
 658 
 659         NDBG0(("_fini"));
 660 
 661         if ((status = mod_remove(&modlinkage)) == 0) {
 662                 ddi_soft_state_fini(&mptsas_state);
 663                 scsi_hba_fini(&modlinkage);
 664                 mutex_destroy(&mptsas_global_mutex);
 665                 rw_destroy(&mptsas_global_rwlock);
 666                 mutex_destroy(&mptsas_log_mutex);
 667         }
 668         return (status);
 669 }
 670 
 671 /*
 672  * The loadable-module _info(9E) entry point
 673  */
 674 int
 675 _info(struct modinfo *modinfop)
 676 {
 677         /* CONSTCOND */
 678         ASSERT(NO_COMPETING_THREADS);
 679         NDBG0(("mptsas _info"));
 680 
 681         return (mod_info(&modlinkage, modinfop));
 682 }


 748 static void
 749 mptsas_target_free(void *op)
 750 {
 751         kmem_free(op, sizeof (mptsas_target_t));
 752 }
 753 
 754 static void
 755 mptsas_smp_free(void *op)
 756 {
 757         kmem_free(op, sizeof (mptsas_smp_t));
 758 }
 759 
 760 static void
 761 mptsas_destroy_hashes(mptsas_t *mpt)
 762 {
 763         mptsas_target_t *tp;
 764         mptsas_smp_t *sp;
 765 
 766         for (tp = refhash_first(mpt->m_targets); tp != NULL;
 767             tp = refhash_next(mpt->m_targets, tp)) {

 768                 refhash_remove(mpt->m_targets, tp);
 769         }
 770         for (sp = refhash_first(mpt->m_smp_targets); sp != NULL;
 771             sp = refhash_next(mpt->m_smp_targets, sp)) {
 772                 refhash_remove(mpt->m_smp_targets, sp);
 773         }
 774         refhash_destroy(mpt->m_targets);
 775         refhash_destroy(mpt->m_smp_targets);
 776         mpt->m_targets = NULL;
 777         mpt->m_smp_targets = NULL;
 778 }
 779 
 780 static int
 781 mptsas_iport_attach(dev_info_t *dip, ddi_attach_cmd_t cmd)
 782 {
 783         dev_info_t              *pdip;
 784         mptsas_t                *mpt;
 785         scsi_hba_tran_t         *hba_tran;
 786         char                    *iport = NULL;
 787         char                    phymask[MPTSAS_MAX_PHYS];
 788         mptsas_phymask_t        phy_mask = 0;
 789         int                     dynamic_port = 0;
 790         uint32_t                page_address;
 791         char                    initiator_wwnstr[MPTSAS_WWN_STRLEN];
 792         int                     rval = DDI_FAILURE;
 793         int                     i = 0;
 794         uint8_t                 numphys = 0;
 795         uint8_t                 phy_id;
 796         uint8_t                 phy_port = 0;
 797         uint16_t                attached_devhdl = 0;
 798         uint32_t                dev_info;
 799         uint64_t                attached_sas_wwn;
 800         uint16_t                dev_hdl;
 801         uint16_t                pdev_hdl;
 802         uint16_t                bay_num, enclosure;
 803         char                    attached_wwnstr[MPTSAS_WWN_STRLEN];
 804 
 805         /* CONSTCOND */
 806         ASSERT(NO_COMPETING_THREADS);
 807 
 808         switch (cmd) {
 809         case DDI_ATTACH:
 810                 break;
 811 
 812         case DDI_RESUME:
 813                 /*
 814                  * If this a scsi-iport node, nothing to do here.
 815                  */
 816                 return (DDI_SUCCESS);
 817 
 818         default:
 819                 return (DDI_FAILURE);
 820         }
 821 
 822         pdip = ddi_get_parent(dip);


 944                     "prop update failed");
 945                 return (DDI_FAILURE);
 946         }
 947         if (ddi_prop_update_int(DDI_DEV_T_NONE, dip,
 948             MPTSAS_VIRTUAL_PORT, 0) !=
 949             DDI_PROP_SUCCESS) {
 950                 (void) ddi_prop_remove(DDI_DEV_T_NONE, dip,
 951                     MPTSAS_VIRTUAL_PORT);
 952                 mptsas_log(mpt, CE_WARN, "mptsas virtual port "
 953                     "prop update failed");
 954                 return (DDI_FAILURE);
 955         }
 956         mptsas_smhba_set_all_phy_props(mpt, dip, numphys, phy_mask,
 957             &attached_devhdl);
 958 
 959         mutex_enter(&mpt->m_mutex);
 960         page_address = (MPI2_SAS_DEVICE_PGAD_FORM_HANDLE &
 961             MPI2_SAS_DEVICE_PGAD_FORM_MASK) | (uint32_t)attached_devhdl;
 962         rval = mptsas_get_sas_device_page0(mpt, page_address, &dev_hdl,
 963             &attached_sas_wwn, &dev_info, &phy_port, &phy_id,
 964             &pdev_hdl, &bay_num, &enclosure);
 965         if (rval != DDI_SUCCESS) {
 966                 mptsas_log(mpt, CE_WARN,
 967                     "Failed to get device page0 for handle:%d",
 968                     attached_devhdl);
 969                 mutex_exit(&mpt->m_mutex);
 970                 return (DDI_FAILURE);
 971         }
 972 
 973         for (i = 0; i < MPTSAS_MAX_PHYS; i++) {
 974                 bzero(phymask, sizeof (phymask));
 975                 (void) sprintf(phymask, "%x", mpt->m_phy_info[i].phy_mask);
 976                 if (strcmp(phymask, iport) == 0) {
 977                         (void) sprintf(&mpt->m_phy_info[i].smhba_info.path[0],
 978                             "%x",
 979                             mpt->m_phy_info[i].phy_mask);
 980                 }
 981         }
 982         mutex_exit(&mpt->m_mutex);
 983 
 984         bzero(attached_wwnstr, sizeof (attached_wwnstr));


1001          */
1002         if (mdi_phci_register(MDI_HCI_CLASS_SCSI,
1003             dip, 0) == MDI_SUCCESS) {
1004                 mpt->m_mpxio_enable = TRUE;
1005         }
1006         return (DDI_SUCCESS);
1007 }
1008 
1009 /*
1010  * Notes:
1011  *      Set up all device state and allocate data structures,
1012  *      mutexes, condition variables, etc. for device operation.
1013  *      Add interrupts needed.
1014  *      Return DDI_SUCCESS if device is ready, else return DDI_FAILURE.
1015  */
1016 static int
1017 mptsas_attach(dev_info_t *dip, ddi_attach_cmd_t cmd)
1018 {
1019         mptsas_t                *mpt = NULL;
1020         int                     instance, i, j;
1021         int                     doneq_thread_num;
1022         char                    intr_added = 0;
1023         char                    map_setup = 0;
1024         char                    config_setup = 0;
1025         char                    hba_attach_setup = 0;
1026         char                    smp_attach_setup = 0;
1027         char                    mutex_init_done = 0;
1028         char                    event_taskq_create = 0;
1029         char                    dr_taskq_create = 0;
1030         char                    doneq_thread_create = 0;


1031         scsi_hba_tran_t         *hba_tran;
1032         uint_t                  mem_bar = MEM_SPACE;
1033         int                     rval = DDI_FAILURE;
1034 
1035         /* CONSTCOND */
1036         ASSERT(NO_COMPETING_THREADS);
1037 
1038         if (scsi_hba_iport_unit_address(dip)) {
1039                 return (mptsas_iport_attach(dip, cmd));
1040         }
1041 
1042         switch (cmd) {
1043         case DDI_ATTACH:
1044                 break;
1045 
1046         case DDI_RESUME:
1047                 if ((hba_tran = ddi_get_driver_private(dip)) == NULL)
1048                         return (DDI_FAILURE);
1049 
1050                 mpt = TRAN2MPT(hba_tran);


1125                 }
1126                 mutex_exit(&mptsas_global_mutex);
1127 
1128                 /* report idle status to pm framework */
1129                 if (mpt->m_options & MPTSAS_OPT_PM) {
1130                         (void) pm_idle_component(dip, 0);
1131                 }
1132 
1133                 return (DDI_SUCCESS);
1134 
1135         default:
1136                 return (DDI_FAILURE);
1137 
1138         }
1139 
1140         instance = ddi_get_instance(dip);
1141 
1142         /*
1143          * Allocate softc information.
1144          */
1145         if (ddi_soft_state_zalloc(mptsas_state, instance) != DDI_SUCCESS) {
1146                 mptsas_log(NULL, CE_WARN,
1147                     "mptsas%d: cannot allocate soft state", instance);
1148                 goto fail;
1149         }
1150 
1151         mpt = ddi_get_soft_state(mptsas_state, instance);
1152 
1153         if (mpt == NULL) {
1154                 mptsas_log(NULL, CE_WARN,
1155                     "mptsas%d: cannot get soft state", instance);
1156                 goto fail;
1157         }
1158 
1159         /* Indicate that we are 'sizeof (scsi_*(9S))' clean. */
1160         scsi_size_clean(dip);
1161 
1162         mpt->m_dip = dip;
1163         mpt->m_instance = instance;
1164 
1165         /* Make a per-instance copy of the structures */
1166         mpt->m_io_dma_attr = mptsas_dma_attrs64;



1167         mpt->m_msg_dma_attr = mptsas_dma_attrs;

1168         mpt->m_reg_acc_attr = mptsas_dev_attr;
1169         mpt->m_dev_acc_attr = mptsas_dev_attr;
1170 
1171         /*





1172          * Initialize FMA
1173          */
1174         mpt->m_fm_capabilities = ddi_getprop(DDI_DEV_T_ANY, mpt->m_dip,
1175             DDI_PROP_CANSLEEP | DDI_PROP_DONTPASS, "fm-capable",
1176             DDI_FM_EREPORT_CAPABLE | DDI_FM_ACCCHK_CAPABLE |
1177             DDI_FM_DMACHK_CAPABLE | DDI_FM_ERRCB_CAPABLE);
1178 
1179         mptsas_fm_init(mpt);
1180 
1181         if (mptsas_alloc_handshake_msg(mpt,
1182             sizeof (Mpi2SCSITaskManagementRequest_t)) == DDI_FAILURE) {
1183                 mptsas_log(mpt, CE_WARN, "cannot initialize handshake msg.");
1184                 goto fail;
1185         }
1186 
1187         /*
1188          * Setup configuration space
1189          */
1190         if (mptsas_config_space_init(mpt) == FALSE) {
1191                 mptsas_log(mpt, CE_WARN, "mptsas_config_space_init failed");


1205          */
1206         if ((mpt->m_event_taskq = ddi_taskq_create(dip, "mptsas_event_taskq",
1207             1, TASKQ_DEFAULTPRI, 0)) == NULL) {
1208                 mptsas_log(mpt, CE_NOTE, "ddi_taskq_create failed");
1209                 goto fail;
1210         }
1211         event_taskq_create++;
1212 
1213         /*
1214          * A taskq is created for dealing with dr events
1215          */
1216         if ((mpt->m_dr_taskq = ddi_taskq_create(dip,
1217             "mptsas_dr_taskq",
1218             1, TASKQ_DEFAULTPRI, 0)) == NULL) {
1219                 mptsas_log(mpt, CE_NOTE, "ddi_taskq_create for discovery "
1220                     "failed");
1221                 goto fail;
1222         }
1223         dr_taskq_create++;
1224 
















































1225         mpt->m_doneq_thread_threshold = ddi_prop_get_int(DDI_DEV_T_ANY, dip,
1226             0, "mptsas_doneq_thread_threshold_prop", 10);
1227         mpt->m_doneq_length_threshold = ddi_prop_get_int(DDI_DEV_T_ANY, dip,
1228             0, "mptsas_doneq_length_threshold_prop", 8);
1229         mpt->m_doneq_thread_n = ddi_prop_get_int(DDI_DEV_T_ANY, dip,
1230             0, "mptsas_doneq_thread_n_prop", 8);
1231 
1232         if (mpt->m_doneq_thread_n) {
1233                 cv_init(&mpt->m_doneq_thread_cv, NULL, CV_DRIVER, NULL);
1234                 mutex_init(&mpt->m_doneq_mutex, NULL, MUTEX_DRIVER, NULL);
1235 
1236                 mutex_enter(&mpt->m_doneq_mutex);
1237                 mpt->m_doneq_thread_id =
1238                     kmem_zalloc(sizeof (mptsas_doneq_thread_list_t)
1239                     * mpt->m_doneq_thread_n, KM_SLEEP);
1240 
1241                 for (j = 0; j < mpt->m_doneq_thread_n; j++) {
1242                         cv_init(&mpt->m_doneq_thread_id[j].cv, NULL,
1243                             CV_DRIVER, NULL);
1244                         mutex_init(&mpt->m_doneq_thread_id[j].mutex, NULL,
1245                             MUTEX_DRIVER, NULL);
1246                         mutex_enter(&mpt->m_doneq_thread_id[j].mutex);
1247                         mpt->m_doneq_thread_id[j].flag |=
1248                             MPTSAS_DONEQ_THREAD_ACTIVE;
1249                         mpt->m_doneq_thread_id[j].arg.mpt = mpt;
1250                         mpt->m_doneq_thread_id[j].arg.t = j;
1251                         mpt->m_doneq_thread_id[j].threadp =
1252                             thread_create(NULL, 0, mptsas_doneq_thread,
1253                             &mpt->m_doneq_thread_id[j].arg,
1254                             0, &p0, TS_RUN, minclsyspri);
1255                         mpt->m_doneq_thread_id[j].donetail =
1256                             &mpt->m_doneq_thread_id[j].doneq;
1257                         mutex_exit(&mpt->m_doneq_thread_id[j].mutex);
1258                 }
1259                 mutex_exit(&mpt->m_doneq_mutex);
1260                 doneq_thread_create++;
1261         }
1262 
1263         /* Initialize mutex used in interrupt handler */
1264         mutex_init(&mpt->m_mutex, NULL, MUTEX_DRIVER,
1265             DDI_INTR_PRI(mpt->m_intr_pri));












1266         mutex_init(&mpt->m_passthru_mutex, NULL, MUTEX_DRIVER, NULL);
1267         mutex_init(&mpt->m_tx_waitq_mutex, NULL, MUTEX_DRIVER,
1268             DDI_INTR_PRI(mpt->m_intr_pri));
1269         for (i = 0; i < MPTSAS_MAX_PHYS; i++) {
1270                 mutex_init(&mpt->m_phy_info[i].smhba_info.phy_mutex,
1271                     NULL, MUTEX_DRIVER,
1272                     DDI_INTR_PRI(mpt->m_intr_pri));
1273         }
1274 
1275         cv_init(&mpt->m_cv, NULL, CV_DRIVER, NULL);
1276         cv_init(&mpt->m_passthru_cv, NULL, CV_DRIVER, NULL);
1277         cv_init(&mpt->m_fw_cv, NULL, CV_DRIVER, NULL);
1278         cv_init(&mpt->m_config_cv, NULL, CV_DRIVER, NULL);
1279         cv_init(&mpt->m_fw_diag_cv, NULL, CV_DRIVER, NULL);
1280         mutex_init_done++;
1281 
1282         /*
1283          * Disable hardware interrupt since we're not ready to
1284          * handle it yet.
1285          */
1286         MPTSAS_DISABLE_INTR(mpt);
1287         if (mptsas_register_intrs(mpt) == FALSE)
1288                 goto fail;
1289         intr_added++;
1290 
1291         mutex_enter(&mpt->m_mutex);
1292         /*
1293          * Initialize power management component
1294          */
1295         if (mpt->m_options & MPTSAS_OPT_PM) {
1296                 if (mptsas_init_pm(mpt)) {
1297                         mutex_exit(&mpt->m_mutex);
1298                         mptsas_log(mpt, CE_WARN, "mptsas pm initialization "
1299                             "failed");
1300                         goto fail;
1301                 }
1302         }
1303 
1304         /*
1305          * Initialize chip using Message Unit Reset, if allowed
1306          */
1307         mpt->m_softstate |= MPTSAS_SS_MSG_UNIT_RESET;
1308         if (mptsas_init_chip(mpt, TRUE) == DDI_FAILURE) {
1309                 mutex_exit(&mpt->m_mutex);
1310                 mptsas_log(mpt, CE_WARN, "mptsas chip initialization failed");


1315          * Fill in the phy_info structure and get the base WWID
1316          */
1317         if (mptsas_get_manufacture_page5(mpt) == DDI_FAILURE) {
1318                 mptsas_log(mpt, CE_WARN,
1319                     "mptsas_get_manufacture_page5 failed!");
1320                 goto fail;
1321         }
1322 
1323         if (mptsas_get_sas_io_unit_page_hndshk(mpt)) {
1324                 mptsas_log(mpt, CE_WARN,
1325                     "mptsas_get_sas_io_unit_page_hndshk failed!");
1326                 goto fail;
1327         }
1328 
1329         if (mptsas_get_manufacture_page0(mpt) == DDI_FAILURE) {
1330                 mptsas_log(mpt, CE_WARN,
1331                     "mptsas_get_manufacture_page0 failed!");
1332                 goto fail;
1333         }
1334 













1335         mutex_exit(&mpt->m_mutex);
1336 
1337         /*
1338          * Register the iport for multiple port HBA
1339          */
1340         mptsas_iport_register(mpt);
1341 
1342         /*
1343          * initialize SCSI HBA transport structure
1344          */
1345         if (mptsas_hba_setup(mpt) == FALSE)
1346                 goto fail;
1347         hba_attach_setup++;
1348 
1349         if (mptsas_smp_setup(mpt) == FALSE)
1350                 goto fail;
1351         smp_attach_setup++;
1352 
1353         if (mptsas_cache_create(mpt) == FALSE)
1354                 goto fail;
1355 
1356         mpt->m_scsi_reset_delay      = ddi_prop_get_int(DDI_DEV_T_ANY,
1357             dip, 0, "scsi-reset-delay", SCSI_DEFAULT_RESET_DELAY);
1358         if (mpt->m_scsi_reset_delay == 0) {
1359                 mptsas_log(mpt, CE_NOTE,
1360                     "scsi_reset_delay of 0 is not recommended,"
1361                     " resetting to SCSI_DEFAULT_RESET_DELAY\n");
1362                 mpt->m_scsi_reset_delay = SCSI_DEFAULT_RESET_DELAY;
1363         }
1364 
1365         /*
1366          * Initialize the wait and done FIFO queue
1367          */
1368         mpt->m_donetail = &mpt->m_doneq;
1369         mpt->m_waitqtail = &mpt->m_waitq;
1370         mpt->m_tx_waitqtail = &mpt->m_tx_waitq;
1371         mpt->m_tx_draining = 0;
1372 
1373         /*
1374          * ioc cmd queue initialize
1375          */
1376         mpt->m_ioc_event_cmdtail = &mpt->m_ioc_event_cmdq;
1377         mpt->m_dev_handle = 0xFFFF;
1378 
1379         MPTSAS_ENABLE_INTR(mpt);
1380 
1381         /*
1382          * enable event notification
1383          */
1384         mutex_enter(&mpt->m_mutex);
1385         if (mptsas_ioc_enable_event_notification(mpt)) {
1386                 mutex_exit(&mpt->m_mutex);
1387                 goto fail;
1388         }
1389         mutex_exit(&mpt->m_mutex);
1390 
1391         /*
1392          * Initialize PHY info for smhba





















1393          */
1394         if (mptsas_smhba_setup(mpt)) {
1395                 mptsas_log(mpt, CE_WARN, "mptsas phy initialization "
1396                     "failed");
1397                 goto fail;
1398         }
1399 
1400         /* Check all dma handles allocated in attach */
1401         if ((mptsas_check_dma_handle(mpt->m_dma_req_frame_hdl)
1402             != DDI_SUCCESS) ||


1403             (mptsas_check_dma_handle(mpt->m_dma_reply_frame_hdl)
1404             != DDI_SUCCESS) ||
1405             (mptsas_check_dma_handle(mpt->m_dma_free_queue_hdl)
1406             != DDI_SUCCESS) ||
1407             (mptsas_check_dma_handle(mpt->m_dma_post_queue_hdl)
1408             != DDI_SUCCESS) ||
1409             (mptsas_check_dma_handle(mpt->m_hshk_dma_hdl)
1410             != DDI_SUCCESS)) {
1411                 goto fail;
1412         }
1413 
1414         /* Check all acc handles allocated in attach */
1415         if ((mptsas_check_acc_handle(mpt->m_datap) != DDI_SUCCESS) ||
1416             (mptsas_check_acc_handle(mpt->m_acc_req_frame_hdl)
1417             != DDI_SUCCESS) ||


1418             (mptsas_check_acc_handle(mpt->m_acc_reply_frame_hdl)
1419             != DDI_SUCCESS) ||
1420             (mptsas_check_acc_handle(mpt->m_acc_free_queue_hdl)
1421             != DDI_SUCCESS) ||
1422             (mptsas_check_acc_handle(mpt->m_acc_post_queue_hdl)
1423             != DDI_SUCCESS) ||
1424             (mptsas_check_acc_handle(mpt->m_hshk_acc_hdl)
1425             != DDI_SUCCESS) ||
1426             (mptsas_check_acc_handle(mpt->m_config_handle)
1427             != DDI_SUCCESS)) {
1428                 goto fail;
1429         }
1430 
1431         /*
1432          * After this point, we are not going to fail the attach.
1433          */
1434         /*
1435          * used for mptsas_watch
1436          */
1437         mptsas_list_add(mpt);
1438 
1439         mutex_enter(&mptsas_global_mutex);
1440         if (mptsas_timeouts_enabled == 0) {
1441                 mptsas_scsi_watchdog_tick = ddi_prop_get_int(DDI_DEV_T_ANY,
1442                     dip, 0, "scsi-watchdog-tick", DEFAULT_WD_TICK);
1443 
1444                 mptsas_tick = mptsas_scsi_watchdog_tick *
1445                     drv_usectohz((clock_t)1000000);
1446 
1447                 mptsas_timeout_id = timeout(mptsas_watch, NULL, mptsas_tick);
1448                 mptsas_timeouts_enabled = 1;
1449         }
1450         mutex_exit(&mptsas_global_mutex);
1451 
1452         /* Print message of HBA present */
1453         ddi_report_dev(dip);
1454 
1455         /* report idle status to pm framework */
1456         if (mpt->m_options & MPTSAS_OPT_PM) {
1457                 (void) pm_idle_component(dip, 0);
1458         }
1459 
1460         return (DDI_SUCCESS);
1461 
1462 fail:
1463         mptsas_log(mpt, CE_WARN, "attach failed");
1464         mptsas_fm_ereport(mpt, DDI_FM_DEVICE_NO_RESPONSE);
1465         ddi_fm_service_impact(mpt->m_dip, DDI_SERVICE_LOST);
1466         if (mpt) {



1467                 mutex_enter(&mptsas_global_mutex);
1468 
1469                 if (mptsas_timeout_id && (mptsas_head == NULL)) {
1470                         timeout_id_t tid = mptsas_timeout_id;
1471                         mptsas_timeouts_enabled = 0;
1472                         mptsas_timeout_id = 0;
1473                         mutex_exit(&mptsas_global_mutex);
1474                         (void) untimeout(tid);
1475                         mutex_enter(&mptsas_global_mutex);
1476                 }
1477                 mutex_exit(&mptsas_global_mutex);
1478                 /* deallocate in reverse order */

1479                 mptsas_cache_destroy(mpt);
1480 
1481                 if (smp_attach_setup) {
1482                         mptsas_smp_teardown(mpt);
1483                 }
1484                 if (hba_attach_setup) {
1485                         mptsas_hba_teardown(mpt);
1486                 }
1487 
1488                 if (mpt->m_targets)
1489                         refhash_destroy(mpt->m_targets);
1490                 if (mpt->m_smp_targets)
1491                         refhash_destroy(mpt->m_smp_targets);
1492 
1493                 if (mpt->m_active) {
1494                         mptsas_free_active_slots(mpt);
1495                 }
1496                 if (intr_added) {
1497                         mptsas_unregister_intrs(mpt);
1498                 }
1499 
1500                 if (doneq_thread_create) {
1501                         mutex_enter(&mpt->m_doneq_mutex);
1502                         doneq_thread_num = mpt->m_doneq_thread_n;
1503                         for (j = 0; j < mpt->m_doneq_thread_n; j++) {
1504                                 mutex_enter(&mpt->m_doneq_thread_id[j].mutex);
1505                                 mpt->m_doneq_thread_id[j].flag &=
1506                                     (~MPTSAS_DONEQ_THREAD_ACTIVE);
1507                                 cv_signal(&mpt->m_doneq_thread_id[j].cv);
1508                                 mutex_exit(&mpt->m_doneq_thread_id[j].mutex);
1509                         }
1510                         while (mpt->m_doneq_thread_n) {
1511                                 cv_wait(&mpt->m_doneq_thread_cv,
1512                                     &mpt->m_doneq_mutex);
1513                         }
1514                         for (j = 0; j < doneq_thread_num; j++) {
1515                                 cv_destroy(&mpt->m_doneq_thread_id[j].cv);
1516                                 mutex_destroy(&mpt->m_doneq_thread_id[j].mutex);
1517                         }
1518                         kmem_free(mpt->m_doneq_thread_id,
1519                             sizeof (mptsas_doneq_thread_list_t)
1520                             * doneq_thread_num);
1521                         mutex_exit(&mpt->m_doneq_mutex);
1522                         cv_destroy(&mpt->m_doneq_thread_cv);
1523                         mutex_destroy(&mpt->m_doneq_mutex);

















1524                 }
1525                 if (event_taskq_create) {
1526                         ddi_taskq_destroy(mpt->m_event_taskq);
1527                 }
1528                 if (dr_taskq_create) {
1529                         ddi_taskq_destroy(mpt->m_dr_taskq);
1530                 }
1531                 if (mutex_init_done) {
1532                         mutex_destroy(&mpt->m_tx_waitq_mutex);
1533                         mutex_destroy(&mpt->m_passthru_mutex);
1534                         mutex_destroy(&mpt->m_mutex);
1535                         for (i = 0; i < MPTSAS_MAX_PHYS; i++) {
1536                                 mutex_destroy(
1537                                     &mpt->m_phy_info[i].smhba_info.phy_mutex);
1538                         }

1539                         cv_destroy(&mpt->m_cv);
1540                         cv_destroy(&mpt->m_passthru_cv);
1541                         cv_destroy(&mpt->m_fw_cv);
1542                         cv_destroy(&mpt->m_config_cv);
1543                         cv_destroy(&mpt->m_fw_diag_cv);
1544                 }
1545 
1546                 if (map_setup) {
1547                         mptsas_cfg_fini(mpt);
1548                 }
1549                 if (config_setup) {
1550                         mptsas_config_space_fini(mpt);
1551                 }
1552                 mptsas_free_handshake_msg(mpt);
1553                 mptsas_hba_fini(mpt);
1554 
1555                 mptsas_fm_fini(mpt);
1556                 ddi_soft_state_free(mptsas_state, instance);
1557                 ddi_prop_remove_all(dip);
1558         }
1559         return (DDI_FAILURE);
1560 }
1561 
1562 static int
1563 mptsas_suspend(dev_info_t *devi)
1564 {
1565         mptsas_t        *mpt, *g;
1566         scsi_hba_tran_t *tran;
1567 
1568         if (scsi_hba_iport_unit_address(devi)) {
1569                 return (DDI_SUCCESS);
1570         }
1571 
1572         if ((tran = ddi_get_driver_private(devi)) == NULL)
1573                 return (DDI_SUCCESS);
1574 
1575         mpt = TRAN2MPT(tran);
1576         if (!mpt) {


1750                 return (mptsas_do_detach(devi));
1751 
1752         case DDI_SUSPEND:
1753                 return (mptsas_suspend(devi));
1754 
1755         default:
1756                 return (DDI_FAILURE);
1757         }
1758         /* NOTREACHED */
1759 }
1760 
1761 static int
1762 mptsas_do_detach(dev_info_t *dip)
1763 {
1764         mptsas_t        *mpt;
1765         scsi_hba_tran_t *tran;
1766         int             circ = 0;
1767         int             circ1 = 0;
1768         mdi_pathinfo_t  *pip = NULL;
1769         int             i;
1770         int             doneq_thread_num = 0;
1771 
1772         NDBG0(("mptsas_do_detach: dip=0x%p", (void *)dip));
1773 
1774         if ((tran = ndi_flavorv_get(dip, SCSA_FLAVOR_SCSI_DEVICE)) == NULL)
1775                 return (DDI_FAILURE);
1776 
1777         mpt = TRAN2MPT(tran);
1778         if (!mpt) {
1779                 return (DDI_FAILURE);
1780         }
1781         /*
1782          * Still have pathinfo child, should not detach mpt driver
1783          */
1784         if (scsi_hba_iport_unit_address(dip)) {
1785                 if (mpt->m_mpxio_enable) {
1786                         /*
1787                          * MPxIO enabled for the iport
1788                          */
1789                         ndi_devi_enter(scsi_vhci_dip, &circ1);
1790                         ndi_devi_enter(dip, &circ);


1798                                     "outstanding path info"));
1799                                 return (DDI_FAILURE);
1800                         }
1801                         ndi_devi_exit(dip, circ);
1802                         ndi_devi_exit(scsi_vhci_dip, circ1);
1803                         (void) mdi_phci_unregister(dip, 0);
1804                 }
1805 
1806                 ddi_prop_remove_all(dip);
1807 
1808                 return (DDI_SUCCESS);
1809         }
1810 
1811         /* Make sure power level is D0 before accessing registers */
1812         if (mpt->m_options & MPTSAS_OPT_PM) {
1813                 (void) pm_busy_component(dip, 0);
1814                 if (mpt->m_power_level != PM_LEVEL_D0) {
1815                         if (pm_raise_power(dip, 0, PM_LEVEL_D0) !=
1816                             DDI_SUCCESS) {
1817                                 mptsas_log(mpt, CE_WARN,
1818                                     "mptsas%d: Raise power request failed.",
1819                                     mpt->m_instance);
1820                                 (void) pm_idle_component(dip, 0);
1821                                 return (DDI_FAILURE);
1822                         }
1823                 }
1824         }
1825 
1826         /*
1827          * Send RAID action system shutdown to sync IR.  After action, send a
1828          * Message Unit Reset. Since after that DMA resource will be freed,
1829          * set ioc to READY state will avoid HBA initiated DMA operation.
1830          */
1831         mutex_enter(&mpt->m_mutex);
1832         MPTSAS_DISABLE_INTR(mpt);
1833         mptsas_raid_action_system_shutdown(mpt);
1834         mpt->m_softstate |= MPTSAS_SS_MSG_UNIT_RESET;
1835         (void) mptsas_ioc_reset(mpt, FALSE);
1836         mutex_exit(&mpt->m_mutex);
1837         mptsas_rem_intrs(mpt);
1838         ddi_taskq_destroy(mpt->m_event_taskq);
1839         ddi_taskq_destroy(mpt->m_dr_taskq);
1840 
1841         if (mpt->m_doneq_thread_n) {
1842                 mutex_enter(&mpt->m_doneq_mutex);
1843                 doneq_thread_num = mpt->m_doneq_thread_n;
1844                 for (i = 0; i < mpt->m_doneq_thread_n; i++) {
1845                         mutex_enter(&mpt->m_doneq_thread_id[i].mutex);
1846                         mpt->m_doneq_thread_id[i].flag &=
1847                             (~MPTSAS_DONEQ_THREAD_ACTIVE);
1848                         cv_signal(&mpt->m_doneq_thread_id[i].cv);
1849                         mutex_exit(&mpt->m_doneq_thread_id[i].mutex);
1850                 }
1851                 while (mpt->m_doneq_thread_n) {
1852                         cv_wait(&mpt->m_doneq_thread_cv,
1853                             &mpt->m_doneq_mutex);
1854                 }
1855                 for (i = 0;  i < doneq_thread_num; i++) {
1856                         cv_destroy(&mpt->m_doneq_thread_id[i].cv);
1857                         mutex_destroy(&mpt->m_doneq_thread_id[i].mutex);
1858                 }
1859                 kmem_free(mpt->m_doneq_thread_id,
1860                     sizeof (mptsas_doneq_thread_list_t)
1861                     * doneq_thread_num);
1862                 mutex_exit(&mpt->m_doneq_mutex);
1863                 cv_destroy(&mpt->m_doneq_thread_cv);
1864                 mutex_destroy(&mpt->m_doneq_mutex);

















1865         }
1866 
1867         scsi_hba_reset_notify_tear_down(mpt->m_reset_notify_listf);
1868 
1869         mptsas_list_del(mpt);
1870 
1871         /*
1872          * Cancel timeout threads for this mpt
1873          */
1874         mutex_enter(&mpt->m_mutex);
1875         if (mpt->m_quiesce_timeid) {
1876                 timeout_id_t tid = mpt->m_quiesce_timeid;
1877                 mpt->m_quiesce_timeid = 0;
1878                 mutex_exit(&mpt->m_mutex);
1879                 (void) untimeout(tid);
1880                 mutex_enter(&mpt->m_mutex);
1881         }
1882 
1883         if (mpt->m_restart_cmd_timeid) {
1884                 timeout_id_t tid = mpt->m_restart_cmd_timeid;


1925 
1926         mptsas_destroy_hashes(mpt);
1927 
1928         /*
1929          * Delete nt_active.
1930          */
1931         mutex_enter(&mpt->m_mutex);
1932         mptsas_free_active_slots(mpt);
1933         mutex_exit(&mpt->m_mutex);
1934 
1935         /* deallocate everything that was allocated in mptsas_attach */
1936         mptsas_cache_destroy(mpt);
1937 
1938         mptsas_hba_fini(mpt);
1939         mptsas_cfg_fini(mpt);
1940 
1941         /* Lower the power informing PM Framework */
1942         if (mpt->m_options & MPTSAS_OPT_PM) {
1943                 if (pm_lower_power(dip, 0, PM_LEVEL_D3) != DDI_SUCCESS)
1944                         mptsas_log(mpt, CE_WARN,
1945                             "!mptsas%d: Lower power request failed "
1946                             "during detach, ignoring.",
1947                             mpt->m_instance);
1948         }
1949 
1950         mutex_destroy(&mpt->m_tx_waitq_mutex);
1951         mutex_destroy(&mpt->m_passthru_mutex);
1952         mutex_destroy(&mpt->m_mutex);
1953         for (i = 0; i < MPTSAS_MAX_PHYS; i++) {
1954                 mutex_destroy(&mpt->m_phy_info[i].smhba_info.phy_mutex);
1955         }

1956         cv_destroy(&mpt->m_cv);
1957         cv_destroy(&mpt->m_passthru_cv);
1958         cv_destroy(&mpt->m_fw_cv);
1959         cv_destroy(&mpt->m_config_cv);
1960         cv_destroy(&mpt->m_fw_diag_cv);
1961 
1962 
1963         mptsas_smp_teardown(mpt);
1964         mptsas_hba_teardown(mpt);
1965 
1966         mptsas_config_space_fini(mpt);
1967 
1968         mptsas_free_handshake_msg(mpt);
1969 
1970         mptsas_fm_fini(mpt);
1971         ddi_soft_state_free(mptsas_state, ddi_get_instance(dip));
1972         ddi_prop_remove_all(dip);
1973 
1974         return (DDI_SUCCESS);
1975 }
1976 
1977 static void
1978 mptsas_list_add(mptsas_t *mpt)
1979 {
1980         rw_enter(&mptsas_global_rwlock, RW_WRITER);
1981 
1982         if (mptsas_head == NULL) {
1983                 mptsas_head = mpt;
1984         } else {
1985                 mptsas_tail->m_next = mpt;
1986         }
1987         mptsas_tail = mpt;
1988         rw_exit(&mptsas_global_rwlock);
1989 }
1990 
1991 static void


2004                                 m->m_next = mpt->m_next;
2005                                 break;
2006                         }
2007                 }
2008                 if (m == NULL) {
2009                         mptsas_log(mpt, CE_PANIC, "Not in softc list!");
2010                 }
2011         }
2012 
2013         if (mptsas_tail == mpt) {
2014                 mptsas_tail = m;
2015         }
2016         rw_exit(&mptsas_global_rwlock);
2017 }
2018 
2019 static int
2020 mptsas_alloc_handshake_msg(mptsas_t *mpt, size_t alloc_size)
2021 {
2022         ddi_dma_attr_t  task_dma_attrs;
2023 

2024         task_dma_attrs = mpt->m_msg_dma_attr;
2025         task_dma_attrs.dma_attr_sgllen = 1;
2026         task_dma_attrs.dma_attr_granular = (uint32_t)(alloc_size);
2027 
2028         /* allocate Task Management ddi_dma resources */
2029         if (mptsas_dma_addr_create(mpt, task_dma_attrs,
2030             &mpt->m_hshk_dma_hdl, &mpt->m_hshk_acc_hdl, &mpt->m_hshk_memp,
2031             alloc_size, NULL) == FALSE) {
2032                 return (DDI_FAILURE);
2033         }
2034         mpt->m_hshk_dma_size = alloc_size;
2035 
2036         return (DDI_SUCCESS);
2037 }
2038 
2039 static void
2040 mptsas_free_handshake_msg(mptsas_t *mpt)
2041 {


2042         mptsas_dma_addr_destroy(&mpt->m_hshk_dma_hdl, &mpt->m_hshk_acc_hdl);
2043         mpt->m_hshk_dma_size = 0;
2044 }
2045 
2046 static int
2047 mptsas_hba_setup(mptsas_t *mpt)
2048 {
2049         scsi_hba_tran_t         *hba_tran;
2050         int                     tran_flags;
2051 
2052         /* Allocate a transport structure */
2053         hba_tran = mpt->m_tran = scsi_hba_tran_alloc(mpt->m_dip,
2054             SCSI_HBA_CANSLEEP);
2055         ASSERT(mpt->m_tran != NULL);
2056 
2057         hba_tran->tran_hba_private   = mpt;
2058         hba_tran->tran_tgt_private   = NULL;
2059 
2060         hba_tran->tran_tgt_init              = mptsas_scsi_tgt_init;
2061         hba_tran->tran_tgt_free              = mptsas_scsi_tgt_free;


2199 static void
2200 mptsas_smp_teardown(mptsas_t *mpt)
2201 {
2202         (void) smp_hba_detach(mpt->m_dip);
2203         if (mpt->m_smptran != NULL) {
2204                 smp_hba_tran_free(mpt->m_smptran);
2205                 mpt->m_smptran = NULL;
2206         }
2207         mpt->m_smp_devhdl = 0;
2208 }
2209 
2210 static int
2211 mptsas_cache_create(mptsas_t *mpt)
2212 {
2213         int instance = mpt->m_instance;
2214         char buf[64];
2215 
2216         /*
2217          * create kmem cache for packets
2218          */
2219         (void) sprintf(buf, "mptsas%d_cache", instance);
2220         mpt->m_kmem_cache = kmem_cache_create(buf,
2221             sizeof (struct mptsas_cmd) + scsi_pkt_size(), 8,
2222             mptsas_kmem_cache_constructor, mptsas_kmem_cache_destructor,
2223             NULL, (void *)mpt, NULL, 0);
2224 
2225         if (mpt->m_kmem_cache == NULL) {
2226                 mptsas_log(mpt, CE_WARN, "creating kmem cache failed");
2227                 return (FALSE);
2228         }
2229 
2230         /*
2231          * create kmem cache for extra SGL frames if SGL cannot
2232          * be accomodated into main request frame.
2233          */
2234         (void) sprintf(buf, "mptsas%d_cache_frames", instance);
2235         mpt->m_cache_frames = kmem_cache_create(buf,
2236             sizeof (mptsas_cache_frames_t), 8,
2237             mptsas_cache_frames_constructor, mptsas_cache_frames_destructor,
2238             NULL, (void *)mpt, NULL, 0);
2239 
2240         if (mpt->m_cache_frames == NULL) {
2241                 mptsas_log(mpt, CE_WARN, "creating cache for frames failed");
2242                 return (FALSE);
2243         }
2244 
2245         return (TRUE);
2246 }
2247 
2248 static void
2249 mptsas_cache_destroy(mptsas_t *mpt)
2250 {
2251         /* deallocate in reverse order */
2252         if (mpt->m_cache_frames) {
2253                 kmem_cache_destroy(mpt->m_cache_frames);
2254                 mpt->m_cache_frames = NULL;
2255         }
2256         if (mpt->m_kmem_cache) {
2257                 kmem_cache_destroy(mpt->m_kmem_cache);
2258                 mpt->m_kmem_cache = NULL;
2259         }
2260 }
2261 
2262 static int
2263 mptsas_power(dev_info_t *dip, int component, int level)
2264 {
2265 #ifndef __lock_lint
2266         _NOTE(ARGUNUSED(component))
2267 #endif
2268         mptsas_t        *mpt;
2269         int             rval = DDI_SUCCESS;
2270         int             polls = 0;
2271         uint32_t        ioc_status;
2272 
2273         if (scsi_hba_iport_unit_address(dip) != 0)
2274                 return (DDI_SUCCESS);
2275 
2276         mpt = ddi_get_soft_state(mptsas_state, ddi_get_instance(dip));
2277         if (mpt == NULL) {
2278                 return (DDI_FAILURE);
2279         }
2280 
2281         mutex_enter(&mpt->m_mutex);
2282 
2283         /*
2284          * If the device is busy, don't lower its power level
2285          */
2286         if (mpt->m_busy && (mpt->m_power_level > level)) {
2287                 mutex_exit(&mpt->m_mutex);
2288                 return (DDI_FAILURE);
2289         }
2290         switch (level) {
2291         case PM_LEVEL_D0:
2292                 NDBG11(("mptsas%d: turning power ON.", mpt->m_instance));
2293                 MPTSAS_POWER_ON(mpt);
2294                 /*
2295                  * Wait up to 30 seconds for IOC to come out of reset.
2296                  */
2297                 while (((ioc_status = ddi_get32(mpt->m_datap,
2298                     &mpt->m_reg->Doorbell)) &
2299                     MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_RESET) {
2300                         if (polls++ > 3000) {
2301                                 break;
2302                         }
2303                         delay(drv_usectohz(10000));
2304                 }
2305                 /*
2306                  * If IOC is not in operational state, try to hard reset it.
2307                  */
2308                 if ((ioc_status & MPI2_IOC_STATE_MASK) !=
2309                     MPI2_IOC_STATE_OPERATIONAL) {
2310                         mpt->m_softstate &= ~MPTSAS_SS_MSG_UNIT_RESET;
2311                         if (mptsas_restart_ioc(mpt) == DDI_FAILURE) {
2312                                 mptsas_log(mpt, CE_WARN,
2313                                     "mptsas_power: hard reset failed");
2314                                 mutex_exit(&mpt->m_mutex);
2315                                 return (DDI_FAILURE);
2316                         }
2317                 }
2318                 mpt->m_power_level = PM_LEVEL_D0;
2319                 break;
2320         case PM_LEVEL_D3:
2321                 NDBG11(("mptsas%d: turning power OFF.", mpt->m_instance));
2322                 MPTSAS_POWER_OFF(mpt);
2323                 break;
2324         default:
2325                 mptsas_log(mpt, CE_WARN, "mptsas%d: unknown power level <%x>.",
2326                     mpt->m_instance, level);
2327                 rval = DDI_FAILURE;
2328                 break;
2329         }
2330         mutex_exit(&mpt->m_mutex);
2331         return (rval);
2332 }
2333 
2334 /*
2335  * Initialize configuration space and figure out which
2336  * chip and revison of the chip the mpt driver is using.
2337  */
2338 static int
2339 mptsas_config_space_init(mptsas_t *mpt)
2340 {
2341         NDBG0(("mptsas_config_space_init"));
2342 
2343         if (mpt->m_config_handle != NULL)
2344                 return (TRUE);
2345 


2483                 ddi_fm_service_impact(mpt->m_dip, DDI_SERVICE_UNAFFECTED);
2484                 rval = DDI_FAILURE;
2485         }
2486 
2487         mptsas_dma_addr_destroy(&dma_handle, &accessp);
2488         return (rval);
2489 
2490 }
2491 
2492 static int
2493 mptsas_alloc_request_frames(mptsas_t *mpt)
2494 {
2495         ddi_dma_attr_t          frame_dma_attrs;
2496         caddr_t                 memp;
2497         ddi_dma_cookie_t        cookie;
2498         size_t                  mem_size;
2499 
2500         /*
2501          * re-alloc when it has already alloced
2502          */

2503         mptsas_dma_addr_destroy(&mpt->m_dma_req_frame_hdl,
2504             &mpt->m_acc_req_frame_hdl);


2505 
2506         /*
2507          * The size of the request frame pool is:
2508          *   Number of Request Frames * Request Frame Size
2509          */
2510         mem_size = mpt->m_max_requests * mpt->m_req_frame_size;
2511 
2512         /*
2513          * set the DMA attributes.  System Request Message Frames must be
2514          * aligned on a 16-byte boundry.
2515          */
2516         frame_dma_attrs = mpt->m_msg_dma_attr;
2517         frame_dma_attrs.dma_attr_align = 16;
2518         frame_dma_attrs.dma_attr_sgllen = 1;
2519 
2520         /*
2521          * allocate the request frame pool.
2522          */
2523         if (mptsas_dma_addr_create(mpt, frame_dma_attrs,
2524             &mpt->m_dma_req_frame_hdl, &mpt->m_acc_req_frame_hdl, &memp,
2525             mem_size, &cookie) == FALSE) {
2526                 return (DDI_FAILURE);
2527         }
2528 
2529         /*
2530          * Store the request frame memory address.  This chip uses this
2531          * address to dma to and from the driver's frame.  The second
2532          * address is the address mpt uses to fill in the frame.
2533          */
2534         mpt->m_req_frame_dma_addr = cookie.dmac_laddress;
2535         mpt->m_req_frame = memp;
2536 
2537         /*
2538          * Clear the request frame pool.
2539          */
2540         bzero(mpt->m_req_frame, mem_size);
2541 











































































2542         return (DDI_SUCCESS);
2543 }
2544 
2545 static int
2546 mptsas_alloc_reply_frames(mptsas_t *mpt)
2547 {
2548         ddi_dma_attr_t          frame_dma_attrs;
2549         caddr_t                 memp;
2550         ddi_dma_cookie_t        cookie;
2551         size_t                  mem_size;
2552 
2553         /*
2554          * re-alloc when it has already alloced
2555          */

2556         mptsas_dma_addr_destroy(&mpt->m_dma_reply_frame_hdl,
2557             &mpt->m_acc_reply_frame_hdl);


2558 
2559         /*
2560          * The size of the reply frame pool is:
2561          *   Number of Reply Frames * Reply Frame Size
2562          */
2563         mem_size = mpt->m_max_replies * mpt->m_reply_frame_size;
2564 
2565         /*
2566          * set the DMA attributes.   System Reply Message Frames must be
2567          * aligned on a 4-byte boundry.  This is the default.
2568          */
2569         frame_dma_attrs = mpt->m_msg_dma_attr;
2570         frame_dma_attrs.dma_attr_sgllen = 1;
2571 
2572         /*
2573          * allocate the reply frame pool
2574          */
2575         if (mptsas_dma_addr_create(mpt, frame_dma_attrs,
2576             &mpt->m_dma_reply_frame_hdl, &mpt->m_acc_reply_frame_hdl, &memp,
2577             mem_size, &cookie) == FALSE) {
2578                 return (DDI_FAILURE);
2579         }
2580 
2581         /*
2582          * Store the reply frame memory address.  This chip uses this
2583          * address to dma to and from the driver's frame.  The second
2584          * address is the address mpt uses to process the frame.
2585          */
2586         mpt->m_reply_frame_dma_addr = cookie.dmac_laddress;
2587         mpt->m_reply_frame = memp;
2588 
2589         /*
2590          * Clear the reply frame pool.
2591          */
2592         bzero(mpt->m_reply_frame, mem_size);
2593 

2594         return (DDI_SUCCESS);
2595 }
2596 
2597 static int
2598 mptsas_alloc_free_queue(mptsas_t *mpt)
2599 {
2600         ddi_dma_attr_t          frame_dma_attrs;
2601         caddr_t                 memp;
2602         ddi_dma_cookie_t        cookie;
2603         size_t                  mem_size;
2604 
2605         /*
2606          * re-alloc when it has already alloced
2607          */

2608         mptsas_dma_addr_destroy(&mpt->m_dma_free_queue_hdl,
2609             &mpt->m_acc_free_queue_hdl);


2610 
2611         /*
2612          * The reply free queue size is:
2613          *   Reply Free Queue Depth * 4
2614          * The "4" is the size of one 32 bit address (low part of 64-bit
2615          *   address)
2616          */
2617         mem_size = mpt->m_free_queue_depth * 4;
2618 
2619         /*
2620          * set the DMA attributes  The Reply Free Queue must be aligned on a
2621          * 16-byte boundry.
2622          */
2623         frame_dma_attrs = mpt->m_msg_dma_attr;
2624         frame_dma_attrs.dma_attr_align = 16;
2625         frame_dma_attrs.dma_attr_sgllen = 1;
2626 
2627         /*
2628          * allocate the reply free queue
2629          */
2630         if (mptsas_dma_addr_create(mpt, frame_dma_attrs,
2631             &mpt->m_dma_free_queue_hdl, &mpt->m_acc_free_queue_hdl, &memp,
2632             mem_size, &cookie) == FALSE) {
2633                 return (DDI_FAILURE);
2634         }
2635 
2636         /*
2637          * Store the reply free queue memory address.  This chip uses this
2638          * address to read from the reply free queue.  The second address
2639          * is the address mpt uses to manage the queue.
2640          */
2641         mpt->m_free_queue_dma_addr = cookie.dmac_laddress;
2642         mpt->m_free_queue = memp;
2643 
2644         /*
2645          * Clear the reply free queue memory.
2646          */
2647         bzero(mpt->m_free_queue, mem_size);
2648 

2649         return (DDI_SUCCESS);
2650 }
2651 





















2652 static int
2653 mptsas_alloc_post_queue(mptsas_t *mpt)
2654 {
2655         ddi_dma_attr_t          frame_dma_attrs;
2656         caddr_t                 memp;
2657         ddi_dma_cookie_t        cookie;
2658         size_t                  mem_size;


2659 
2660         /*
2661          * re-alloc when it has already alloced
2662          */
2663         mptsas_dma_addr_destroy(&mpt->m_dma_post_queue_hdl,
2664             &mpt->m_acc_post_queue_hdl);
2665 
2666         /*
2667          * The reply descriptor post queue size is:
2668          *   Reply Descriptor Post Queue Depth * 8
2669          * The "8" is the size of each descriptor (8 bytes or 64 bits).
2670          */
2671         mem_size = mpt->m_post_queue_depth * 8;

2672 
2673         /*
2674          * set the DMA attributes.  The Reply Descriptor Post Queue must be
2675          * aligned on a 16-byte boundry.
2676          */
2677         frame_dma_attrs = mpt->m_msg_dma_attr;
2678         frame_dma_attrs.dma_attr_align = 16;
2679         frame_dma_attrs.dma_attr_sgllen = 1;
2680 
2681         /*
2682          * allocate the reply post queue





2683          */
2684         if (mptsas_dma_addr_create(mpt, frame_dma_attrs,
2685             &mpt->m_dma_post_queue_hdl, &mpt->m_acc_post_queue_hdl, &memp,
2686             mem_size, &cookie) == FALSE) {
2687                 return (DDI_FAILURE);
2688         }
2689 
2690         /*
2691          * Store the reply descriptor post queue memory address.  This chip
2692          * uses this address to write to the reply descriptor post queue.  The
2693          * second address is the address mpt uses to manage the queue.
2694          */
2695         mpt->m_post_queue_dma_addr = cookie.dmac_laddress;
2696         mpt->m_post_queue = memp;
2697 












2698         /*
2699          * Clear the reply post queue memory.
2700          */
2701         bzero(mpt->m_post_queue, mem_size);
2702 

2703         return (DDI_SUCCESS);
2704 }
2705 
2706 static void
2707 mptsas_alloc_reply_args(mptsas_t *mpt)
2708 {
2709         if (mpt->m_replyh_args == NULL) {
2710                 mpt->m_replyh_args = kmem_zalloc(sizeof (m_replyh_arg_t) *
2711                     mpt->m_max_replies, KM_SLEEP);



2712         }
2713 }
2714 
2715 static int
2716 mptsas_alloc_extra_sgl_frame(mptsas_t *mpt, mptsas_cmd_t *cmd)
2717 {
2718         mptsas_cache_frames_t   *frames = NULL;
2719         if (cmd->cmd_extra_frames == NULL) {
2720                 frames = kmem_cache_alloc(mpt->m_cache_frames, KM_NOSLEEP);
2721                 if (frames == NULL) {
2722                         return (DDI_FAILURE);
2723                 }
2724                 cmd->cmd_extra_frames = frames;
2725         }
2726         return (DDI_SUCCESS);
2727 }
2728 
2729 static void
2730 mptsas_free_extra_sgl_frame(mptsas_t *mpt, mptsas_cmd_t *cmd)
2731 {


2734                     (void *)cmd->cmd_extra_frames);
2735                 cmd->cmd_extra_frames = NULL;
2736         }
2737 }
2738 
2739 static void
2740 mptsas_cfg_fini(mptsas_t *mpt)
2741 {
2742         NDBG0(("mptsas_cfg_fini"));
2743         ddi_regs_map_free(&mpt->m_datap);
2744 }
2745 
2746 static void
2747 mptsas_hba_fini(mptsas_t *mpt)
2748 {
2749         NDBG0(("mptsas_hba_fini"));
2750 
2751         /*
2752          * Free up any allocated memory
2753          */

2754         mptsas_dma_addr_destroy(&mpt->m_dma_req_frame_hdl,
2755             &mpt->m_acc_req_frame_hdl);







2756 

2757         mptsas_dma_addr_destroy(&mpt->m_dma_reply_frame_hdl,
2758             &mpt->m_acc_reply_frame_hdl);

2759 

2760         mptsas_dma_addr_destroy(&mpt->m_dma_free_queue_hdl,
2761             &mpt->m_acc_free_queue_hdl);

2762 
2763         mptsas_dma_addr_destroy(&mpt->m_dma_post_queue_hdl,
2764             &mpt->m_acc_post_queue_hdl);
2765 
2766         if (mpt->m_replyh_args != NULL) {
2767                 kmem_free(mpt->m_replyh_args, sizeof (m_replyh_arg_t)
2768                     * mpt->m_max_replies);
2769         }
2770 }
2771 
2772 static int
2773 mptsas_name_child(dev_info_t *lun_dip, char *name, int len)
2774 {
2775         int             lun = 0;
2776         char            *sas_wwn = NULL;
2777         int             phynum = -1;
2778         int             reallen = 0;
2779 
2780         /* Get the target num */
2781         lun = ddi_prop_get_int(DDI_DEV_T_ANY, lun_dip, DDI_PROP_DONTPASS,
2782             LUN_PROP, 0);
2783 
2784         if ((phynum = ddi_prop_get_int(DDI_DEV_T_ANY, lun_dip,


3023  * scsi_pkt handling
3024  *
3025  * Visible to the external world via the transport structure.
3026  */
3027 
3028 /*
3029  * Notes:
3030  *      - transport the command to the addressed SCSI target/lun device
3031  *      - normal operation is to schedule the command to be transported,
3032  *        and return TRAN_ACCEPT if this is successful.
3033  *      - if NO_INTR, tran_start must poll device for command completion
3034  */
3035 static int
3036 mptsas_scsi_start(struct scsi_address *ap, struct scsi_pkt *pkt)
3037 {
3038 #ifndef __lock_lint
3039         _NOTE(ARGUNUSED(ap))
3040 #endif
3041         mptsas_t        *mpt = PKT2MPT(pkt);
3042         mptsas_cmd_t    *cmd = PKT2CMD(pkt);
3043         int             rval;

3044         mptsas_target_t *ptgt = cmd->cmd_tgt_addr;

3045 
3046         NDBG1(("mptsas_scsi_start: pkt=0x%p", (void *)pkt));
3047         ASSERT(ptgt);
3048         if (ptgt == NULL)
3049                 return (TRAN_FATAL_ERROR);
3050 
3051         /*
3052          * prepare the pkt before taking mutex.
3053          */
3054         rval = mptsas_prepare_pkt(cmd);
3055         if (rval != TRAN_ACCEPT) {
3056                 return (rval);
3057         }
3058 
3059         /*
3060          * Send the command to target/lun, however your HBA requires it.
3061          * If busy, return TRAN_BUSY; if there's some other formatting error
3062          * in the packet, return TRAN_BADPKT; otherwise, fall through to the
3063          * return of TRAN_ACCEPT.
3064          *


3073          * interrupt handler can refer to the pkt to set completion
3074          * status, call the target driver back through pkt_comp, etc.
3075          *
3076          * If the instance lock is held by other thread, don't spin to wait
3077          * for it. Instead, queue the cmd and next time when the instance lock
3078          * is not held, accept all the queued cmd. A extra tx_waitq is
3079          * introduced to protect the queue.
3080          *
3081          * The polled cmd will not be queud and accepted as usual.
3082          *
3083          * Under the tx_waitq mutex, record whether a thread is draining
3084          * the tx_waitq.  An IO requesting thread that finds the instance
3085          * mutex contended appends to the tx_waitq and while holding the
3086          * tx_wait mutex, if the draining flag is not set, sets it and then
3087          * proceeds to spin for the instance mutex. This scheme ensures that
3088          * the last cmd in a burst be processed.
3089          *
3090          * we enable this feature only when the helper threads are enabled,
3091          * at which we think the loads are heavy.
3092          *
3093          * per instance mutex m_tx_waitq_mutex is introduced to protect the
3094          * m_tx_waitqtail, m_tx_waitq, m_tx_draining.
3095          */
3096 
3097         if (mpt->m_doneq_thread_n) {
3098                 if (mutex_tryenter(&mpt->m_mutex) != 0) {
3099                         rval = mptsas_accept_txwq_and_pkt(mpt, cmd);
3100                         mutex_exit(&mpt->m_mutex);
3101                 } else if (cmd->cmd_pkt_flags & FLAG_NOINTR) {




3102                         mutex_enter(&mpt->m_mutex);
3103                         rval = mptsas_accept_txwq_and_pkt(mpt, cmd);
3104                         mutex_exit(&mpt->m_mutex);
3105                 } else {
3106                         mutex_enter(&mpt->m_tx_waitq_mutex);
3107                         /*
3108                          * ptgt->m_dr_flag is protected by m_mutex or
3109                          * m_tx_waitq_mutex. In this case, m_tx_waitq_mutex
3110                          * is acquired.
3111                          */
3112                         if (ptgt->m_dr_flag == MPTSAS_DR_INTRANSITION) {
3113                                 if (cmd->cmd_pkt_flags & FLAG_NOQUEUE) {
3114                                         /*
3115                                          * The command should be allowed to
3116                                          * retry by returning TRAN_BUSY to
3117                                          * to stall the I/O's which come from
3118                                          * scsi_vhci since the device/path is
3119                                          * in unstable state now.
3120                                          */
3121                                         mutex_exit(&mpt->m_tx_waitq_mutex);
3122                                         return (TRAN_BUSY);
3123                                 } else {
3124                                         /*
3125                                          * The device is offline, just fail the
3126                                          * command by returning
3127                                          * TRAN_FATAL_ERROR.
3128                                          */
3129                                         mutex_exit(&mpt->m_tx_waitq_mutex);
3130                                         return (TRAN_FATAL_ERROR);
3131                                 }






3132                         }
3133                         if (mpt->m_tx_draining) {
3134                                 cmd->cmd_flags |= CFLAG_TXQ;
3135                                 *mpt->m_tx_waitqtail = cmd;
3136                                 mpt->m_tx_waitqtail = &cmd->cmd_linkp;
3137                                 mutex_exit(&mpt->m_tx_waitq_mutex);
3138                         } else { /* drain the queue */
3139                                 mpt->m_tx_draining = 1;
3140                                 mutex_exit(&mpt->m_tx_waitq_mutex);
3141                                 mutex_enter(&mpt->m_mutex);
3142                                 rval = mptsas_accept_txwq_and_pkt(mpt, cmd);
3143                                 mutex_exit(&mpt->m_mutex);
3144                         }
3145                 }
3146         } else {
3147                 mutex_enter(&mpt->m_mutex);
3148                 /*
3149                  * ptgt->m_dr_flag is protected by m_mutex or m_tx_waitq_mutex
3150                  * in this case, m_mutex is acquired.
3151                  */
3152                 if (ptgt->m_dr_flag == MPTSAS_DR_INTRANSITION) {
3153                         if (cmd->cmd_pkt_flags & FLAG_NOQUEUE) {
3154                                 /*
3155                                  * commands should be allowed to retry by
3156                                  * returning TRAN_BUSY to stall the I/O's
3157                                  * which come from scsi_vhci since the device/
3158                                  * path is in unstable state now.
3159                                  */
3160                                 mutex_exit(&mpt->m_mutex);
3161                                 return (TRAN_BUSY);
3162                         } else {
3163                                 /*
3164                                  * The device is offline, just fail the
3165                                  * command by returning TRAN_FATAL_ERROR.
3166                                  */
3167                                 mutex_exit(&mpt->m_mutex);
3168                                 return (TRAN_FATAL_ERROR);
3169                         }





3170                 }
3171                 rval = mptsas_accept_pkt(mpt, cmd);

3172                 mutex_exit(&mpt->m_mutex);


3173         }
3174 
3175         return (rval);
3176 }
3177 
3178 /*
3179  * Accept all the queued cmds(if any) before accept the current one.
3180  */
3181 static int
3182 mptsas_accept_txwq_and_pkt(mptsas_t *mpt, mptsas_cmd_t *cmd)
3183 {
3184         int rval;
3185         mptsas_target_t *ptgt = cmd->cmd_tgt_addr;
3186 
3187         ASSERT(mutex_owned(&mpt->m_mutex));
3188         /*
3189          * The call to mptsas_accept_tx_waitq() must always be performed
3190          * because that is where mpt->m_tx_draining is cleared.
3191          */
3192         mutex_enter(&mpt->m_tx_waitq_mutex);
3193         mptsas_accept_tx_waitq(mpt);
3194         mutex_exit(&mpt->m_tx_waitq_mutex);
3195         /*
3196          * ptgt->m_dr_flag is protected by m_mutex or m_tx_waitq_mutex
3197          * in this case, m_mutex is acquired.
3198          */

3199         if (ptgt->m_dr_flag == MPTSAS_DR_INTRANSITION) {
3200                 if (cmd->cmd_pkt_flags & FLAG_NOQUEUE) {
3201                         /*
3202                          * The command should be allowed to retry by returning
3203                          * TRAN_BUSY to stall the I/O's which come from
3204                          * scsi_vhci since the device/path is in unstable state
3205                          * now.
3206                          */
3207                         return (TRAN_BUSY);
3208                 } else {
3209                         /*
3210                          * The device is offline, just fail the command by
3211                          * return TRAN_FATAL_ERROR.
3212                          */
3213                         return (TRAN_FATAL_ERROR);
3214                 }
3215         }
3216         rval = mptsas_accept_pkt(mpt, cmd);

3217 
3218         return (rval);




























3219 }
3220 






3221 static int
3222 mptsas_accept_pkt(mptsas_t *mpt, mptsas_cmd_t *cmd)
3223 {
3224         int             rval = TRAN_ACCEPT;
3225         mptsas_target_t *ptgt = cmd->cmd_tgt_addr;
3226 
3227         NDBG1(("mptsas_accept_pkt: cmd=0x%p", (void *)cmd));
3228 
3229         ASSERT(mutex_owned(&mpt->m_mutex));
3230 
3231         if ((cmd->cmd_flags & CFLAG_PREPARED) == 0) {
3232                 rval = mptsas_prepare_pkt(cmd);
3233                 if (rval != TRAN_ACCEPT) {
3234                         cmd->cmd_flags &= ~CFLAG_TRANFLAG;
3235                         return (rval);
3236                 }
3237         }
3238 
3239         /*
3240          * reset the throttle if we were draining


3241          */
3242         if ((ptgt->m_t_ncmds == 0) &&
3243             (ptgt->m_t_throttle == DRAIN_THROTTLE)) {
3244                 NDBG23(("reset throttle"));
3245                 ASSERT(ptgt->m_reset_delay == 0);
3246                 mptsas_set_throttle(mpt, ptgt, MAX_THROTTLE);





3247         }
3248 
3249         /*
3250          * If HBA is being reset, the DevHandles are being re-initialized,
3251          * which means that they could be invalid even if the target is still
3252          * attached.  Check if being reset and if DevHandle is being
3253          * re-initialized.  If this is the case, return BUSY so the I/O can be
3254          * retried later.
3255          */
3256         if ((ptgt->m_devhdl == MPTSAS_INVALID_DEVHDL) && mpt->m_in_reset) {
3257                 mptsas_set_pkt_reason(mpt, cmd, CMD_RESET, STAT_BUS_RESET);
3258                 if (cmd->cmd_flags & CFLAG_TXQ) {
3259                         mptsas_doneq_add(mpt, cmd);
3260                         mptsas_doneq_empty(mpt);
3261                         return (rval);
3262                 } else {
3263                         return (TRAN_BUSY);
3264                 }












3265         }
3266 
3267         /*
3268          * If device handle has already been invalidated, just
3269          * fail the command. In theory, command from scsi_vhci
3270          * client is impossible send down command with invalid
3271          * devhdl since devhdl is set after path offline, target
3272          * driver is not suppose to select a offlined path.
3273          */
3274         if (ptgt->m_devhdl == MPTSAS_INVALID_DEVHDL) {
3275                 NDBG20(("rejecting command, it might because invalid devhdl "
3276                     "request."));

3277                 mptsas_set_pkt_reason(mpt, cmd, CMD_DEV_GONE, STAT_TERMINATED);
3278                 if (cmd->cmd_flags & CFLAG_TXQ) {
3279                         mptsas_doneq_add(mpt, cmd);
3280                         mptsas_doneq_empty(mpt);
3281                         return (rval);
3282                 } else {
3283                         return (TRAN_FATAL_ERROR);
3284                 }

3285         }
3286         /*
3287          * The first case is the normal case.  mpt gets a command from the
3288          * target driver and starts it.
3289          * Since SMID 0 is reserved and the TM slot is reserved, the actual max
3290          * commands is m_max_requests - 2.
3291          */
3292         if ((mpt->m_ncmds <= (mpt->m_max_requests - 2)) &&
3293             (ptgt->m_t_throttle > HOLD_THROTTLE) &&
3294             (ptgt->m_t_ncmds < ptgt->m_t_throttle) &&
3295             (ptgt->m_reset_delay == 0) &&
3296             (ptgt->m_t_nwait == 0) &&
3297             ((cmd->cmd_pkt_flags & FLAG_NOINTR) == 0)) {
3298                 if (mptsas_save_cmd(mpt, cmd) == TRUE) {
3299                         (void) mptsas_start_cmd(mpt, cmd);





3300                 } else {

3301                         mptsas_waitq_add(mpt, cmd);
3302                 }
3303         } else {

3304                 /*
3305                  * Add this pkt to the work queue
3306                  */
3307                 mptsas_waitq_add(mpt, cmd);
3308 
3309                 if (cmd->cmd_pkt_flags & FLAG_NOINTR) {
3310                         (void) mptsas_poll(mpt, cmd, MPTSAS_POLL_TIME);
3311 
3312                         /*
3313                          * Only flush the doneq if this is not a TM
3314                          * cmd.  For TM cmds the flushing of the
3315                          * doneq will be done in those routines.
3316                          */
3317                         if ((cmd->cmd_flags & CFLAG_TM_CMD) == 0) {
3318                                 mptsas_doneq_empty(mpt);
3319                         }
3320                 }
3321         }
3322         return (rval);


3323 }
3324 
3325 int
3326 mptsas_save_cmd(mptsas_t *mpt, mptsas_cmd_t *cmd)
3327 {
3328         mptsas_slots_t *slots = mpt->m_active;
3329         uint_t slot, start_rotor;
3330         mptsas_target_t *ptgt = cmd->cmd_tgt_addr;
3331 
3332         ASSERT(MUTEX_HELD(&mpt->m_mutex));



















3333 
3334         /*
3335          * Account for reserved TM request slot and reserved SMID of 0.
3336          */
3337         ASSERT(slots->m_n_normal == (mpt->m_max_requests - 2));
3338 
3339         /*
3340          * Find the next available slot, beginning at m_rotor.  If no slot is
3341          * available, we'll return FALSE to indicate that.  This mechanism
3342          * considers only the normal slots, not the reserved slot 0 nor the
3343          * task management slot m_n_normal + 1.  The rotor is left to point to
3344          * the normal slot after the one we select, unless we select the last
3345          * normal slot in which case it returns to slot 1.
3346          */
3347         start_rotor = slots->m_rotor;

3348         do {
3349                 slot = slots->m_rotor++;
3350                 if (slots->m_rotor > slots->m_n_normal)
3351                         slots->m_rotor = 1;
3352 
3353                 if (slots->m_rotor == start_rotor)
3354                         break;
3355         } while (slots->m_slot[slot] != NULL);

3356 
3357         if (slots->m_slot[slot] != NULL)
3358                 return (FALSE);
3359 
3360         ASSERT(slot != 0 && slot <= slots->m_n_normal);
3361 
3362         cmd->cmd_slot = slot;
3363         slots->m_slot[slot] = cmd;
3364         mpt->m_ncmds++;
























3365 
3366         /*
3367          * only increment per target ncmds if this is not a
3368          * command that has no target associated with it (i.e. a
3369          * event acknoledgment)
3370          */
3371         if ((cmd->cmd_flags & CFLAG_CMDIOC) == 0) {




3372                 ptgt->m_t_ncmds++;
3373         }
3374         cmd->cmd_active_timeout = cmd->cmd_pkt->pkt_time;
3375 
3376         /*
3377          * If initial timout is less than or equal to one tick, bump
3378          * the timeout by a tick so that command doesn't timeout before
3379          * its allotted time.
3380          */
3381         if (cmd->cmd_active_timeout <= mptsas_scsi_watchdog_tick) {
3382                 cmd->cmd_active_timeout += mptsas_scsi_watchdog_tick;
3383         }
3384         return (TRUE);
3385 }
3386 
3387 /*
3388  * prepare the pkt:
3389  * the pkt may have been resubmitted or just reused so
3390  * initialize some fields and do some checks.
3391  */
3392 static int
3393 mptsas_prepare_pkt(mptsas_cmd_t *cmd)
3394 {
3395         struct scsi_pkt *pkt = CMD2PKT(cmd);
3396 
3397         NDBG1(("mptsas_prepare_pkt: cmd=0x%p", (void *)cmd));
3398 
3399         /*
3400          * Reinitialize some fields that need it; the packet may
3401          * have been resubmitted
3402          */


3467         ASSERT(ptgt != NULL);
3468         if (ptgt == NULL)
3469                 return (NULL);
3470         ap->a_target = ptgt->m_devhdl;
3471         ap->a_lun = tgt_private->t_lun;
3472 
3473         ASSERT(callback == NULL_FUNC || callback == SLEEP_FUNC);
3474 #ifdef MPTSAS_TEST_EXTRN_ALLOC
3475         statuslen *= 100; tgtlen *= 4;
3476 #endif
3477         NDBG3(("mptsas_scsi_init_pkt:\n"
3478             "\ttgt=%d in=0x%p bp=0x%p clen=%d slen=%d tlen=%d flags=%x",
3479             ap->a_target, (void *)pkt, (void *)bp,
3480             cmdlen, statuslen, tgtlen, flags));
3481 
3482         /*
3483          * Allocate the new packet.
3484          */
3485         if (pkt == NULL) {
3486                 ddi_dma_handle_t        save_dma_handle;
3487                 ddi_dma_handle_t        save_arq_dma_handle;
3488                 struct buf              *save_arq_bp;
3489                 ddi_dma_cookie_t        save_arqcookie;
3490 
3491                 cmd = kmem_cache_alloc(mpt->m_kmem_cache, kf);
3492 
3493                 if (cmd) {
3494                         save_dma_handle = cmd->cmd_dmahandle;
3495                         save_arq_dma_handle = cmd->cmd_arqhandle;
3496                         save_arq_bp = cmd->cmd_arq_buf;
3497                         save_arqcookie = cmd->cmd_arqcookie;
3498                         bzero(cmd, sizeof (*cmd) + scsi_pkt_size());
3499                         cmd->cmd_dmahandle = save_dma_handle;
3500                         cmd->cmd_arqhandle = save_arq_dma_handle;
3501                         cmd->cmd_arq_buf = save_arq_bp;
3502                         cmd->cmd_arqcookie = save_arqcookie;
3503 
3504                         pkt = (void *)((uchar_t *)cmd +
3505                             sizeof (struct mptsas_cmd));
3506                         pkt->pkt_ha_private = (opaque_t)cmd;
3507                         pkt->pkt_address = *ap;
3508                         pkt->pkt_private = (opaque_t)cmd->cmd_pkt_private;
3509                         pkt->pkt_scbp = (opaque_t)&cmd->cmd_scb;
3510                         pkt->pkt_cdbp = (opaque_t)&cmd->cmd_cdb;
3511                         cmd->cmd_pkt = (struct scsi_pkt *)pkt;
3512                         cmd->cmd_cdblen = (uchar_t)cmdlen;
3513                         cmd->cmd_scblen = statuslen;
3514                         cmd->cmd_rqslen = SENSE_LENGTH;
3515                         cmd->cmd_tgt_addr = ptgt;
3516                         failure = 0;
3517                 }
3518 
3519                 if (failure || (cmdlen > sizeof (cmd->cmd_cdb)) ||
3520                     (tgtlen > PKT_PRIV_LEN) ||
3521                     (statuslen > EXTCMDS_STATUS_SIZE)) {
3522                         if (failure == 0) {


3762 
3763                         cmd->cmd_dmacount += cmd->cmd_cookie.dmac_size;
3764                         cmd->cmd_totaldmacount += cmd->cmd_cookie.dmac_size;
3765 
3766                         /*
3767                          * store the segment parms into the S/G list
3768                          */
3769                         dmap->count = cmd->cmd_cookie.dmac_size;
3770                         dmap->addr.address64.Low = (uint32_t)
3771                             (cmd->cmd_cookie.dmac_laddress & 0xffffffffull);
3772                         dmap->addr.address64.High = (uint32_t)
3773                             (cmd->cmd_cookie.dmac_laddress >> 32);
3774                 }
3775 
3776                 /*
3777                  * If this was partially allocated we set the resid
3778                  * the amount of data NOT transferred in this window
3779                  * If there is only one window, the resid will be 0
3780                  */
3781                 pkt->pkt_resid = (bp->b_bcount - cmd->cmd_totaldmacount);
3782                 NDBG16(("mptsas_dmaget: cmd_dmacount=%d.", cmd->cmd_dmacount));

3783         }
3784         return (pkt);
3785 }
3786 
3787 /*
3788  * tran_destroy_pkt(9E) - scsi_pkt(9s) deallocation
3789  *
3790  * Notes:
3791  *      - also frees DMA resources if allocated
3792  *      - implicit DMA synchonization
3793  */
3794 static void
3795 mptsas_scsi_destroy_pkt(struct scsi_address *ap, struct scsi_pkt *pkt)
3796 {
3797         mptsas_cmd_t    *cmd = PKT2CMD(pkt);
3798         mptsas_t        *mpt = ADDR2MPT(ap);
3799 
3800         NDBG3(("mptsas_scsi_destroy_pkt: target=%d pkt=0x%p",
3801             ap->a_target, (void *)pkt));
3802 


3815         if ((cmd->cmd_flags &
3816             (CFLAG_FREE | CFLAG_CDBEXTERN | CFLAG_PRIVEXTERN |
3817             CFLAG_SCBEXTERN)) == 0) {
3818                 cmd->cmd_flags = CFLAG_FREE;
3819                 kmem_cache_free(mpt->m_kmem_cache, (void *)cmd);
3820         } else {
3821                 mptsas_pkt_destroy_extern(mpt, cmd);
3822         }
3823 }
3824 
3825 /*
3826  * kmem cache constructor and destructor:
3827  * When constructing, we bzero the cmd and allocate the dma handle
3828  * When destructing, just free the dma handle
3829  */
3830 static int
3831 mptsas_kmem_cache_constructor(void *buf, void *cdrarg, int kmflags)
3832 {
3833         mptsas_cmd_t            *cmd = buf;
3834         mptsas_t                *mpt  = cdrarg;
3835         struct scsi_address     ap;
3836         uint_t                  cookiec;
3837         ddi_dma_attr_t          arq_dma_attr;
3838         int                     (*callback)(caddr_t);
3839 
3840         callback = (kmflags == KM_SLEEP)? DDI_DMA_SLEEP: DDI_DMA_DONTWAIT;
3841 
3842         NDBG4(("mptsas_kmem_cache_constructor"));
3843 
3844         ap.a_hba_tran = mpt->m_tran;
3845         ap.a_target = 0;
3846         ap.a_lun = 0;
3847 
3848         /*
3849          * allocate a dma handle
3850          */
3851         if ((ddi_dma_alloc_handle(mpt->m_dip, &mpt->m_io_dma_attr, callback,
3852             NULL, &cmd->cmd_dmahandle)) != DDI_SUCCESS) {
3853                 cmd->cmd_dmahandle = NULL;
3854                 return (-1);
3855         }
3856 
3857         cmd->cmd_arq_buf = scsi_alloc_consistent_buf(&ap, (struct buf *)NULL,
3858             SENSE_LENGTH, B_READ, callback, NULL);
3859         if (cmd->cmd_arq_buf == NULL) {
3860                 ddi_dma_free_handle(&cmd->cmd_dmahandle);
3861                 cmd->cmd_dmahandle = NULL;
3862                 return (-1);
3863         }
3864 
3865         /*
3866          * allocate a arq handle
3867          */
3868         arq_dma_attr = mpt->m_msg_dma_attr;
3869         arq_dma_attr.dma_attr_sgllen = 1;
3870         if ((ddi_dma_alloc_handle(mpt->m_dip, &arq_dma_attr, callback,
3871             NULL, &cmd->cmd_arqhandle)) != DDI_SUCCESS) {
3872                 ddi_dma_free_handle(&cmd->cmd_dmahandle);
3873                 scsi_free_consistent_buf(cmd->cmd_arq_buf);
3874                 cmd->cmd_dmahandle = NULL;
3875                 cmd->cmd_arqhandle = NULL;
3876                 return (-1);
3877         }
3878 
3879         if (ddi_dma_buf_bind_handle(cmd->cmd_arqhandle,
3880             cmd->cmd_arq_buf, (DDI_DMA_READ | DDI_DMA_CONSISTENT),
3881             callback, NULL, &cmd->cmd_arqcookie, &cookiec) != DDI_SUCCESS) {
3882                 ddi_dma_free_handle(&cmd->cmd_dmahandle);
3883                 ddi_dma_free_handle(&cmd->cmd_arqhandle);
3884                 scsi_free_consistent_buf(cmd->cmd_arq_buf);
3885                 cmd->cmd_dmahandle = NULL;
3886                 cmd->cmd_arqhandle = NULL;
3887                 cmd->cmd_arq_buf = NULL;
3888                 return (-1);
3889         }
3890 
3891         return (0);
3892 }
3893 
3894 static void
3895 mptsas_kmem_cache_destructor(void *buf, void *cdrarg)
3896 {
3897 #ifndef __lock_lint
3898         _NOTE(ARGUNUSED(cdrarg))
3899 #endif
3900         mptsas_cmd_t    *cmd = buf;
3901 
3902         NDBG4(("mptsas_kmem_cache_destructor"));
3903 
3904         if (cmd->cmd_arqhandle) {
3905                 (void) ddi_dma_unbind_handle(cmd->cmd_arqhandle);
3906                 ddi_dma_free_handle(&cmd->cmd_arqhandle);
3907                 cmd->cmd_arqhandle = NULL;
3908         }
3909         if (cmd->cmd_arq_buf) {
3910                 scsi_free_consistent_buf(cmd->cmd_arq_buf);
3911                 cmd->cmd_arq_buf = NULL;
3912         }
3913         if (cmd->cmd_dmahandle) {
3914                 ddi_dma_free_handle(&cmd->cmd_dmahandle);
3915                 cmd->cmd_dmahandle = NULL;
3916         }
3917 }
3918 
3919 static int
3920 mptsas_cache_frames_constructor(void *buf, void *cdrarg, int kmflags)
3921 {
3922         mptsas_cache_frames_t   *p = buf;
3923         mptsas_t                *mpt = cdrarg;
3924         ddi_dma_attr_t          frame_dma_attr;
3925         size_t                  mem_size, alloc_len;
3926         ddi_dma_cookie_t        cookie;
3927         uint_t                  ncookie;
3928         int (*callback)(caddr_t) = (kmflags == KM_SLEEP)
3929             ? DDI_DMA_SLEEP: DDI_DMA_DONTWAIT;
3930 
3931         frame_dma_attr = mpt->m_msg_dma_attr;
3932         frame_dma_attr.dma_attr_align = 0x10;


3950                     " extra SGL.");
3951                 return (DDI_FAILURE);
3952         }
3953 
3954         if (ddi_dma_addr_bind_handle(p->m_dma_hdl, NULL, p->m_frames_addr,
3955             alloc_len, DDI_DMA_RDWR | DDI_DMA_CONSISTENT, callback, NULL,
3956             &cookie, &ncookie) != DDI_DMA_MAPPED) {
3957                 (void) ddi_dma_mem_free(&p->m_acc_hdl);
3958                 ddi_dma_free_handle(&p->m_dma_hdl);
3959                 p->m_dma_hdl = NULL;
3960                 mptsas_log(mpt, CE_WARN, "Unable to bind DMA resources for"
3961                     " extra SGL");
3962                 return (DDI_FAILURE);
3963         }
3964 
3965         /*
3966          * Store the SGL memory address.  This chip uses this
3967          * address to dma to and from the driver.  The second
3968          * address is the address mpt uses to fill in the SGL.
3969          */
3970         p->m_phys_addr = cookie.dmac_address;
3971 
3972         return (DDI_SUCCESS);
3973 }
3974 
3975 static void
3976 mptsas_cache_frames_destructor(void *buf, void *cdrarg)
3977 {
3978 #ifndef __lock_lint
3979         _NOTE(ARGUNUSED(cdrarg))
3980 #endif
3981         mptsas_cache_frames_t   *p = buf;
3982         if (p->m_dma_hdl != NULL) {
3983                 (void) ddi_dma_unbind_handle(p->m_dma_hdl);
3984                 (void) ddi_dma_mem_free(&p->m_acc_hdl);
3985                 ddi_dma_free_handle(&p->m_dma_hdl);
3986                 p->m_phys_addr = NULL;
3987                 p->m_frames_addr = NULL;
3988                 p->m_dma_hdl = NULL;
3989                 p->m_acc_hdl = NULL;
3990         }
3991 
3992 }
3993 
3994 /*
3995  * allocate and deallocate external pkt space (ie. not part of mptsas_cmd)
3996  * for non-standard length cdb, pkt_private, status areas
3997  * if allocation fails, then deallocate all external space and the pkt
3998  */
3999 /* ARGSUSED */
4000 static int
4001 mptsas_pkt_alloc_extern(mptsas_t *mpt, mptsas_cmd_t *cmd,
4002     int cmdlen, int tgtlen, int statuslen, int kf)
4003 {
4004         caddr_t                 cdbp, scbp, tgt;
4005         int                     (*callback)(caddr_t) = (kf == KM_SLEEP) ?
4006             DDI_DMA_SLEEP : DDI_DMA_DONTWAIT;
4007         struct scsi_address     ap;
4008         size_t                  senselength;
4009         ddi_dma_attr_t          ext_arq_dma_attr;
4010         uint_t                  cookiec;
4011 
4012         NDBG3(("mptsas_pkt_alloc_extern: "
4013             "cmd=0x%p cmdlen=%d tgtlen=%d statuslen=%d kf=%x",
4014             (void *)cmd, cmdlen, tgtlen, statuslen, kf));
4015 
4016         tgt = cdbp = scbp = NULL;
4017         cmd->cmd_scblen              = statuslen;
4018         cmd->cmd_privlen     = (uchar_t)tgtlen;
4019 
4020         if (cmdlen > sizeof (cmd->cmd_cdb)) {
4021                 if ((cdbp = kmem_zalloc((size_t)cmdlen, kf)) == NULL) {
4022                         goto fail;
4023                 }
4024                 cmd->cmd_pkt->pkt_cdbp = (opaque_t)cdbp;
4025                 cmd->cmd_flags |= CFLAG_CDBEXTERN;
4026         }
4027         if (tgtlen > PKT_PRIV_LEN) {
4028                 if ((tgt = kmem_zalloc((size_t)tgtlen, kf)) == NULL) {
4029                         goto fail;
4030                 }
4031                 cmd->cmd_flags |= CFLAG_PRIVEXTERN;
4032                 cmd->cmd_pkt->pkt_private = tgt;
4033         }
4034         if (statuslen > EXTCMDS_STATUS_SIZE) {
4035                 if ((scbp = kmem_zalloc((size_t)statuslen, kf)) == NULL) {
4036                         goto fail;
4037                 }
4038                 cmd->cmd_flags |= CFLAG_SCBEXTERN;
4039                 cmd->cmd_pkt->pkt_scbp = (opaque_t)scbp;
4040 
4041                 /* allocate sense data buf for DMA */
4042 
4043                 senselength = statuslen - MPTSAS_GET_ITEM_OFF(
4044                     struct scsi_arq_status, sts_sensedata);












4045                 cmd->cmd_rqslen = (uchar_t)senselength;
4046 
4047                 ap.a_hba_tran = mpt->m_tran;
4048                 ap.a_target = 0;
4049                 ap.a_lun = 0;
4050 
4051                 cmd->cmd_ext_arq_buf = scsi_alloc_consistent_buf(&ap,
4052                     (struct buf *)NULL, senselength, B_READ,
4053                     callback, NULL);
4054 
4055                 if (cmd->cmd_ext_arq_buf == NULL) {
4056                         goto fail;
4057                 }
4058                 /*
4059                  * allocate a extern arq handle and bind the buf
4060                  */
4061                 ext_arq_dma_attr = mpt->m_msg_dma_attr;
4062                 ext_arq_dma_attr.dma_attr_sgllen = 1;
4063                 if ((ddi_dma_alloc_handle(mpt->m_dip,
4064                     &ext_arq_dma_attr, callback,
4065                     NULL, &cmd->cmd_ext_arqhandle)) != DDI_SUCCESS) {
4066                         goto fail;
4067                 }
4068 
4069                 if (ddi_dma_buf_bind_handle(cmd->cmd_ext_arqhandle,
4070                     cmd->cmd_ext_arq_buf, (DDI_DMA_READ | DDI_DMA_CONSISTENT),
4071                     callback, NULL, &cmd->cmd_ext_arqcookie,
4072                     &cookiec)
4073                     != DDI_SUCCESS) {
4074                         goto fail;
4075                 }
4076                 cmd->cmd_flags |= CFLAG_EXTARQBUFVALID;
4077         }
4078         return (0);
4079 fail:
4080         mptsas_pkt_destroy_extern(mpt, cmd);
4081         return (1);
4082 }
4083 
4084 /*
4085  * deallocate external pkt space and deallocate the pkt
4086  */
4087 static void
4088 mptsas_pkt_destroy_extern(mptsas_t *mpt, mptsas_cmd_t *cmd)
4089 {
4090         NDBG3(("mptsas_pkt_destroy_extern: cmd=0x%p", (void *)cmd));
4091 
4092         if (cmd->cmd_flags & CFLAG_FREE) {
4093                 mptsas_log(mpt, CE_PANIC,
4094                     "mptsas_pkt_destroy_extern: freeing free packet");
4095                 _NOTE(NOT_REACHED)
4096                 /* NOTREACHED */
4097         }




4098         if (cmd->cmd_flags & CFLAG_CDBEXTERN) {
4099                 kmem_free(cmd->cmd_pkt->pkt_cdbp, (size_t)cmd->cmd_cdblen);
4100         }
4101         if (cmd->cmd_flags & CFLAG_SCBEXTERN) {
4102                 kmem_free(cmd->cmd_pkt->pkt_scbp, (size_t)cmd->cmd_scblen);
4103                 if (cmd->cmd_flags & CFLAG_EXTARQBUFVALID) {
4104                         (void) ddi_dma_unbind_handle(cmd->cmd_ext_arqhandle);
4105                 }
4106                 if (cmd->cmd_ext_arqhandle) {
4107                         ddi_dma_free_handle(&cmd->cmd_ext_arqhandle);
4108                         cmd->cmd_ext_arqhandle = NULL;
4109                 }
4110                 if (cmd->cmd_ext_arq_buf)
4111                         scsi_free_consistent_buf(cmd->cmd_ext_arq_buf);
4112         }
4113         if (cmd->cmd_flags & CFLAG_PRIVEXTERN) {
4114                 kmem_free(cmd->cmd_pkt->pkt_private, (size_t)cmd->cmd_privlen);
4115         }
4116         cmd->cmd_flags = CFLAG_FREE;
4117         kmem_cache_free(mpt->m_kmem_cache, (void *)cmd);
4118 }
4119 
4120 /*
4121  * tran_sync_pkt(9E) - explicit DMA synchronization
4122  */
4123 /*ARGSUSED*/
4124 static void
4125 mptsas_scsi_sync_pkt(struct scsi_address *ap, struct scsi_pkt *pkt)
4126 {
4127         mptsas_cmd_t    *cmd = PKT2CMD(pkt);
4128 
4129         NDBG3(("mptsas_scsi_sync_pkt: target=%d, pkt=0x%p",
4130             ap->a_target, (void *)pkt));
4131 


4137 }
4138 
4139 /*
4140  * tran_dmafree(9E) - deallocate DMA resources allocated for command
4141  */
4142 /*ARGSUSED*/
4143 static void
4144 mptsas_scsi_dmafree(struct scsi_address *ap, struct scsi_pkt *pkt)
4145 {
4146         mptsas_cmd_t    *cmd = PKT2CMD(pkt);
4147         mptsas_t        *mpt = ADDR2MPT(ap);
4148 
4149         NDBG3(("mptsas_scsi_dmafree: target=%d pkt=0x%p",
4150             ap->a_target, (void *)pkt));
4151 
4152         if (cmd->cmd_flags & CFLAG_DMAVALID) {
4153                 (void) ddi_dma_unbind_handle(cmd->cmd_dmahandle);
4154                 cmd->cmd_flags &= ~CFLAG_DMAVALID;
4155         }
4156 
4157         if (cmd->cmd_flags & CFLAG_EXTARQBUFVALID) {
4158                 (void) ddi_dma_unbind_handle(cmd->cmd_ext_arqhandle);
4159                 cmd->cmd_flags &= ~CFLAG_EXTARQBUFVALID;
4160         }
4161 
4162         mptsas_free_extra_sgl_frame(mpt, cmd);
4163 }
4164 
4165 static void
4166 mptsas_pkt_comp(struct scsi_pkt *pkt, mptsas_cmd_t *cmd)
4167 {
4168         if ((cmd->cmd_flags & CFLAG_CMDIOPB) &&
4169             (!(cmd->cmd_flags & CFLAG_DMASEND))) {
4170                 (void) ddi_dma_sync(cmd->cmd_dmahandle, 0, 0,
4171                     DDI_DMA_SYNC_FORCPU);
4172         }
4173         (*pkt->pkt_comp)(pkt);
4174 }
4175 
4176 static void
4177 mptsas_sge_setup(mptsas_t *mpt, mptsas_cmd_t *cmd, uint32_t *control,
4178         pMpi2SCSIIORequest_t frame, ddi_acc_handle_t acc_hdl)

4179 {
4180         uint_t                  cookiec;
4181         mptti_t                 *dmap;
4182         uint32_t                flags;
4183         pMpi2SGESimple64_t      sge;
4184         pMpi2SGEChain64_t       sgechain;
4185         ASSERT(cmd->cmd_flags & CFLAG_DMAVALID);
4186 
4187         /*
4188          * Save the number of entries in the DMA
4189          * Scatter/Gather list
4190          */
4191         cookiec = cmd->cmd_cookiec;
4192 
4193         NDBG1(("mptsas_sge_setup: cookiec=%d", cookiec));
4194 
4195         /*
4196          * Set read/write bit in control.
4197          */
4198         if (cmd->cmd_flags & CFLAG_DMASEND) {
4199                 *control |= MPI2_SCSIIO_CONTROL_WRITE;
4200         } else {
4201                 *control |= MPI2_SCSIIO_CONTROL_READ;
4202         }
4203 
4204         ddi_put32(acc_hdl, &frame->DataLength, cmd->cmd_dmacount);
4205 
4206         /*
4207          * We have 2 cases here.  First where we can fit all the
4208          * SG elements into the main frame, and the case
4209          * where we can't.
4210          * If we have more cookies than we can attach to a frame
4211          * we will need to use a chain element to point
4212          * a location of memory where the rest of the S/G
4213          * elements reside.
4214          */
4215         if (cookiec <= MPTSAS_MAX_FRAME_SGES64(mpt)) {
4216                 dmap = cmd->cmd_sg;

4217                 sge = (pMpi2SGESimple64_t)(&frame->SGL);
4218                 while (cookiec--) {
4219                         ddi_put32(acc_hdl,
4220                             &sge->Address.Low, dmap->addr.address64.Low);
4221                         ddi_put32(acc_hdl,
4222                             &sge->Address.High, dmap->addr.address64.High);
4223                         ddi_put32(acc_hdl, &sge->FlagsLength,
4224                             dmap->count);
4225                         flags = ddi_get32(acc_hdl, &sge->FlagsLength);
4226                         flags |= ((uint32_t)
4227                             (MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
4228                             MPI2_SGE_FLAGS_SYSTEM_ADDRESS |
4229                             MPI2_SGE_FLAGS_64_BIT_ADDRESSING) <<
4230                             MPI2_SGE_FLAGS_SHIFT);
4231 
4232                         /*
4233                          * If this is the last cookie, we set the flags
4234                          * to indicate so
4235                          */
4236                         if (cookiec == 0) {
4237                                 flags |=
4238                                     ((uint32_t)(MPI2_SGE_FLAGS_LAST_ELEMENT
4239                                     | MPI2_SGE_FLAGS_END_OF_BUFFER
4240                                     | MPI2_SGE_FLAGS_END_OF_LIST) <<
4241                                     MPI2_SGE_FLAGS_SHIFT);
4242                         }
4243                         if (cmd->cmd_flags & CFLAG_DMASEND) {
4244                                 flags |= (MPI2_SGE_FLAGS_HOST_TO_IOC <<
4245                                     MPI2_SGE_FLAGS_SHIFT);
4246                         } else {
4247                                 flags |= (MPI2_SGE_FLAGS_IOC_TO_HOST <<
4248                                     MPI2_SGE_FLAGS_SHIFT);
4249                         }
4250                         ddi_put32(acc_hdl, &sge->FlagsLength, flags);
4251                         dmap++;
4252                         sge++;
4253                 }
4254         } else {



















4255                 /*
4256                  * Hereby we start to deal with multiple frames.
4257                  * The process is as follows:
4258                  * 1. Determine how many frames are needed for SGL element
4259                  *    storage; Note that all frames are stored in contiguous
4260                  *    memory space and in 64-bit DMA mode each element is
4261                  *    3 double-words (12 bytes) long.
4262                  * 2. Fill up the main frame. We need to do this separately
4263                  *    since it contains the SCSI IO request header and needs
4264                  *    dedicated processing. Note that the last 4 double-words
4265                  *    of the SCSI IO header is for SGL element storage
4266                  *    (MPI2_SGE_IO_UNION).
4267                  * 3. Fill the chain element in the main frame, so the DMA
4268                  *    engine can use the following frames.
4269                  * 4. Enter a loop to fill the remaining frames. Note that the
4270                  *    last frame contains no chain element.  The remaining
4271                  *    frames go into the mpt SGL buffer allocated on the fly,
4272                  *    not immediately following the main message frame, as in
4273                  *    Gen1.
4274                  * Some restrictions:
4275                  * 1. For 64-bit DMA, the simple element and chain element
4276                  *    are both of 3 double-words (12 bytes) in size, even
4277                  *    though all frames are stored in the first 4G of mem
4278                  *    range and the higher 32-bits of the address are always 0.
4279                  * 2. On some controllers (like the 1064/1068), a frame can
4280                  *    hold SGL elements with the last 1 or 2 double-words
4281                  *    (4 or 8 bytes) un-used. On these controllers, we should
4282                  *    recognize that there's not enough room for another SGL
4283                  *    element and move the sge pointer to the next frame.
4284                  */
4285                 int             i, j, k, l, frames, sgemax;
4286                 int             temp;
4287                 uint8_t         chainflags;
4288                 uint16_t        chainlength;
4289                 mptsas_cache_frames_t *p;
4290 
4291                 /*
4292                  * Sgemax is the number of SGE's that will fit
4293                  * each extra frame and frames is total
4294                  * number of frames we'll need.  1 sge entry per
4295                  * frame is reseverd for the chain element thus the -1 below.
4296                  */
4297                 sgemax = ((mpt->m_req_frame_size / sizeof (MPI2_SGE_SIMPLE64))
4298                     - 1);
4299                 temp = (cookiec - (MPTSAS_MAX_FRAME_SGES64(mpt) - 1)) / sgemax;
4300 
4301                 /*
4302                  * A little check to see if we need to round up the number
4303                  * of frames we need
4304                  */
4305                 if ((cookiec - (MPTSAS_MAX_FRAME_SGES64(mpt) - 1)) - (temp *
4306                     sgemax) > 1) {
4307                         frames = (temp + 1);
4308                 } else {
4309                         frames = temp;
4310                 }
4311                 dmap = cmd->cmd_sg;
4312                 sge = (pMpi2SGESimple64_t)(&frame->SGL);
4313 
4314                 /*
4315                  * First fill in the main frame
4316                  */
4317                 for (j = 1; j < MPTSAS_MAX_FRAME_SGES64(mpt); j++) {
4318                         ddi_put32(acc_hdl, &sge->Address.Low,
4319                             dmap->addr.address64.Low);
4320                         ddi_put32(acc_hdl, &sge->Address.High,
4321                             dmap->addr.address64.High);
4322                         ddi_put32(acc_hdl, &sge->FlagsLength, dmap->count);
4323                         flags = ddi_get32(acc_hdl, &sge->FlagsLength);
4324                         flags |= ((uint32_t)(MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
4325                             MPI2_SGE_FLAGS_SYSTEM_ADDRESS |
4326                             MPI2_SGE_FLAGS_64_BIT_ADDRESSING) <<
4327                             MPI2_SGE_FLAGS_SHIFT);
4328 
4329                         /*
4330                          * If this is the last SGE of this frame
4331                          * we set the end of list flag
4332                          */
4333                         if (j == (MPTSAS_MAX_FRAME_SGES64(mpt) - 1)) {
4334                                 flags |= ((uint32_t)
4335                                     (MPI2_SGE_FLAGS_LAST_ELEMENT) <<
4336                                     MPI2_SGE_FLAGS_SHIFT);
4337                         }
4338                         if (cmd->cmd_flags & CFLAG_DMASEND) {
4339                                 flags |=
4340                                     (MPI2_SGE_FLAGS_HOST_TO_IOC <<
4341                                     MPI2_SGE_FLAGS_SHIFT);
4342                         } else {
4343                                 flags |=
4344                                     (MPI2_SGE_FLAGS_IOC_TO_HOST <<
4345                                     MPI2_SGE_FLAGS_SHIFT);
4346                         }
4347                         ddi_put32(acc_hdl, &sge->FlagsLength, flags);
4348                         dmap++;
4349                         sge++;
4350                 }
4351 
4352                 /*
4353                  * Fill in the chain element in the main frame.
4354                  * About calculation on ChainOffset:
4355                  * 1. Struct msg_scsi_io_request has 4 double-words (16 bytes)
4356                  *    in the end reserved for SGL element storage
4357                  *    (MPI2_SGE_IO_UNION); we should count it in our
4358                  *    calculation.  See its definition in the header file.
4359                  * 2. Constant j is the counter of the current SGL element
4360                  *    that will be processed, and (j - 1) is the number of
4361                  *    SGL elements that have been processed (stored in the
4362                  *    main frame).
4363                  * 3. ChainOffset value should be in units of double-words (4
4364                  *    bytes) so the last value should be divided by 4.
4365                  */
4366                 ddi_put8(acc_hdl, &frame->ChainOffset,
4367                     (sizeof (MPI2_SCSI_IO_REQUEST) -
4368                     sizeof (MPI2_SGE_IO_UNION) +
4369                     (j - 1) * sizeof (MPI2_SGE_SIMPLE64)) >> 2);
4370                 sgechain = (pMpi2SGEChain64_t)sge;


4375 
4376                 /*
4377                  * The size of the next frame is the accurate size of space
4378                  * (in bytes) used to store the SGL elements. j is the counter
4379                  * of SGL elements. (j - 1) is the number of SGL elements that
4380                  * have been processed (stored in frames).
4381                  */
4382                 if (frames >= 2) {
4383                         chainlength = mpt->m_req_frame_size /
4384                             sizeof (MPI2_SGE_SIMPLE64) *
4385                             sizeof (MPI2_SGE_SIMPLE64);
4386                 } else {
4387                         chainlength = ((cookiec - (j - 1)) *
4388                             sizeof (MPI2_SGE_SIMPLE64));
4389                 }
4390 
4391                 p = cmd->cmd_extra_frames;
4392 
4393                 ddi_put16(acc_hdl, &sgechain->Length, chainlength);
4394                 ddi_put32(acc_hdl, &sgechain->Address.Low,
4395                     p->m_phys_addr);
4396                 /* SGL is allocated in the first 4G mem range */
4397                 ddi_put32(acc_hdl, &sgechain->Address.High, 0);
4398 
4399                 /*
4400                  * If there are more than 2 frames left we have to
4401                  * fill in the next chain offset to the location of
4402                  * the chain element in the next frame.
4403                  * sgemax is the number of simple elements in an extra
4404                  * frame. Note that the value NextChainOffset should be
4405                  * in double-words (4 bytes).
4406                  */
4407                 if (frames >= 2) {
4408                         ddi_put8(acc_hdl, &sgechain->NextChainOffset,
4409                             (sgemax * sizeof (MPI2_SGE_SIMPLE64)) >> 2);
4410                 } else {
4411                         ddi_put8(acc_hdl, &sgechain->NextChainOffset, 0);
4412                 }
4413 
4414                 /*
4415                  * Jump to next frame;
4416                  * Starting here, chain buffers go into the per command SGL.
4417                  * This buffer is allocated when chain buffers are needed.


4435                                  * and we have more SGE's to fill in
4436                                  * we have to fill the final entry
4437                                  * with a chain element and then
4438                                  * continue to the next frame
4439                                  */
4440                                 if ((l == (sgemax + 1)) && (k != frames)) {
4441                                         sgechain = (pMpi2SGEChain64_t)sge;
4442                                         j--;
4443                                         chainflags = (
4444                                             MPI2_SGE_FLAGS_CHAIN_ELEMENT |
4445                                             MPI2_SGE_FLAGS_SYSTEM_ADDRESS |
4446                                             MPI2_SGE_FLAGS_64_BIT_ADDRESSING);
4447                                         ddi_put8(p->m_acc_hdl,
4448                                             &sgechain->Flags, chainflags);
4449                                         /*
4450                                          * k is the frame counter and (k + 1)
4451                                          * is the number of the next frame.
4452                                          * Note that frames are in contiguous
4453                                          * memory space.
4454                                          */


4455                                         ddi_put32(p->m_acc_hdl,
4456                                             &sgechain->Address.Low,
4457                                             (p->m_phys_addr +
4458                                             (mpt->m_req_frame_size * k)));
4459                                         ddi_put32(p->m_acc_hdl,
4460                                             &sgechain->Address.High, 0);

4461 
4462                                         /*
4463                                          * If there are more than 2 frames left
4464                                          * we have to next chain offset to
4465                                          * the location of the chain element
4466                                          * in the next frame and fill in the
4467                                          * length of the next chain
4468                                          */
4469                                         if ((frames - k) >= 2) {
4470                                                 ddi_put8(p->m_acc_hdl,
4471                                                     &sgechain->NextChainOffset,
4472                                                     (sgemax *
4473                                                     sizeof (MPI2_SGE_SIMPLE64))
4474                                                     >> 2);
4475                                                 ddi_put16(p->m_acc_hdl,
4476                                                     &sgechain->Length,
4477                                                     mpt->m_req_frame_size /
4478                                                     sizeof (MPI2_SGE_SIMPLE64) *
4479                                                     sizeof (MPI2_SGE_SIMPLE64));
4480                                         } else {


4543                                 if (cmd->cmd_flags & CFLAG_DMASEND) {
4544                                         flags |=
4545                                             (MPI2_SGE_FLAGS_HOST_TO_IOC <<
4546                                             MPI2_SGE_FLAGS_SHIFT);
4547                                 } else {
4548                                         flags |=
4549                                             (MPI2_SGE_FLAGS_IOC_TO_HOST <<
4550                                             MPI2_SGE_FLAGS_SHIFT);
4551                                 }
4552                                 ddi_put32(p->m_acc_hdl,
4553                                     &sge->FlagsLength, flags);
4554                                 dmap++;
4555                                 sge++;
4556                         }
4557                 }
4558 
4559                 /*
4560                  * Sync DMA with the chain buffers that were just created
4561                  */
4562                 (void) ddi_dma_sync(p->m_dma_hdl, 0, 0, DDI_DMA_SYNC_FORDEV);
4563         }
4564 }
4565 
4566 /*
4567  * Interrupt handling
4568  * Utility routine.  Poll for status of a command sent to HBA
4569  * without interrupts (a FLAG_NOINTR command).
4570  */
4571 int
4572 mptsas_poll(mptsas_t *mpt, mptsas_cmd_t *poll_cmd, int polltime)
4573 {
4574         int     rval = TRUE;


4575 
4576         NDBG5(("mptsas_poll: cmd=0x%p", (void *)poll_cmd));
4577 
4578         if ((poll_cmd->cmd_flags & CFLAG_TM_CMD) == 0) {
4579                 mptsas_restart_hba(mpt);
4580         }











4581 
4582         /*
4583          * Wait, using drv_usecwait(), long enough for the command to
4584          * reasonably return from the target if the target isn't
4585          * "dead".  A polled command may well be sent from scsi_poll, and
4586          * there are retries built in to scsi_poll if the transport
4587          * accepted the packet (TRAN_ACCEPT).  scsi_poll waits 1 second
4588          * and retries the transport up to scsi_poll_busycnt times
4589          * (currently 60) if
4590          * 1. pkt_reason is CMD_INCOMPLETE and pkt_state is 0, or
4591          * 2. pkt_reason is CMD_CMPLT and *pkt_scbp has STATUS_BUSY
4592          *
4593          * limit the waiting to avoid a hang in the event that the
4594          * cmd never gets started but we are still receiving interrupts
4595          */
4596         while (!(poll_cmd->cmd_flags & CFLAG_FINISHED)) {
4597                 if (mptsas_wait_intr(mpt, polltime) == FALSE) {
4598                         NDBG5(("mptsas_poll: command incomplete"));
4599                         rval = FALSE;
4600                         break;
4601                 }
4602         }
4603 
4604         if (rval == FALSE) {
4605 
4606                 /*
4607                  * this isn't supposed to happen, the hba must be wedged
4608                  * Mark this cmd as a timeout.
4609                  */
4610                 mptsas_set_pkt_reason(mpt, poll_cmd, CMD_TIMEOUT,
4611                     (STAT_TIMEOUT|STAT_ABORTED));
4612 
4613                 if (poll_cmd->cmd_queued == FALSE) {
4614 
4615                         NDBG5(("mptsas_poll: not on waitq"));
4616 
4617                         poll_cmd->cmd_pkt->pkt_state |=


































































































































































































































































































































































































4618                             (STATE_GOT_BUS|STATE_GOT_TARGET|STATE_SENT_CMD);
4619                 } else {
4620 
4621                         /* find and remove it from the waitq */
4622                         NDBG5(("mptsas_poll: delete from waitq"));
4623                         mptsas_waitq_delete(mpt, poll_cmd);
4624                 }
4625 
4626         }
4627         mptsas_fma_check(mpt, poll_cmd);














4628         NDBG5(("mptsas_poll: done"));
4629         return (rval);
4630 }
4631 
4632 /*
4633  * Used for polling cmds and TM function
4634  */
4635 static int
4636 mptsas_wait_intr(mptsas_t *mpt, int polltime)
4637 {
4638         int                             cnt;
4639         pMpi2ReplyDescriptorsUnion_t    reply_desc_union;
4640         uint32_t                        int_mask;
4641 
4642         NDBG5(("mptsas_wait_intr"));
4643 
4644         mpt->m_polled_intr = 1;
4645 
4646         /*
4647          * Get the current interrupt mask and disable interrupts.  When
4648          * re-enabling ints, set mask to saved value.
4649          */
4650         int_mask = ddi_get32(mpt->m_datap, &mpt->m_reg->HostInterruptMask);
4651         MPTSAS_DISABLE_INTR(mpt);
4652 
4653         /*
4654          * Keep polling for at least (polltime * 1000) seconds
4655          */


4656         for (cnt = 0; cnt < polltime; cnt++) {
4657                 (void) ddi_dma_sync(mpt->m_dma_post_queue_hdl, 0, 0,
4658                     DDI_DMA_SYNC_FORCPU);
4659 




4660                 reply_desc_union = (pMpi2ReplyDescriptorsUnion_t)
4661                     MPTSAS_GET_NEXT_REPLY(mpt, mpt->m_post_index);
4662 
4663                 if (ddi_get32(mpt->m_acc_post_queue_hdl,
4664                     &reply_desc_union->Words.Low) == 0xFFFFFFFF ||
4665                     ddi_get32(mpt->m_acc_post_queue_hdl,
4666                     &reply_desc_union->Words.High) == 0xFFFFFFFF) {
4667                         drv_usecwait(1000);
4668                         continue;
4669                 }
4670 
4671                 /*
4672                  * The reply is valid, process it according to its
4673                  * type.
4674                  */
4675                 mptsas_process_intr(mpt, reply_desc_union);
4676 
4677                 if (++mpt->m_post_index == mpt->m_post_queue_depth) {
4678                         mpt->m_post_index = 0;
4679                 }
4680 
4681                 /*
4682                  * Update the global reply index
4683                  */
4684                 ddi_put32(mpt->m_datap,
4685                     &mpt->m_reg->ReplyPostHostIndex, mpt->m_post_index);
4686                 mpt->m_polled_intr = 0;
4687 
4688                 /*
4689                  * Re-enable interrupts and quit.
4690                  */
4691                 ddi_put32(mpt->m_datap, &mpt->m_reg->HostInterruptMask,
4692                     int_mask);
4693                 return (TRUE);


4694 


4695         }
4696 
4697         /*
4698          * Clear polling flag, re-enable interrupts and quit.
4699          */
4700         mpt->m_polled_intr = 0;
4701         ddi_put32(mpt->m_datap, &mpt->m_reg->HostInterruptMask, int_mask);
4702         return (FALSE);







4703 }
4704 
4705 static void
4706 mptsas_handle_scsi_io_success(mptsas_t *mpt,

4707     pMpi2ReplyDescriptorsUnion_t reply_desc)
4708 {
4709         pMpi2SCSIIOSuccessReplyDescriptor_t     scsi_io_success;
4710         uint16_t                                SMID;
4711         mptsas_slots_t                          *slots = mpt->m_active;
4712         mptsas_cmd_t                            *cmd = NULL;
4713         struct scsi_pkt                         *pkt;
4714 
4715         ASSERT(mutex_owned(&mpt->m_mutex));
4716 
4717         scsi_io_success = (pMpi2SCSIIOSuccessReplyDescriptor_t)reply_desc;
4718         SMID = ddi_get16(mpt->m_acc_post_queue_hdl, &scsi_io_success->SMID);
4719 
4720         /*
4721          * This is a success reply so just complete the IO.  First, do a sanity
4722          * check on the SMID.  The final slot is used for TM requests, which
4723          * would not come into this reply handler.
4724          */
4725         if ((SMID == 0) || (SMID > slots->m_n_normal)) {
4726                 mptsas_log(mpt, CE_WARN, "?Received invalid SMID of %d\n",
4727                     SMID);
4728                 ddi_fm_service_impact(mpt->m_dip, DDI_SERVICE_UNAFFECTED);
4729                 return;
4730         }
4731 
4732         cmd = slots->m_slot[SMID];
4733 
4734         /*
4735          * print warning and return if the slot is empty
4736          */
4737         if (cmd == NULL) {
4738                 mptsas_log(mpt, CE_WARN, "?NULL command for successful SCSI IO "
4739                     "in slot %d", SMID);
4740                 return;
4741         }

4742 
4743         pkt = CMD2PKT(cmd);
4744         pkt->pkt_state |= (STATE_GOT_BUS | STATE_GOT_TARGET | STATE_SENT_CMD |
4745             STATE_GOT_STATUS);
4746         if (cmd->cmd_flags & CFLAG_DMAVALID) {
4747                 pkt->pkt_state |= STATE_XFERRED_DATA;
4748         }
4749         pkt->pkt_resid = 0;
4750 
4751         if (cmd->cmd_flags & CFLAG_PASSTHRU) {
4752                 cmd->cmd_flags |= CFLAG_FINISHED;
4753                 cv_broadcast(&mpt->m_passthru_cv);
4754                 return;
4755         } else {



4756                 mptsas_remove_cmd(mpt, cmd);



















4757         }
4758 
4759         if (cmd->cmd_flags & CFLAG_RETRY) {
4760                 /*
4761                  * The target returned QFULL or busy, do not add tihs
4762                  * pkt to the doneq since the hba will retry
4763                  * this cmd.
4764                  *
4765                  * The pkt has already been resubmitted in
4766                  * mptsas_handle_qfull() or in mptsas_check_scsi_io_error().
4767                  * Remove this cmd_flag here.
4768                  */
4769                 cmd->cmd_flags &= ~CFLAG_RETRY;
4770         } else {
4771                 mptsas_doneq_add(mpt, cmd);
4772         }
4773 }
4774 
4775 static void
4776 mptsas_handle_address_reply(mptsas_t *mpt,
4777     pMpi2ReplyDescriptorsUnion_t reply_desc)
4778 {
4779         pMpi2AddressReplyDescriptor_t   address_reply;
4780         pMPI2DefaultReply_t             reply;
4781         mptsas_fw_diagnostic_buffer_t   *pBuffer;
4782         uint32_t                        reply_addr;
4783         uint16_t                        SMID, iocstatus;
4784         mptsas_slots_t                  *slots = mpt->m_active;
4785         mptsas_cmd_t                    *cmd = NULL;
4786         uint8_t                         function, buffer_type;
4787         m_replyh_arg_t                  *args;
4788         int                             reply_frame_no;
4789 
4790         ASSERT(mutex_owned(&mpt->m_mutex));
4791 
4792         address_reply = (pMpi2AddressReplyDescriptor_t)reply_desc;
4793         reply_addr = ddi_get32(mpt->m_acc_post_queue_hdl,
4794             &address_reply->ReplyFrameAddress);
4795         SMID = ddi_get16(mpt->m_acc_post_queue_hdl, &address_reply->SMID);
4796 
4797         /*
4798          * If reply frame is not in the proper range we should ignore this
4799          * message and exit the interrupt handler.
4800          */
4801         if ((reply_addr < mpt->m_reply_frame_dma_addr) ||
4802             (reply_addr >= (mpt->m_reply_frame_dma_addr +

4803             (mpt->m_reply_frame_size * mpt->m_max_replies))) ||
4804             ((reply_addr - mpt->m_reply_frame_dma_addr) %
4805             mpt->m_reply_frame_size != 0)) {
4806                 mptsas_log(mpt, CE_WARN, "?Received invalid reply frame "
4807                     "address 0x%x\n", reply_addr);
4808                 ddi_fm_service_impact(mpt->m_dip, DDI_SERVICE_UNAFFECTED);
4809                 return;
4810         }
4811 
4812         (void) ddi_dma_sync(mpt->m_dma_reply_frame_hdl, 0, 0,
4813             DDI_DMA_SYNC_FORCPU);
4814         reply = (pMPI2DefaultReply_t)(mpt->m_reply_frame + (reply_addr -
4815             mpt->m_reply_frame_dma_addr));
4816         function = ddi_get8(mpt->m_acc_reply_frame_hdl, &reply->Function);
4817 



4818         /*
4819          * don't get slot information and command for events since these values
4820          * don't exist
4821          */
4822         if ((function != MPI2_FUNCTION_EVENT_NOTIFICATION) &&
4823             (function != MPI2_FUNCTION_DIAG_BUFFER_POST)) {
4824                 /*
4825                  * This could be a TM reply, which use the last allocated SMID,
4826                  * so allow for that.
4827                  */
4828                 if ((SMID == 0) || (SMID > (slots->m_n_normal + 1))) {
4829                         mptsas_log(mpt, CE_WARN, "?Received invalid SMID of "
4830                             "%d\n", SMID);
4831                         ddi_fm_service_impact(mpt->m_dip,
4832                             DDI_SERVICE_UNAFFECTED);
4833                         return;
4834                 }
4835 
4836                 cmd = slots->m_slot[SMID];
4837 
4838                 /*
4839                  * print warning and return if the slot is empty
4840                  */
4841                 if (cmd == NULL) {
4842                         mptsas_log(mpt, CE_WARN, "?NULL command for address "
4843                             "reply in slot %d", SMID);
4844                         return;
4845                 }
4846                 if ((cmd->cmd_flags & CFLAG_PASSTHRU) ||
4847                     (cmd->cmd_flags & CFLAG_CONFIG) ||
4848                     (cmd->cmd_flags & CFLAG_FW_DIAG)) {
4849                         cmd->cmd_rfm = reply_addr;
4850                         cmd->cmd_flags |= CFLAG_FINISHED;
4851                         cv_broadcast(&mpt->m_passthru_cv);
4852                         cv_broadcast(&mpt->m_config_cv);
4853                         cv_broadcast(&mpt->m_fw_diag_cv);
4854                         return;
4855                 } else if (!(cmd->cmd_flags & CFLAG_FW_CMD)) {
4856                         mptsas_remove_cmd(mpt, cmd);
4857                 }
4858                 NDBG31(("\t\tmptsas_process_intr: slot=%d", SMID));
4859         }
4860         /*
4861          * Depending on the function, we need to handle
4862          * the reply frame (and cmd) differently.
4863          */
4864         switch (function) {
4865         case MPI2_FUNCTION_SCSI_IO_REQUEST:
4866                 mptsas_check_scsi_io_error(mpt, (pMpi2SCSIIOReply_t)reply, cmd);
4867                 break;
4868         case MPI2_FUNCTION_SCSI_TASK_MGMT:
4869                 cmd->cmd_rfm = reply_addr;
4870                 mptsas_check_task_mgt(mpt, (pMpi2SCSIManagementReply_t)reply,
4871                     cmd);
4872                 break;
4873         case MPI2_FUNCTION_FW_DOWNLOAD:
4874                 cmd->cmd_flags |= CFLAG_FINISHED;
4875                 cv_signal(&mpt->m_fw_cv);
4876                 break;
4877         case MPI2_FUNCTION_EVENT_NOTIFICATION:
4878                 reply_frame_no = (reply_addr - mpt->m_reply_frame_dma_addr) /
4879                     mpt->m_reply_frame_size;
4880                 args = &mpt->m_replyh_args[reply_frame_no];
4881                 args->mpt = (void *)mpt;
4882                 args->rfm = reply_addr;
4883 
4884                 /*
4885                  * Record the event if its type is enabled in
4886                  * this mpt instance by ioctl.
4887                  */
4888                 mptsas_record_event(args);
4889 
4890                 /*
4891                  * Handle time critical events
4892                  * NOT_RESPONDING/ADDED only now
4893                  */
4894                 if (mptsas_handle_event_sync(args) == DDI_SUCCESS) {
4895                         /*
4896                          * Would not return main process,
4897                          * just let taskq resolve ack action
4898                          * and ack would be sent in taskq thread


4969 
4970         /*
4971          * Return the reply frame to the free queue.
4972          */
4973         ddi_put32(mpt->m_acc_free_queue_hdl,
4974             &((uint32_t *)(void *)mpt->m_free_queue)[mpt->m_free_index],
4975             reply_addr);
4976         (void) ddi_dma_sync(mpt->m_dma_free_queue_hdl, 0, 0,
4977             DDI_DMA_SYNC_FORDEV);
4978         if (++mpt->m_free_index == mpt->m_free_queue_depth) {
4979                 mpt->m_free_index = 0;
4980         }
4981         ddi_put32(mpt->m_datap, &mpt->m_reg->ReplyFreeHostIndex,
4982             mpt->m_free_index);
4983 
4984         if (cmd->cmd_flags & CFLAG_FW_CMD)
4985                 return;
4986 
4987         if (cmd->cmd_flags & CFLAG_RETRY) {
4988                 /*
4989                  * The target returned QFULL or busy, do not add tihs
4990                  * pkt to the doneq since the hba will retry
4991                  * this cmd.
4992                  *
4993                  * The pkt has already been resubmitted in
4994                  * mptsas_handle_qfull() or in mptsas_check_scsi_io_error().
4995                  * Remove this cmd_flag here.
4996                  */
4997                 cmd->cmd_flags &= ~CFLAG_RETRY;
4998         } else {
4999                 mptsas_doneq_add(mpt, cmd);
5000         }
5001 }
5002 




5003 static void
5004 mptsas_check_scsi_io_error(mptsas_t *mpt, pMpi2SCSIIOReply_t reply,
5005     mptsas_cmd_t *cmd)
5006 {
5007         uint8_t                 scsi_status, scsi_state;
5008         uint16_t                ioc_status;
5009         uint32_t                xferred, sensecount, responsedata, loginfo = 0;
5010         struct scsi_pkt         *pkt;
5011         struct scsi_arq_status  *arqstat;
5012         struct buf              *bp;
5013         mptsas_target_t         *ptgt = cmd->cmd_tgt_addr;
5014         uint8_t                 *sensedata = NULL;
5015 
5016         if ((cmd->cmd_flags & (CFLAG_SCBEXTERN | CFLAG_EXTARQBUFVALID)) ==
5017             (CFLAG_SCBEXTERN | CFLAG_EXTARQBUFVALID)) {
5018                 bp = cmd->cmd_ext_arq_buf;
5019         } else {
5020                 bp = cmd->cmd_arq_buf;
5021         }
5022 
5023         scsi_status = ddi_get8(mpt->m_acc_reply_frame_hdl, &reply->SCSIStatus);
5024         ioc_status = ddi_get16(mpt->m_acc_reply_frame_hdl, &reply->IOCStatus);
5025         scsi_state = ddi_get8(mpt->m_acc_reply_frame_hdl, &reply->SCSIState);
5026         xferred = ddi_get32(mpt->m_acc_reply_frame_hdl, &reply->TransferCount);
5027         sensecount = ddi_get32(mpt->m_acc_reply_frame_hdl, &reply->SenseCount);
5028         responsedata = ddi_get32(mpt->m_acc_reply_frame_hdl,
5029             &reply->ResponseInfo);
5030 
5031         if (ioc_status & MPI2_IOCSTATUS_FLAG_LOG_INFO_AVAILABLE) {







5032                 loginfo = ddi_get32(mpt->m_acc_reply_frame_hdl,
5033                     &reply->IOCLogInfo);
5034                 mptsas_log(mpt, CE_NOTE,
5035                     "?Log info 0x%x received for target %d.\n"
5036                     "\tscsi_status=0x%x, ioc_status=0x%x, scsi_state=0x%x",
5037                     loginfo, Tgt(cmd), scsi_status, ioc_status,
5038                     scsi_state);
5039         }
5040 
5041         NDBG31(("\t\tscsi_status=0x%x, ioc_status=0x%x, scsi_state=0x%x",
5042             scsi_status, ioc_status, scsi_state));
5043 
5044         pkt = CMD2PKT(cmd);
5045         *(pkt->pkt_scbp) = scsi_status;
5046 
5047         if (loginfo == 0x31170000) {
5048                 /*
5049                  * if loginfo PL_LOGINFO_CODE_IO_DEVICE_MISSING_DELAY_RETRY
5050                  * 0x31170000 comes, that means the device missing delay
5051                  * is in progressing, the command need retry later.
5052                  */
5053                 *(pkt->pkt_scbp) = STATUS_BUSY;
5054                 return;
5055         }
5056 
5057         if ((scsi_state & MPI2_SCSI_STATE_NO_SCSI_STATUS) &&
5058             ((ioc_status & MPI2_IOCSTATUS_MASK) ==
5059             MPI2_IOCSTATUS_SCSI_DEVICE_NOT_THERE)) {
5060                 pkt->pkt_reason = CMD_INCOMPLETE;
5061                 pkt->pkt_state |= STATE_GOT_BUS;

5062                 if (ptgt->m_reset_delay == 0) {
5063                         mptsas_set_throttle(mpt, ptgt,
5064                             DRAIN_THROTTLE);
5065                 }

5066                 return;
5067         }
5068 
5069         if (scsi_state & MPI2_SCSI_STATE_RESPONSE_INFO_VALID) {
5070                 responsedata &= 0x000000FF;
5071                 if (responsedata & MPTSAS_SCSI_RESPONSE_CODE_TLR_OFF) {
5072                         mptsas_log(mpt, CE_NOTE, "Do not support the TLR\n");
5073                         pkt->pkt_reason = CMD_TLR_OFF;
5074                         return;
5075                 }
5076         }
5077 
5078 
5079         switch (scsi_status) {
5080         case MPI2_SCSI_STATUS_CHECK_CONDITION:


5081                 pkt->pkt_resid = (cmd->cmd_dmacount - xferred);
5082                 arqstat = (void*)(pkt->pkt_scbp);
5083                 arqstat->sts_rqpkt_status = *((struct scsi_status *)
5084                     (pkt->pkt_scbp));
5085                 pkt->pkt_state |= (STATE_GOT_BUS | STATE_GOT_TARGET |
5086                     STATE_SENT_CMD | STATE_GOT_STATUS | STATE_ARQ_DONE);
5087                 if (cmd->cmd_flags & CFLAG_XARQ) {
5088                         pkt->pkt_state |= STATE_XARQ_DONE;
5089                 }
5090                 if (pkt->pkt_resid != cmd->cmd_dmacount) {
5091                         pkt->pkt_state |= STATE_XFERRED_DATA;
5092                 }
5093                 arqstat->sts_rqpkt_reason = pkt->pkt_reason;
5094                 arqstat->sts_rqpkt_state  = pkt->pkt_state;
5095                 arqstat->sts_rqpkt_state |= STATE_XFERRED_DATA;
5096                 arqstat->sts_rqpkt_statistics = pkt->pkt_statistics;
5097                 sensedata = (uint8_t *)&arqstat->sts_sensedata;
5098 
5099                 bcopy((uchar_t *)bp->b_un.b_addr, sensedata,








5100                     ((cmd->cmd_rqslen >= sensecount) ? sensecount :
5101                     cmd->cmd_rqslen));
5102                 arqstat->sts_rqpkt_resid = (cmd->cmd_rqslen - sensecount);
5103                 cmd->cmd_flags |= CFLAG_CMDARQ;
5104                 /*
5105                  * Set proper status for pkt if autosense was valid
5106                  */
5107                 if (scsi_state & MPI2_SCSI_STATE_AUTOSENSE_VALID) {
5108                         struct scsi_status zero_status = { 0 };
5109                         arqstat->sts_rqpkt_status = zero_status;
5110                 }
5111 
5112                 /*
5113                  * ASC=0x47 is parity error
5114                  * ASC=0x48 is initiator detected error received
5115                  */
5116                 if ((scsi_sense_key(sensedata) == KEY_ABORTED_COMMAND) &&
5117                     ((scsi_sense_asc(sensedata) == 0x47) ||
5118                     (scsi_sense_asc(sensedata) == 0x48))) {
5119                         mptsas_log(mpt, CE_NOTE, "Aborted_command!");
5120                 }
5121 
5122                 /*


5134                         topo_node = kmem_zalloc(
5135                             sizeof (mptsas_topo_change_list_t),
5136                             KM_NOSLEEP);
5137                         if (topo_node == NULL) {
5138                                 mptsas_log(mpt, CE_NOTE, "No memory"
5139                                     "resource for handle SAS dynamic"
5140                                     "reconfigure.\n");
5141                                 break;
5142                         }
5143                         topo_node->mpt = mpt;
5144                         topo_node->event = MPTSAS_DR_EVENT_RECONFIG_TARGET;
5145                         topo_node->un.phymask = ptgt->m_addr.mta_phymask;
5146                         topo_node->devhdl = ptgt->m_devhdl;
5147                         topo_node->object = (void *)ptgt;
5148                         topo_node->flags = MPTSAS_TOPO_FLAG_LUN_ASSOCIATED;
5149 
5150                         if ((ddi_taskq_dispatch(mpt->m_dr_taskq,
5151                             mptsas_handle_dr,
5152                             (void *)topo_node,
5153                             DDI_NOSLEEP)) != DDI_SUCCESS) {


5154                                 mptsas_log(mpt, CE_NOTE, "mptsas start taskq"
5155                                     "for handle SAS dynamic reconfigure"
5156                                     "failed. \n");
5157                         }
5158                 }
5159                 break;
5160         case MPI2_SCSI_STATUS_GOOD:
5161                 switch (ioc_status & MPI2_IOCSTATUS_MASK) {
5162                 case MPI2_IOCSTATUS_SCSI_DEVICE_NOT_THERE:
5163                         pkt->pkt_reason = CMD_DEV_GONE;
5164                         pkt->pkt_state |= STATE_GOT_BUS;

5165                         if (ptgt->m_reset_delay == 0) {
5166                                 mptsas_set_throttle(mpt, ptgt, DRAIN_THROTTLE);
5167                         }

5168                         NDBG31(("lost disk for target%d, command:%x",
5169                             Tgt(cmd), pkt->pkt_cdbp[0]));
5170                         break;
5171                 case MPI2_IOCSTATUS_SCSI_DATA_OVERRUN:
5172                         NDBG31(("data overrun: xferred=%d", xferred));
5173                         NDBG31(("dmacount=%d", cmd->cmd_dmacount));
5174                         pkt->pkt_reason = CMD_DATA_OVR;
5175                         pkt->pkt_state |= (STATE_GOT_BUS | STATE_GOT_TARGET
5176                             | STATE_SENT_CMD | STATE_GOT_STATUS
5177                             | STATE_XFERRED_DATA);
5178                         pkt->pkt_resid = 0;
5179                         break;
5180                 case MPI2_IOCSTATUS_SCSI_RESIDUAL_MISMATCH:
5181                 case MPI2_IOCSTATUS_SCSI_DATA_UNDERRUN:
5182                         NDBG31(("data underrun: xferred=%d", xferred));
5183                         NDBG31(("dmacount=%d", cmd->cmd_dmacount));
5184                         pkt->pkt_state |= (STATE_GOT_BUS | STATE_GOT_TARGET
5185                             | STATE_SENT_CMD | STATE_GOT_STATUS);
5186                         pkt->pkt_resid = (cmd->cmd_dmacount - xferred);
5187                         if (pkt->pkt_resid != cmd->cmd_dmacount) {
5188                                 pkt->pkt_state |= STATE_XFERRED_DATA;
5189                         }
5190                         break;
5191                 case MPI2_IOCSTATUS_SCSI_TASK_TERMINATED:
5192                         mptsas_set_pkt_reason(mpt,
5193                             cmd, CMD_RESET, STAT_BUS_RESET);










5194                         break;
5195                 case MPI2_IOCSTATUS_SCSI_IOC_TERMINATED:
5196                 case MPI2_IOCSTATUS_SCSI_EXT_TERMINATED:
5197                         mptsas_set_pkt_reason(mpt,
5198                             cmd, CMD_RESET, STAT_DEV_RESET);
5199                         break;
5200                 case MPI2_IOCSTATUS_SCSI_IO_DATA_ERROR:
5201                 case MPI2_IOCSTATUS_SCSI_PROTOCOL_ERROR:
5202                         pkt->pkt_state |= (STATE_GOT_BUS | STATE_GOT_TARGET);
5203                         mptsas_set_pkt_reason(mpt,
5204                             cmd, CMD_TERMINATED, STAT_TERMINATED);
5205                         break;
5206                 case MPI2_IOCSTATUS_INSUFFICIENT_RESOURCES:
5207                 case MPI2_IOCSTATUS_BUSY:
5208                         /*
5209                          * set throttles to drain
5210                          */
5211                         for (ptgt = refhash_first(mpt->m_targets); ptgt != NULL;
5212                             ptgt = refhash_next(mpt->m_targets, ptgt)) {
5213                                 mptsas_set_throttle(mpt, ptgt, DRAIN_THROTTLE);

5214                         }
5215 
5216                         /*
5217                          * retry command
5218                          */
5219                         cmd->cmd_flags |= CFLAG_RETRY;
5220                         cmd->cmd_pkt_flags |= FLAG_HEAD;
5221 
5222                         (void) mptsas_accept_pkt(mpt, cmd);
5223                         break;
5224                 default:
5225                         mptsas_log(mpt, CE_WARN,
5226                             "unknown ioc_status = %x\n", ioc_status);
5227                         mptsas_log(mpt, CE_CONT, "scsi_state = %x, transfer "
5228                             "count = %x, scsi_status = %x", scsi_state,
5229                             xferred, scsi_status);
5230                         break;
5231                 }
5232                 break;
5233         case MPI2_SCSI_STATUS_TASK_SET_FULL:
5234                 mptsas_handle_qfull(mpt, cmd);
5235                 break;
5236         case MPI2_SCSI_STATUS_BUSY:
5237                 NDBG31(("scsi_status busy received"));
5238                 break;
5239         case MPI2_SCSI_STATUS_RESERVATION_CONFLICT:
5240                 NDBG31(("scsi_status reservation conflict received"));
5241                 break;
5242         default:


5286                  * Check for invalid DevHandle of 0 in case application
5287                  * sends bad command.  DevHandle of 0 could cause problems.
5288                  */
5289                 if (dev_handle == 0) {
5290                         mptsas_log(mpt, CE_WARN, "!Can't flush target with"
5291                             " DevHandle of 0.");
5292                 } else {
5293                         mptsas_flush_target(mpt, dev_handle, Lun(cmd),
5294                             task_type);
5295                 }
5296                 break;
5297         default:
5298                 mptsas_log(mpt, CE_WARN, "Unknown task management type %d.",
5299                     task_type);
5300                 mptsas_log(mpt, CE_WARN, "ioc status = %x", ioc_status);
5301                 break;
5302         }
5303 }
5304 
5305 static void
5306 mptsas_doneq_thread(mptsas_doneq_thread_arg_t *arg)
5307 {
5308         mptsas_t                        *mpt = arg->mpt;
5309         uint64_t                        t = arg->t;
5310         mptsas_cmd_t                    *cmd;
5311         struct scsi_pkt                 *pkt;
5312         mptsas_doneq_thread_list_t      *item = &mpt->m_doneq_thread_id[t];
5313 
5314         mutex_enter(&item->mutex);
5315         while (item->flag & MPTSAS_DONEQ_THREAD_ACTIVE) {
5316                 if (!item->doneq) {
5317                         cv_wait(&item->cv, &item->mutex);
5318                 }
5319                 pkt = NULL;
5320                 if ((cmd = mptsas_doneq_thread_rm(mpt, t)) != NULL) {
5321                         cmd->cmd_flags |= CFLAG_COMPLETED;
5322                         pkt = CMD2PKT(cmd);
5323                 }
5324                 mutex_exit(&item->mutex);
5325                 if (pkt) {
5326                         mptsas_pkt_comp(pkt, cmd);
5327                 }
5328                 mutex_enter(&item->mutex);
5329         }
5330         mutex_exit(&item->mutex);
5331         mutex_enter(&mpt->m_doneq_mutex);
5332         mpt->m_doneq_thread_n--;
5333         cv_broadcast(&mpt->m_doneq_thread_cv);
5334         mutex_exit(&mpt->m_doneq_mutex);
5335 }
5336 
5337 
5338 /*
5339  * mpt interrupt handler.
5340  */
5341 static uint_t
5342 mptsas_intr(caddr_t arg1, caddr_t arg2)
5343 {
5344         mptsas_t                        *mpt = (void *)arg1;


5345         pMpi2ReplyDescriptorsUnion_t    reply_desc_union;
5346         uchar_t                         did_reply = FALSE;



5347 
5348         NDBG1(("mptsas_intr: arg1 0x%p arg2 0x%p", (void *)arg1, (void *)arg2));
5349 
5350         mutex_enter(&mpt->m_mutex);
5351 
5352         /*
5353          * If interrupts are shared by two channels then check whether this
5354          * interrupt is genuinely for this channel by making sure first the
5355          * chip is in high power state.
5356          */
5357         if ((mpt->m_options & MPTSAS_OPT_PM) &&
5358             (mpt->m_power_level != PM_LEVEL_D0)) {
5359                 mutex_exit(&mpt->m_mutex);
5360                 return (DDI_INTR_UNCLAIMED);
5361         }
5362 















5363         /*
5364          * If polling, interrupt was triggered by some shared interrupt because
5365          * IOC interrupts are disabled during polling, so polling routine will
5366          * handle any replies.  Considering this, if polling is happening,
5367          * return with interrupt unclaimed.
5368          */
5369         if (mpt->m_polled_intr) {
5370                 mutex_exit(&mpt->m_mutex);
5371                 mptsas_log(mpt, CE_WARN, "mpt_sas: Unclaimed interrupt");


5372                 return (DDI_INTR_UNCLAIMED);
5373         }
5374 
5375         /*
5376          * Read the istat register.

5377          */
5378         if ((INTPENDING(mpt)) != 0) {









5379                 /*
5380                  * read fifo until empty.



5381                  */

5382 #ifndef __lock_lint
5383                 _NOTE(CONSTCOND)
5384 #endif
5385                 while (TRUE) {
5386                         (void) ddi_dma_sync(mpt->m_dma_post_queue_hdl, 0, 0,
5387                             DDI_DMA_SYNC_FORCPU);
5388                         reply_desc_union = (pMpi2ReplyDescriptorsUnion_t)
5389                             MPTSAS_GET_NEXT_REPLY(mpt, mpt->m_post_index);
5390 
5391                         if (ddi_get32(mpt->m_acc_post_queue_hdl,
5392                             &reply_desc_union->Words.Low) == 0xFFFFFFFF ||
5393                             ddi_get32(mpt->m_acc_post_queue_hdl,
5394                             &reply_desc_union->Words.High) == 0xFFFFFFFF) {
5395                                 break;
5396                         }
5397 





5398                         /*
5399                          * The reply is valid, process it according to its
5400                          * type.  Also, set a flag for updating the reply index
5401                          * after they've all been processed.
5402                          */
5403                         did_reply = TRUE;
5404 
5405                         mptsas_process_intr(mpt, reply_desc_union);





5406 
5407                         /*
5408                          * Increment post index and roll over if needed.
5409                          */
5410                         if (++mpt->m_post_index == mpt->m_post_queue_depth) {
5411                                 mpt->m_post_index = 0;

5412                         }






5413                 }

5414 














5415                 /*
5416                  * Update the global reply index if at least one reply was
5417                  * processed.

5418                  */
5419                 if (did_reply) {
5420                         ddi_put32(mpt->m_datap,
5421                             &mpt->m_reg->ReplyPostHostIndex, mpt->m_post_index);
5422                 }



5423         } else {
5424                 mutex_exit(&mpt->m_mutex);
5425                 return (DDI_INTR_UNCLAIMED);



5426         }
5427         NDBG1(("mptsas_intr complete"));
5428 
5429         /*
5430          * If no helper threads are created, process the doneq in ISR. If
5431          * helpers are created, use the doneq length as a metric to measure the
5432          * load on the interrupt CPU. If it is long enough, which indicates the
5433          * load is heavy, then we deliver the IO completions to the helpers.
5434          * This measurement has some limitations, although it is simple and
5435          * straightforward and works well for most of the cases at present.



















5436          */



5437         if (!mpt->m_doneq_thread_n ||
5438             (mpt->m_doneq_len <= mpt->m_doneq_length_threshold)) {

5439                 mptsas_doneq_empty(mpt);
5440         } else {
5441                 mptsas_deliver_doneq_thread(mpt);



5442         }
5443 
5444         /*
5445          * If there are queued cmd, start them now.
5446          */
5447         if (mpt->m_waitq != NULL) {


5448                 mptsas_restart_waitq(mpt);
5449         }
5450 
5451         mutex_exit(&mpt->m_mutex);

5452         return (DDI_INTR_CLAIMED);
5453 }
5454 
5455 static void
5456 mptsas_process_intr(mptsas_t *mpt,
5457     pMpi2ReplyDescriptorsUnion_t reply_desc_union)
5458 {
5459         uint8_t reply_type;
5460 
5461         ASSERT(mutex_owned(&mpt->m_mutex));





5462 
5463         /*
5464          * The reply is valid, process it according to its
5465          * type.  Also, set a flag for updated the reply index
5466          * after they've all been processed.
5467          */
5468         reply_type = ddi_get8(mpt->m_acc_post_queue_hdl,
5469             &reply_desc_union->Default.ReplyFlags);


5470         reply_type &= MPI2_RPY_DESCRIPT_FLAGS_TYPE_MASK;
5471         if (reply_type == MPI2_RPY_DESCRIPT_FLAGS_SCSI_IO_SUCCESS) {
5472                 mptsas_handle_scsi_io_success(mpt, reply_desc_union);

5473         } else if (reply_type == MPI2_RPY_DESCRIPT_FLAGS_ADDRESS_REPLY) {

5474                 mptsas_handle_address_reply(mpt, reply_desc_union);

5475         } else {
5476                 mptsas_log(mpt, CE_WARN, "?Bad reply type %x", reply_type);
5477                 ddi_fm_service_impact(mpt->m_dip, DDI_SERVICE_UNAFFECTED);
5478         }
5479 
5480         /*
5481          * Clear the reply descriptor for re-use and increment
5482          * index.
5483          */
5484         ddi_put64(mpt->m_acc_post_queue_hdl,
5485             &((uint64_t *)(void *)mpt->m_post_queue)[mpt->m_post_index],
5486             0xFFFFFFFFFFFFFFFF);
5487         (void) ddi_dma_sync(mpt->m_dma_post_queue_hdl, 0, 0,
5488             DDI_DMA_SYNC_FORDEV);
5489 }
5490 
5491 /*
5492  * handle qfull condition
5493  */
5494 static void
5495 mptsas_handle_qfull(mptsas_t *mpt, mptsas_cmd_t *cmd)
5496 {
5497         mptsas_target_t *ptgt = cmd->cmd_tgt_addr;
5498 

5499         if ((++cmd->cmd_qfull_retries > ptgt->m_qfull_retries) ||
5500             (ptgt->m_qfull_retries == 0)) {
5501                 /*
5502                  * We have exhausted the retries on QFULL, or,
5503                  * the target driver has indicated that it
5504                  * wants to handle QFULL itself by setting
5505                  * qfull-retries capability to 0. In either case
5506                  * we want the target driver's QFULL handling
5507                  * to kick in. We do this by having pkt_reason
5508                  * as CMD_CMPLT and pkt_scbp as STATUS_QFULL.
5509                  */
5510                 mptsas_set_throttle(mpt, ptgt, DRAIN_THROTTLE);
5511         } else {
5512                 if (ptgt->m_reset_delay == 0) {
5513                         ptgt->m_t_throttle =
5514                             max((ptgt->m_t_ncmds - 2), 0);
5515                 }

5516 
5517                 cmd->cmd_pkt_flags |= FLAG_HEAD;
5518                 cmd->cmd_flags &= ~(CFLAG_TRANFLAG);
5519                 cmd->cmd_flags |= CFLAG_RETRY;
5520 
5521                 (void) mptsas_accept_pkt(mpt, cmd);
5522 

5523                 /*
5524                  * when target gives queue full status with no commands
5525                  * outstanding (m_t_ncmds == 0), throttle is set to 0
5526                  * (HOLD_THROTTLE), and the queue full handling start
5527                  * (see psarc/1994/313); if there are commands outstanding,
5528                  * throttle is set to (m_t_ncmds - 2)
5529                  */
5530                 if (ptgt->m_t_throttle == HOLD_THROTTLE) {
5531                         /*
5532                          * By setting throttle to QFULL_THROTTLE, we
5533                          * avoid submitting new commands and in
5534                          * mptsas_restart_cmd find out slots which need
5535                          * their throttles to be cleared.
5536                          */
5537                         mptsas_set_throttle(mpt, ptgt, QFULL_THROTTLE);
5538                         if (mpt->m_restart_cmd_timeid == 0) {
5539                                 mpt->m_restart_cmd_timeid =
5540                                     timeout(mptsas_restart_cmd, mpt,
5541                                     ptgt->m_qfull_retry_interval);
5542                         }
5543                 }
5544         }

5545 }
5546 
5547 mptsas_phymask_t
5548 mptsas_physport_to_phymask(mptsas_t *mpt, uint8_t physport)
5549 {
5550         mptsas_phymask_t        phy_mask = 0;
5551         uint8_t                 i = 0;
5552 
5553         NDBG20(("mptsas%d physport_to_phymask enter", mpt->m_instance));
5554 
5555         ASSERT(mutex_owned(&mpt->m_mutex));
5556 
5557         /*
5558          * If physport is 0xFF, this is a RAID volume.  Use phymask of 0.
5559          */
5560         if (physport == 0xFF) {
5561                 return (0);
5562         }
5563 
5564         for (i = 0; i < MPTSAS_MAX_PHYS; i++) {
5565                 if (mpt->m_phy_info[i].attached_devhdl &&
5566                     (mpt->m_phy_info[i].phy_mask != 0) &&
5567                     (mpt->m_phy_info[i].port_num == physport)) {
5568                         phy_mask = mpt->m_phy_info[i].phy_mask;
5569                         break;
5570                 }
5571         }
5572         NDBG20(("mptsas%d physport_to_phymask:physport :%x phymask :%x, ",
5573             mpt->m_instance, physport, phy_mask));
5574         return (phy_mask);
5575 }
5576 
5577 /*
5578  * mpt free device handle after device gone, by use of passthrough
5579  */
5580 static int
5581 mptsas_free_devhdl(mptsas_t *mpt, uint16_t devhdl)
5582 {
5583         Mpi2SasIoUnitControlRequest_t   req;
5584         Mpi2SasIoUnitControlReply_t     rep;
5585         int                             ret;
5586 
5587         ASSERT(mutex_owned(&mpt->m_mutex));
5588 
5589         /*
5590          * Need to compose a SAS IO Unit Control request message
5591          * and call mptsas_do_passthru() function
5592          */


5606         }
5607 
5608         /* do passthrough success, check the ioc status */
5609         if (LE_16(rep.IOCStatus) != MPI2_IOCSTATUS_SUCCESS) {
5610                 cmn_err(CE_WARN, "mptsas_free_devhdl: passthru SAS IO Unit "
5611                     "Control IOCStatus %d", LE_16(rep.IOCStatus));
5612                 return (DDI_FAILURE);
5613         }
5614 
5615         return (DDI_SUCCESS);
5616 }
5617 
5618 static void
5619 mptsas_update_phymask(mptsas_t *mpt)
5620 {
5621         mptsas_phymask_t mask = 0, phy_mask;
5622         char            *phy_mask_name;
5623         uint8_t         current_port;
5624         int             i, j;
5625 
5626         NDBG20(("mptsas%d update phymask ", mpt->m_instance));
5627 
5628         ASSERT(mutex_owned(&mpt->m_mutex));
5629 
5630         (void) mptsas_get_sas_io_unit_page(mpt);
5631 
5632         phy_mask_name = kmem_zalloc(MPTSAS_MAX_PHYS, KM_SLEEP);
5633 
5634         for (i = 0; i < mpt->m_num_phys; i++) {
5635                 phy_mask = 0x00;
5636 
5637                 if (mpt->m_phy_info[i].attached_devhdl == 0)
5638                         continue;
5639 
5640                 bzero(phy_mask_name, sizeof (phy_mask_name));
5641 
5642                 current_port = mpt->m_phy_info[i].port_num;
5643 
5644                 if ((mask & (1 << i)) != 0)
5645                         continue;
5646 


5652                 }
5653                 mask = mask | phy_mask;
5654 
5655                 for (j = 0; j < mpt->m_num_phys; j++) {
5656                         if ((phy_mask >> j) & 0x01) {
5657                                 mpt->m_phy_info[j].phy_mask = phy_mask;
5658                         }
5659                 }
5660 
5661                 (void) sprintf(phy_mask_name, "%x", phy_mask);
5662 
5663                 mutex_exit(&mpt->m_mutex);
5664                 /*
5665                  * register a iport, if the port has already been existed
5666                  * SCSA will do nothing and just return.
5667                  */
5668                 (void) scsi_hba_iport_register(mpt->m_dip, phy_mask_name);
5669                 mutex_enter(&mpt->m_mutex);
5670         }
5671         kmem_free(phy_mask_name, MPTSAS_MAX_PHYS);
5672         NDBG20(("mptsas%d update phymask return", mpt->m_instance));
5673 }
5674 
5675 /*
5676  * mptsas_handle_dr is a task handler for DR, the DR action includes:
5677  * 1. Directly attched Device Added/Removed.
5678  * 2. Expander Device Added/Removed.
5679  * 3. Indirectly Attached Device Added/Expander.
5680  * 4. LUNs of a existing device status change.
5681  * 5. RAID volume created/deleted.
5682  * 6. Member of RAID volume is released because of RAID deletion.
5683  * 7. Physical disks are removed because of RAID creation.
5684  */
5685 static void
5686 mptsas_handle_dr(void *args) {
5687         mptsas_topo_change_list_t       *topo_node = NULL;
5688         mptsas_topo_change_list_t       *save_node = NULL;
5689         mptsas_t                        *mpt;
5690         dev_info_t                      *parent = NULL;
5691         mptsas_phymask_t                phymask = 0;
5692         char                            *phy_mask_name;
5693         uint8_t                         flags = 0, physport = 0xff;
5694         uint8_t                         port_update = 0;
5695         uint_t                          event;
5696 
5697         topo_node = (mptsas_topo_change_list_t *)args;
5698 
5699         mpt = topo_node->mpt;
5700         event = topo_node->event;
5701         flags = topo_node->flags;
5702 
5703         phy_mask_name = kmem_zalloc(MPTSAS_MAX_PHYS, KM_SLEEP);
5704 
5705         NDBG20(("mptsas%d handle_dr enter", mpt->m_instance));
5706 
5707         switch (event) {
5708         case MPTSAS_DR_EVENT_RECONFIG_TARGET:
5709                 if ((flags == MPTSAS_TOPO_FLAG_DIRECT_ATTACHED_DEVICE) ||
5710                     (flags == MPTSAS_TOPO_FLAG_EXPANDER_ATTACHED_DEVICE) ||
5711                     (flags == MPTSAS_TOPO_FLAG_RAID_PHYSDRV_ASSOCIATED)) {
5712                         /*
5713                          * Direct attached or expander attached device added
5714                          * into system or a Phys Disk that is being unhidden.
5715                          */
5716                         port_update = 1;
5717                 }
5718                 break;
5719         case MPTSAS_DR_EVENT_RECONFIG_SMP:
5720                 /*
5721                  * New expander added into system, it must be the head
5722                  * of topo_change_list_t
5723                  */
5724                 port_update = 1;
5725                 break;


5727                 port_update = 0;
5728                 break;
5729         }
5730         /*
5731          * All cases port_update == 1 may cause initiator port form change
5732          */
5733         mutex_enter(&mpt->m_mutex);
5734         if (mpt->m_port_chng && port_update) {
5735                 /*
5736                  * mpt->m_port_chng flag indicates some PHYs of initiator
5737                  * port have changed to online. So when expander added or
5738                  * directly attached device online event come, we force to
5739                  * update port information by issueing SAS IO Unit Page and
5740                  * update PHYMASKs.
5741                  */
5742                 (void) mptsas_update_phymask(mpt);
5743                 mpt->m_port_chng = 0;
5744 
5745         }
5746         mutex_exit(&mpt->m_mutex);

5747         while (topo_node) {
5748                 phymask = 0;















5749                 if (parent == NULL) {
5750                         physport = topo_node->un.physport;
5751                         event = topo_node->event;
5752                         flags = topo_node->flags;
5753                         if (event & (MPTSAS_DR_EVENT_OFFLINE_TARGET |
5754                             MPTSAS_DR_EVENT_OFFLINE_SMP)) {
5755                                 /*
5756                                  * For all offline events, phymask is known
5757                                  */
5758                                 phymask = topo_node->un.phymask;
5759                                 goto find_parent;
5760                         }
5761                         if (event & MPTSAS_TOPO_FLAG_REMOVE_HANDLE) {
5762                                 goto handle_topo_change;
5763                         }
5764                         if (flags & MPTSAS_TOPO_FLAG_LUN_ASSOCIATED) {
5765                                 phymask = topo_node->un.phymask;
5766                                 goto find_parent;
5767                         }
5768 
5769                         if ((flags ==
5770                             MPTSAS_TOPO_FLAG_RAID_PHYSDRV_ASSOCIATED) &&
5771                             (event == MPTSAS_DR_EVENT_RECONFIG_TARGET)) {
5772                                 /*
5773                                  * There is no any field in IR_CONFIG_CHANGE
5774                                  * event indicate physport/phynum, let's get
5775                                  * parent after SAS Device Page0 request.
5776                                  */
5777                                 goto handle_topo_change;
5778                         }
5779 
5780                         mutex_enter(&mpt->m_mutex);
5781                         if (flags == MPTSAS_TOPO_FLAG_DIRECT_ATTACHED_DEVICE) {
5782                                 /*
5783                                  * If the direct attached device added or a
5784                                  * phys disk is being unhidden, argument
5785                                  * physport actually is PHY#, so we have to get
5786                                  * phymask according PHY#.
5787                                  */
5788                                 physport = mpt->m_phy_info[physport].port_num;
5789                         }
5790 
5791                         /*
5792                          * Translate physport to phymask so that we can search
5793                          * parent dip.
5794                          */
5795                         phymask = mptsas_physport_to_phymask(mpt,
5796                             physport);
5797                         mutex_exit(&mpt->m_mutex);
5798 
5799 find_parent:
5800                         bzero(phy_mask_name, MPTSAS_MAX_PHYS);
5801                         /*
5802                          * For RAID topology change node, write the iport name
5803                          * as v0.
5804                          */
5805                         if (flags & MPTSAS_TOPO_FLAG_RAID_ASSOCIATED) {
5806                                 (void) sprintf(phy_mask_name, "v0");
5807                         } else {
5808                                 /*
5809                                  * phymask can bo 0 if the drive has been
5810                                  * pulled by the time an add event is
5811                                  * processed.  If phymask is 0, just skip this
5812                                  * event and continue.
5813                                  */
5814                                 if (phymask == 0) {
5815                                         mutex_enter(&mpt->m_mutex);
5816                                         save_node = topo_node;
5817                                         topo_node = topo_node->next;
5818                                         ASSERT(save_node);
5819                                         kmem_free(save_node,
5820                                             sizeof (mptsas_topo_change_list_t));
5821                                         mutex_exit(&mpt->m_mutex);
5822 
5823                                         parent = NULL;
5824                                         continue;
5825                                 }
5826                                 (void) sprintf(phy_mask_name, "%x", phymask);
5827                         }
5828                         parent = scsi_hba_iport_find(mpt->m_dip,
5829                             phy_mask_name);
5830                         if (parent == NULL) {
5831                                 mptsas_log(mpt, CE_WARN, "Failed to find an "
5832                                     "iport, should not happen!");
5833                                 goto out;






5834                         }
5835 
5836                 }
5837                 ASSERT(parent);
5838 handle_topo_change:
5839 
5840                 mutex_enter(&mpt->m_mutex);
5841                 /*
5842                  * If HBA is being reset, don't perform operations depending
5843                  * on the IOC. We must free the topo list, however.
5844                  */
5845                 if (!mpt->m_in_reset)
5846                         mptsas_handle_topo_change(topo_node, parent);
5847                 else
5848                         NDBG20(("skipping topo change received during reset"));

5849                 save_node = topo_node;
5850                 topo_node = topo_node->next;
5851                 ASSERT(save_node);
5852                 kmem_free(save_node, sizeof (mptsas_topo_change_list_t));
5853                 mutex_exit(&mpt->m_mutex);
5854 
5855                 if ((flags == MPTSAS_TOPO_FLAG_DIRECT_ATTACHED_DEVICE) ||
5856                     (flags == MPTSAS_TOPO_FLAG_RAID_PHYSDRV_ASSOCIATED) ||
5857                     (flags == MPTSAS_TOPO_FLAG_RAID_ASSOCIATED)) {
5858                         /*
5859                          * If direct attached device associated, make sure
5860                          * reset the parent before start the next one. But
5861                          * all devices associated with expander shares the
5862                          * parent.  Also, reset parent if this is for RAID.
5863                          */
5864                         parent = NULL;
5865                 }
5866         }
5867 out:
5868         kmem_free(phy_mask_name, MPTSAS_MAX_PHYS);
























































































5869 }
5870 
5871 static void
5872 mptsas_handle_topo_change(mptsas_topo_change_list_t *topo_node,
5873     dev_info_t *parent)
5874 {
5875         mptsas_target_t *ptgt = NULL;
5876         mptsas_smp_t    *psmp = NULL;
5877         mptsas_t        *mpt = (void *)topo_node->mpt;
5878         uint16_t        devhdl;
5879         uint16_t        attached_devhdl;
5880         uint64_t        sas_wwn = 0;
5881         int             rval = 0;
5882         uint32_t        page_address;
5883         uint8_t         phy, flags;
5884         char            *addr = NULL;
5885         dev_info_t      *lundip;
5886         int             circ = 0, circ1 = 0;
5887         char            attached_wwnstr[MPTSAS_WWN_STRLEN];
5888 
5889         NDBG20(("mptsas%d handle_topo_change enter", mpt->m_instance));


5890 
5891         ASSERT(mutex_owned(&mpt->m_mutex));
5892 
5893         switch (topo_node->event) {
5894         case MPTSAS_DR_EVENT_RECONFIG_TARGET:
5895         {
5896                 char *phy_mask_name;
5897                 mptsas_phymask_t phymask = 0;
5898 
5899                 if (topo_node->flags == MPTSAS_TOPO_FLAG_RAID_ASSOCIATED) {
5900                         /*
5901                          * Get latest RAID info.
5902                          */
5903                         (void) mptsas_get_raid_info(mpt);
5904                         ptgt = refhash_linear_search(mpt->m_targets,
5905                             mptsas_target_eval_devhdl, &topo_node->devhdl);
5906                         if (ptgt == NULL)
5907                                 break;
5908                 } else {
5909                         ptgt = (void *)topo_node->object;


6028                                 /*
6029                                  * topo_node->un.physport is really the PHY#
6030                                  * for direct attached devices
6031                                  */
6032                                 mptsas_smhba_set_one_phy_props(mpt, parent,
6033                                     topo_node->un.physport, &attached_devhdl);
6034 
6035                                 if (ddi_prop_update_int(DDI_DEV_T_NONE, parent,
6036                                     MPTSAS_VIRTUAL_PORT, 0) !=
6037                                     DDI_PROP_SUCCESS) {
6038                                         (void) ddi_prop_remove(DDI_DEV_T_NONE,
6039                                             parent, MPTSAS_VIRTUAL_PORT);
6040                                         mptsas_log(mpt, CE_WARN,
6041                                             "mptsas virtual-port"
6042                                             "port prop update failed");
6043                                         return;
6044                                 }
6045                         }
6046                 }
6047                 mutex_enter(&mpt->m_mutex);
6048 
6049                 NDBG20(("mptsas%d handle_topo_change to online devhdl:%x, "
6050                     "phymask:%x.", mpt->m_instance, ptgt->m_devhdl,
6051                     ptgt->m_addr.mta_phymask));
6052                 break;
6053         }
6054         case MPTSAS_DR_EVENT_OFFLINE_TARGET:
6055         {
6056                 devhdl = topo_node->devhdl;
6057                 ptgt = refhash_linear_search(mpt->m_targets,
6058                     mptsas_target_eval_devhdl, &devhdl);
6059                 if (ptgt == NULL)
6060                         break;
6061 
6062                 sas_wwn = ptgt->m_addr.mta_wwn;
6063                 phy = ptgt->m_phynum;
6064 
6065                 addr = kmem_zalloc(SCSI_MAXNAMELEN, KM_SLEEP);
6066 
6067                 if (sas_wwn) {
6068                         (void) sprintf(addr, "w%016"PRIx64, sas_wwn);
6069                 } else {
6070                         (void) sprintf(addr, "p%x", phy);
6071                 }
6072                 ASSERT(ptgt->m_devhdl == devhdl);
6073 
6074                 if ((topo_node->flags == MPTSAS_TOPO_FLAG_RAID_ASSOCIATED) ||
6075                     (topo_node->flags ==
6076                     MPTSAS_TOPO_FLAG_RAID_PHYSDRV_ASSOCIATED)) {
6077                         /*
6078                          * Get latest RAID info if RAID volume status changes
6079                          * or Phys Disk status changes
6080                          */
6081                         (void) mptsas_get_raid_info(mpt);
6082                 }
6083                 /*
6084                  * Abort all outstanding command on the device
6085                  */
6086                 rval = mptsas_do_scsi_reset(mpt, devhdl);
6087                 if (rval) {
6088                         NDBG20(("mptsas%d handle_topo_change to reset target "
6089                             "before offline devhdl:%x, phymask:%x, rval:%x",
6090                             mpt->m_instance, ptgt->m_devhdl,
6091                             ptgt->m_addr.mta_phymask, rval));
6092                 }
6093 
6094                 mutex_exit(&mpt->m_mutex);
6095 
6096                 ndi_devi_enter(scsi_vhci_dip, &circ);
6097                 ndi_devi_enter(parent, &circ1);
6098                 rval = mptsas_offline_target(parent, addr);
6099                 ndi_devi_exit(parent, circ1);
6100                 ndi_devi_exit(scsi_vhci_dip, circ);
6101                 NDBG20(("mptsas%d handle_topo_change to offline devhdl:%x, "
6102                     "phymask:%x, rval:%x", mpt->m_instance,
6103                     ptgt->m_devhdl, ptgt->m_addr.mta_phymask, rval));
6104 
6105                 kmem_free(addr, SCSI_MAXNAMELEN);
6106 
6107                 /*
6108                  * Clear parent's props for SMHBA support
6109                  */
6110                 flags = topo_node->flags;
6111                 if (flags == MPTSAS_TOPO_FLAG_DIRECT_ATTACHED_DEVICE) {
6112                         bzero(attached_wwnstr, sizeof (attached_wwnstr));
6113                         if (ddi_prop_update_string(DDI_DEV_T_NONE, parent,
6114                             SCSI_ADDR_PROP_ATTACHED_PORT, attached_wwnstr) !=
6115                             DDI_PROP_SUCCESS) {
6116                                 (void) ddi_prop_remove(DDI_DEV_T_NONE, parent,
6117                                     SCSI_ADDR_PROP_ATTACHED_PORT);
6118                                 mptsas_log(mpt, CE_WARN, "mptsas attached port "
6119                                     "prop update failed");
6120                                 break;
6121                         }
6122                         if (ddi_prop_update_int(DDI_DEV_T_NONE, parent,
6123                             MPTSAS_NUM_PHYS, 0) !=
6124                             DDI_PROP_SUCCESS) {
6125                                 (void) ddi_prop_remove(DDI_DEV_T_NONE, parent,
6126                                     MPTSAS_NUM_PHYS);
6127                                 mptsas_log(mpt, CE_WARN, "mptsas num phys "
6128                                     "prop update failed");
6129                                 break;
6130                         }
6131                         if (ddi_prop_update_int(DDI_DEV_T_NONE, parent,
6132                             MPTSAS_VIRTUAL_PORT, 1) !=
6133                             DDI_PROP_SUCCESS) {
6134                                 (void) ddi_prop_remove(DDI_DEV_T_NONE, parent,
6135                                     MPTSAS_VIRTUAL_PORT);
6136                                 mptsas_log(mpt, CE_WARN, "mptsas virtual port "
6137                                     "prop update failed");
6138                                 break;
6139                         }
6140                 }
6141 
6142                 mutex_enter(&mpt->m_mutex);
6143                 ptgt->m_led_status = 0;
6144                 (void) mptsas_flush_led_status(mpt, ptgt);
6145                 if (rval == DDI_SUCCESS) {
6146                         refhash_remove(mpt->m_targets, ptgt);
6147                         ptgt = NULL;
6148                 } else {
6149                         /*
6150                          * clean DR_INTRANSITION flag to allow I/O down to
6151                          * PHCI driver since failover finished.
6152                          * Invalidate the devhdl
6153                          */
6154                         ptgt->m_devhdl = MPTSAS_INVALID_DEVHDL;
6155                         ptgt->m_tgt_unconfigured = 0;
6156                         mutex_enter(&mpt->m_tx_waitq_mutex);
6157                         ptgt->m_dr_flag = MPTSAS_DR_INACTIVE;
6158                         mutex_exit(&mpt->m_tx_waitq_mutex);
6159                 }
6160 


6161                 /*
6162                  * Send SAS IO Unit Control to free the dev handle
6163                  */
6164                 if ((flags == MPTSAS_TOPO_FLAG_DIRECT_ATTACHED_DEVICE) ||
6165                     (flags == MPTSAS_TOPO_FLAG_EXPANDER_ATTACHED_DEVICE)) {
6166                         rval = mptsas_free_devhdl(mpt, devhdl);
6167 
6168                         NDBG20(("mptsas%d handle_topo_change to remove "
6169                             "devhdl:%x, rval:%x", mpt->m_instance, devhdl,
6170                             rval));
6171                 }
6172 
6173                 break;
6174         }
6175         case MPTSAS_TOPO_FLAG_REMOVE_HANDLE:
6176         {
6177                 devhdl = topo_node->devhdl;

6178                 /*
6179                  * If this is the remove handle event, do a reset first.
6180                  */
6181                 if (topo_node->event == MPTSAS_TOPO_FLAG_REMOVE_HANDLE) {
6182                         rval = mptsas_do_scsi_reset(mpt, devhdl);
6183                         if (rval) {
6184                                 NDBG20(("mpt%d reset target before remove "
6185                                     "devhdl:%x, rval:%x", mpt->m_instance,
6186                                     devhdl, rval));
6187                         }
6188                 }
6189 
6190                 /*
6191                  * Send SAS IO Unit Control to free the dev handle
6192                  */
6193                 rval = mptsas_free_devhdl(mpt, devhdl);
6194                 NDBG20(("mptsas%d handle_topo_change to remove "
6195                     "devhdl:%x, rval:%x", mpt->m_instance, devhdl,
6196                     rval));
6197                 break;
6198         }
6199         case MPTSAS_DR_EVENT_RECONFIG_SMP:
6200         {
6201                 mptsas_smp_t smp;
6202                 dev_info_t *smpdip;
6203 
6204                 devhdl = topo_node->devhdl;
6205 
6206                 page_address = (MPI2_SAS_EXPAND_PGAD_FORM_HNDL &
6207                     MPI2_SAS_EXPAND_PGAD_FORM_MASK) | (uint32_t)devhdl;
6208                 rval = mptsas_get_sas_expander_page0(mpt, page_address, &smp);
6209                 if (rval != DDI_SUCCESS) {
6210                         mptsas_log(mpt, CE_WARN, "failed to online smp, "
6211                             "handle %x", devhdl);
6212                         return;
6213                 }
6214 


6267                                 mptsas_log(mpt, CE_WARN, "mptsas num phys"
6268                                     "prop update failed");
6269                                 return;
6270                         }
6271                         /*
6272                          * Clear parent's attached-port props
6273                          */
6274                         bzero(attached_wwnstr, sizeof (attached_wwnstr));
6275                         if (ddi_prop_update_string(DDI_DEV_T_NONE, parent,
6276                             SCSI_ADDR_PROP_ATTACHED_PORT, attached_wwnstr) !=
6277                             DDI_PROP_SUCCESS) {
6278                                 (void) ddi_prop_remove(DDI_DEV_T_NONE, parent,
6279                                     SCSI_ADDR_PROP_ATTACHED_PORT);
6280                                 mptsas_log(mpt, CE_WARN, "mptsas attached port "
6281                                     "prop update failed");
6282                                 return;
6283                         }
6284                 }
6285 
6286                 mutex_enter(&mpt->m_mutex);
6287                 NDBG20(("mptsas%d handle_topo_change to remove devhdl:%x, "
6288                     "rval:%x", mpt->m_instance, psmp->m_devhdl, rval));
6289                 if (rval == DDI_SUCCESS) {
6290                         refhash_remove(mpt->m_smp_targets, psmp);
6291                 } else {
6292                         psmp->m_devhdl = MPTSAS_INVALID_DEVHDL;
6293                 }
6294 
6295                 bzero(attached_wwnstr, sizeof (attached_wwnstr));
6296 
6297                 break;
6298         }
6299         default:
6300                 return;
6301         }
6302 }
6303 
6304 /*
6305  * Record the event if its type is enabled in mpt instance by ioctl.
6306  */
6307 static void
6308 mptsas_record_event(void *args)
6309 {
6310         m_replyh_arg_t                  *replyh_arg;
6311         pMpi2EventNotificationReply_t   eventreply;
6312         uint32_t                        event, rfm;
6313         mptsas_t                        *mpt;
6314         int                             i, j;
6315         uint16_t                        event_data_len;
6316         boolean_t                       sendAEN = FALSE;
6317 
6318         replyh_arg = (m_replyh_arg_t *)args;
6319         rfm = replyh_arg->rfm;
6320         mpt = replyh_arg->mpt;
6321 
6322         eventreply = (pMpi2EventNotificationReply_t)
6323             (mpt->m_reply_frame + (rfm - mpt->m_reply_frame_dma_addr));

6324         event = ddi_get16(mpt->m_acc_reply_frame_hdl, &eventreply->Event);
6325 
6326 
6327         /*
6328          * Generate a system event to let anyone who cares know that a
6329          * LOG_ENTRY_ADDED event has occurred.  This is sent no matter what the
6330          * event mask is set to.
6331          */
6332         if (event == MPI2_EVENT_LOG_ENTRY_ADDED) {
6333                 sendAEN = TRUE;
6334         }
6335 
6336         /*
6337          * Record the event only if it is not masked.  Determine which dword
6338          * and bit of event mask to test.
6339          */
6340         i = (uint8_t)(event / 32);
6341         j = (uint8_t)(event % 32);
6342         if ((i < 4) && ((1 << j) & mpt->m_event_mask[i])) {
6343                 i = mpt->m_event_index;


6391  * return value:
6392  * DDI_SUCCESS: The event is handled by this func
6393  * DDI_FAILURE: Event is not handled
6394  */
6395 static int
6396 mptsas_handle_event_sync(void *args)
6397 {
6398         m_replyh_arg_t                  *replyh_arg;
6399         pMpi2EventNotificationReply_t   eventreply;
6400         uint32_t                        event, rfm;
6401         mptsas_t                        *mpt;
6402         uint_t                          iocstatus;
6403 
6404         replyh_arg = (m_replyh_arg_t *)args;
6405         rfm = replyh_arg->rfm;
6406         mpt = replyh_arg->mpt;
6407 
6408         ASSERT(mutex_owned(&mpt->m_mutex));
6409 
6410         eventreply = (pMpi2EventNotificationReply_t)
6411             (mpt->m_reply_frame + (rfm - mpt->m_reply_frame_dma_addr));

6412         event = ddi_get16(mpt->m_acc_reply_frame_hdl, &eventreply->Event);
6413 
6414         if (iocstatus = ddi_get16(mpt->m_acc_reply_frame_hdl,
6415             &eventreply->IOCStatus)) {
6416                 if (iocstatus == MPI2_IOCSTATUS_FLAG_LOG_INFO_AVAILABLE) {
6417                         mptsas_log(mpt, CE_WARN,
6418                             "!mptsas_handle_event_sync: IOCStatus=0x%x, "
6419                             "IOCLogInfo=0x%x", iocstatus,

6420                             ddi_get32(mpt->m_acc_reply_frame_hdl,
6421                             &eventreply->IOCLogInfo));
6422                 } else {
6423                         mptsas_log(mpt, CE_WARN,
6424                             "mptsas_handle_event_sync: IOCStatus=0x%x, "
6425                             "IOCLogInfo=0x%x", iocstatus,

6426                             ddi_get32(mpt->m_acc_reply_frame_hdl,
6427                             &eventreply->IOCLogInfo));
6428                 }
6429         }
6430 
6431         /*
6432          * figure out what kind of event we got and handle accordingly
6433          */
6434         switch (event) {
6435         case MPI2_EVENT_SAS_TOPOLOGY_CHANGE_LIST:
6436         {
6437                 pMpi2EventDataSasTopologyChangeList_t   sas_topo_change_list;
6438                 uint8_t                         num_entries, expstatus, phy;
6439                 uint8_t                         phystatus, physport, state, i;
6440                 uint8_t                         start_phy_num, link_rate;
6441                 uint16_t                        dev_handle, reason_code;
6442                 uint16_t                        enc_handle, expd_handle;
6443                 char                            string[80], curr[80], prev[80];
6444                 mptsas_topo_change_list_t       *topo_head = NULL;
6445                 mptsas_topo_change_list_t       *topo_tail = NULL;


6540                         dev_handle = ddi_get16(mpt->m_acc_reply_frame_hdl,
6541                             &sas_topo_change_list->PHY[i].AttachedDevHandle);
6542                         reason_code = phystatus & MPI2_EVENT_SAS_TOPO_RC_MASK;
6543                         /*
6544                          * Filter out processing of Phy Vacant Status unless
6545                          * the reason code is "Not Responding".  Process all
6546                          * other combinations of Phy Status and Reason Codes.
6547                          */
6548                         if ((phystatus &
6549                             MPI2_EVENT_SAS_TOPO_PHYSTATUS_VACANT) &&
6550                             (reason_code !=
6551                             MPI2_EVENT_SAS_TOPO_RC_TARG_NOT_RESPONDING)) {
6552                                 continue;
6553                         }
6554                         curr[0] = 0;
6555                         prev[0] = 0;
6556                         string[0] = 0;
6557                         switch (reason_code) {
6558                         case MPI2_EVENT_SAS_TOPO_RC_TARG_ADDED:
6559                         {
6560                                 NDBG20(("mptsas%d phy %d physical_port %d "
6561                                     "dev_handle %d added", mpt->m_instance, phy,
6562                                     physport, dev_handle));
6563                                 link_rate = ddi_get8(mpt->m_acc_reply_frame_hdl,
6564                                     &sas_topo_change_list->PHY[i].LinkRate);
6565                                 state = (link_rate &
6566                                     MPI2_EVENT_SAS_TOPO_LR_CURRENT_MASK) >>
6567                                     MPI2_EVENT_SAS_TOPO_LR_CURRENT_SHIFT;
6568                                 switch (state) {
6569                                 case MPI2_EVENT_SAS_TOPO_LR_PHY_DISABLED:
6570                                         (void) sprintf(curr, "is disabled");
6571                                         break;
6572                                 case MPI2_EVENT_SAS_TOPO_LR_NEGOTIATION_FAILED:
6573                                         (void) sprintf(curr, "is offline, "
6574                                             "failed speed negotiation");
6575                                         break;
6576                                 case MPI2_EVENT_SAS_TOPO_LR_SATA_OOB_COMPLETE:
6577                                         (void) sprintf(curr, "SATA OOB "
6578                                             "complete");
6579                                         break;
6580                                 case SMP_RESET_IN_PROGRESS:
6581                                         (void) sprintf(curr, "SMP reset in "
6582                                             "progress");
6583                                         break;
6584                                 case MPI2_EVENT_SAS_TOPO_LR_RATE_1_5:
6585                                         (void) sprintf(curr, "is online at "
6586                                             "1.5 Gbps");
6587                                         break;
6588                                 case MPI2_EVENT_SAS_TOPO_LR_RATE_3_0:
6589                                         (void) sprintf(curr, "is online at 3.0 "
6590                                             "Gbps");
6591                                         break;
6592                                 case MPI2_EVENT_SAS_TOPO_LR_RATE_6_0:
6593                                         (void) sprintf(curr, "is online at 6.0 "
6594                                             "Gbps");
6595                                         break;




6596                                 default:
6597                                         (void) sprintf(curr, "state is "
6598                                             "unknown");
6599                                         break;
6600                                 }
6601                                 /*
6602                                  * New target device added into the system.
6603                                  * Set association flag according to if an
6604                                  * expander is used or not.
6605                                  */
6606                                 exp_flag =
6607                                     MPTSAS_TOPO_FLAG_EXPANDER_ATTACHED_DEVICE;
6608                                 if (flags ==
6609                                     MPTSAS_TOPO_FLAG_EXPANDER_ASSOCIATED) {
6610                                         flags = exp_flag;
6611                                 }
6612                                 topo_node = kmem_zalloc(
6613                                     sizeof (mptsas_topo_change_list_t),
6614                                     KM_SLEEP);
6615                                 topo_node->mpt = mpt;


6622                                          * device. So driver use PHY to decide
6623                                          * which iport is associated
6624                                          */
6625                                         physport = phy;
6626                                         mpt->m_port_chng = 1;
6627                                 }
6628                                 topo_node->un.physport = physport;
6629                                 topo_node->devhdl = dev_handle;
6630                                 topo_node->flags = flags;
6631                                 topo_node->object = NULL;
6632                                 if (topo_head == NULL) {
6633                                         topo_head = topo_tail = topo_node;
6634                                 } else {
6635                                         topo_tail->next = topo_node;
6636                                         topo_tail = topo_node;
6637                                 }
6638                                 break;
6639                         }
6640                         case MPI2_EVENT_SAS_TOPO_RC_TARG_NOT_RESPONDING:
6641                         {
6642                                 NDBG20(("mptsas%d phy %d physical_port %d "
6643                                     "dev_handle %d removed", mpt->m_instance,
6644                                     phy, physport, dev_handle));
6645                                 /*
6646                                  * Set association flag according to if an
6647                                  * expander is used or not.
6648                                  */
6649                                 exp_flag =
6650                                     MPTSAS_TOPO_FLAG_EXPANDER_ATTACHED_DEVICE;
6651                                 if (flags ==
6652                                     MPTSAS_TOPO_FLAG_EXPANDER_ASSOCIATED) {
6653                                         flags = exp_flag;
6654                                 }
6655                                 /*
6656                                  * Target device is removed from the system
6657                                  * Before the device is really offline from
6658                                  * from system.
6659                                  */
6660                                 ptgt = refhash_linear_search(mpt->m_targets,
6661                                     mptsas_target_eval_devhdl, &dev_handle);
6662                                 /*
6663                                  * If ptgt is NULL here, it means that the
6664                                  * DevHandle is not in the hash table.  This is
6665                                  * reasonable sometimes.  For example, if a
6666                                  * disk was pulled, then added, then pulled
6667                                  * again, the disk will not have been put into
6668                                  * the hash table because the add event will
6669                                  * have an invalid phymask.  BUT, this does not
6670                                  * mean that the DevHandle is invalid.  The
6671                                  * controller will still have a valid DevHandle
6672                                  * that must be removed.  To do this, use the
6673                                  * MPTSAS_TOPO_FLAG_REMOVE_HANDLE event.
6674                                  */
6675                                 if (ptgt == NULL) {
6676                                         topo_node = kmem_zalloc(
6677                                             sizeof (mptsas_topo_change_list_t),
6678                                             KM_SLEEP);
6679                                         topo_node->mpt = mpt;
6680                                         topo_node->un.phymask = 0;
6681                                         topo_node->event =
6682                                             MPTSAS_TOPO_FLAG_REMOVE_HANDLE;
6683                                         topo_node->devhdl = dev_handle;
6684                                         topo_node->flags = flags;
6685                                         topo_node->object = NULL;
6686                                         if (topo_head == NULL) {
6687                                                 topo_head = topo_tail =
6688                                                     topo_node;
6689                                         } else {
6690                                                 topo_tail->next = topo_node;
6691                                                 topo_tail = topo_node;
6692                                         }
6693                                         break;
6694                                 }
6695 
6696                                 /*
6697                                  * Update DR flag immediately avoid I/O failure
6698                                  * before failover finish. Pay attention to the
6699                                  * mutex protect, we need grab m_tx_waitq_mutex
6700                                  * during set m_dr_flag because we won't add
6701                                  * the following command into waitq, instead,
6702                                  * we need return TRAN_BUSY in the tran_start
6703                                  * context.
6704                                  */
6705                                 mutex_enter(&mpt->m_tx_waitq_mutex);
6706                                 ptgt->m_dr_flag = MPTSAS_DR_INTRANSITION;
6707                                 mutex_exit(&mpt->m_tx_waitq_mutex);
6708 
6709                                 topo_node = kmem_zalloc(
6710                                     sizeof (mptsas_topo_change_list_t),
6711                                     KM_SLEEP);
6712                                 topo_node->mpt = mpt;
6713                                 topo_node->un.phymask =
6714                                     ptgt->m_addr.mta_phymask;
6715                                 topo_node->event =
6716                                     MPTSAS_DR_EVENT_OFFLINE_TARGET;
6717                                 topo_node->devhdl = dev_handle;
6718                                 topo_node->flags = flags;
6719                                 topo_node->object = NULL;
6720                                 if (topo_head == NULL) {
6721                                         topo_head = topo_tail = topo_node;
6722                                 } else {
6723                                         topo_tail->next = topo_node;
6724                                         topo_tail = topo_node;
6725                                 }
6726                                 break;
6727                         }


6779                                             (enc_handle == 1)) {
6780                                                 mpt->m_port_chng = 1;
6781                                         }
6782                                         mptsas_smhba_log_sysevent(mpt,
6783                                             ESC_SAS_PHY_EVENT,
6784                                             SAS_PHY_ONLINE,
6785                                             &mpt->m_phy_info[i].smhba_info);
6786                                         break;
6787                                 case MPI2_EVENT_SAS_TOPO_LR_RATE_6_0:
6788                                         (void) sprintf(curr, "is online at "
6789                                             "6.0 Gbps");
6790                                         if ((expd_handle == 0) &&
6791                                             (enc_handle == 1)) {
6792                                                 mpt->m_port_chng = 1;
6793                                         }
6794                                         mptsas_smhba_log_sysevent(mpt,
6795                                             ESC_SAS_PHY_EVENT,
6796                                             SAS_PHY_ONLINE,
6797                                             &mpt->m_phy_info[i].smhba_info);
6798                                         break;












6799                                 default:
6800                                         (void) sprintf(curr, "state is "
6801                                             "unknown");
6802                                         break;
6803                                 }
6804 
6805                                 state = (link_rate &
6806                                     MPI2_EVENT_SAS_TOPO_LR_PREV_MASK) >>
6807                                     MPI2_EVENT_SAS_TOPO_LR_PREV_SHIFT;
6808                                 switch (state) {
6809                                 case MPI2_EVENT_SAS_TOPO_LR_PHY_DISABLED:
6810                                         (void) sprintf(prev, ", was disabled");
6811                                         break;
6812                                 case MPI2_EVENT_SAS_TOPO_LR_NEGOTIATION_FAILED:
6813                                         (void) sprintf(prev, ", was offline, "
6814                                             "failed speed negotiation");
6815                                         break;
6816                                 case MPI2_EVENT_SAS_TOPO_LR_SATA_OOB_COMPLETE:
6817                                         (void) sprintf(prev, ", was SATA OOB "
6818                                             "complete");
6819                                         break;
6820                                 case SMP_RESET_IN_PROGRESS:
6821                                         (void) sprintf(prev, ", was SMP reset "
6822                                             "in progress");
6823                                         break;
6824                                 case MPI2_EVENT_SAS_TOPO_LR_RATE_1_5:
6825                                         (void) sprintf(prev, ", was online at "
6826                                             "1.5 Gbps");
6827                                         break;
6828                                 case MPI2_EVENT_SAS_TOPO_LR_RATE_3_0:
6829                                         (void) sprintf(prev, ", was online at "
6830                                             "3.0 Gbps");
6831                                         break;
6832                                 case MPI2_EVENT_SAS_TOPO_LR_RATE_6_0:
6833                                         (void) sprintf(prev, ", was online at "
6834                                             "6.0 Gbps");
6835                                         break;




6836                                 default:
6837                                 break;
6838                                 }
6839                                 (void) sprintf(&string[strlen(string)], "link "
6840                                     "changed, ");
6841                                 break;
6842                         case MPI2_EVENT_SAS_TOPO_RC_NO_CHANGE:
6843                                 continue;
6844                         case MPI2_EVENT_SAS_TOPO_RC_DELAY_NOT_RESPONDING:
6845                                 (void) sprintf(&string[strlen(string)],
6846                                     "target not responding, delaying "
6847                                     "removal");
6848                                 break;
6849                         }
6850                         NDBG20(("mptsas%d phy %d DevHandle %x, %s%s%s\n",
6851                             mpt->m_instance, phy, dev_handle, string, curr,
6852                             prev));
6853                 }
6854                 if (topo_head != NULL) {
6855                         /*
6856                          * Launch DR taskq to handle topology change
6857                          */
6858                         if ((ddi_taskq_dispatch(mpt->m_dr_taskq,
6859                             mptsas_handle_dr, (void *)topo_head,
6860                             DDI_NOSLEEP)) != DDI_SUCCESS) {






6861                                 mptsas_log(mpt, CE_NOTE, "mptsas start taskq "
6862                                     "for handle SAS DR event failed. \n");
6863                         }
6864                 }
6865                 break;
6866         }
6867         case MPI2_EVENT_IR_CONFIGURATION_CHANGE_LIST:
6868         {
6869                 Mpi2EventDataIrConfigChangeList_t       *irChangeList;
6870                 mptsas_topo_change_list_t               *topo_head = NULL;
6871                 mptsas_topo_change_list_t               *topo_tail = NULL;
6872                 mptsas_topo_change_list_t               *topo_node = NULL;
6873                 mptsas_target_t                         *ptgt;
6874                 uint8_t                                 num_entries, i, reason;
6875                 uint16_t                                volhandle, diskhandle;
6876 
6877                 irChangeList = (pMpi2EventDataIrConfigChangeList_t)
6878                     eventreply->EventData;
6879                 num_entries = ddi_get8(mpt->m_acc_reply_frame_hdl,
6880                     &irChangeList->NumElements);
6881 
6882                 NDBG20(("mptsas%d IR_CONFIGURATION_CHANGE_LIST event received",
6883                     mpt->m_instance));
6884 
6885                 for (i = 0; i < num_entries; i++) {
6886                         reason = ddi_get8(mpt->m_acc_reply_frame_hdl,
6887                             &irChangeList->ConfigElement[i].ReasonCode);
6888                         volhandle = ddi_get16(mpt->m_acc_reply_frame_hdl,
6889                             &irChangeList->ConfigElement[i].VolDevHandle);
6890                         diskhandle = ddi_get16(mpt->m_acc_reply_frame_hdl,
6891                             &irChangeList->ConfigElement[i].PhysDiskDevHandle);
6892 
6893                         switch (reason) {
6894                         case MPI2_EVENT_IR_CHANGE_RC_ADDED:
6895                         case MPI2_EVENT_IR_CHANGE_RC_VOLUME_CREATED:
6896                         {
6897                                 NDBG20(("mptsas %d volume added\n",
6898                                     mpt->m_instance));
6899 
6900                                 topo_node = kmem_zalloc(
6901                                     sizeof (mptsas_topo_change_list_t),
6902                                     KM_SLEEP);


6918                                 break;
6919                         }
6920                         case MPI2_EVENT_IR_CHANGE_RC_REMOVED:
6921                         case MPI2_EVENT_IR_CHANGE_RC_VOLUME_DELETED:
6922                         {
6923                                 NDBG20(("mptsas %d volume deleted\n",
6924                                     mpt->m_instance));
6925                                 ptgt = refhash_linear_search(mpt->m_targets,
6926                                     mptsas_target_eval_devhdl, &volhandle);
6927                                 if (ptgt == NULL)
6928                                         break;
6929 
6930                                 /*
6931                                  * Clear any flags related to volume
6932                                  */
6933                                 (void) mptsas_delete_volume(mpt, volhandle);
6934 
6935                                 /*
6936                                  * Update DR flag immediately avoid I/O failure
6937                                  */
6938                                 mutex_enter(&mpt->m_tx_waitq_mutex);
6939                                 ptgt->m_dr_flag = MPTSAS_DR_INTRANSITION;
6940                                 mutex_exit(&mpt->m_tx_waitq_mutex);
6941 
6942                                 topo_node = kmem_zalloc(
6943                                     sizeof (mptsas_topo_change_list_t),
6944                                     KM_SLEEP);
6945                                 topo_node->mpt = mpt;
6946                                 topo_node->un.phymask =
6947                                     ptgt->m_addr.mta_phymask;
6948                                 topo_node->event =
6949                                     MPTSAS_DR_EVENT_OFFLINE_TARGET;
6950                                 topo_node->devhdl = volhandle;
6951                                 topo_node->flags =
6952                                     MPTSAS_TOPO_FLAG_RAID_ASSOCIATED;
6953                                 topo_node->object = (void *)ptgt;
6954                                 if (topo_head == NULL) {
6955                                         topo_head = topo_tail = topo_node;
6956                                 } else {
6957                                         topo_tail->next = topo_node;
6958                                         topo_tail = topo_node;
6959                                 }
6960                                 break;
6961                         }
6962                         case MPI2_EVENT_IR_CHANGE_RC_PD_CREATED:
6963                         case MPI2_EVENT_IR_CHANGE_RC_HIDE:
6964                         {
6965                                 ptgt = refhash_linear_search(mpt->m_targets,
6966                                     mptsas_target_eval_devhdl, &diskhandle);
6967                                 if (ptgt == NULL)
6968                                         break;
6969 
6970                                 /*
6971                                  * Update DR flag immediately avoid I/O failure
6972                                  */
6973                                 mutex_enter(&mpt->m_tx_waitq_mutex);
6974                                 ptgt->m_dr_flag = MPTSAS_DR_INTRANSITION;
6975                                 mutex_exit(&mpt->m_tx_waitq_mutex);
6976 
6977                                 topo_node = kmem_zalloc(
6978                                     sizeof (mptsas_topo_change_list_t),
6979                                     KM_SLEEP);
6980                                 topo_node->mpt = mpt;
6981                                 topo_node->un.phymask =
6982                                     ptgt->m_addr.mta_phymask;
6983                                 topo_node->event =
6984                                     MPTSAS_DR_EVENT_OFFLINE_TARGET;
6985                                 topo_node->devhdl = diskhandle;
6986                                 topo_node->flags =
6987                                     MPTSAS_TOPO_FLAG_RAID_PHYSDRV_ASSOCIATED;
6988                                 topo_node->object = (void *)ptgt;
6989                                 if (topo_head == NULL) {
6990                                         topo_head = topo_tail = topo_node;
6991                                 } else {
6992                                         topo_tail->next = topo_node;
6993                                         topo_tail = topo_node;
6994                                 }
6995                                 break;


7019                                 if (topo_head == NULL) {
7020                                         topo_head = topo_tail = topo_node;
7021                                 } else {
7022                                         topo_tail->next = topo_node;
7023                                         topo_tail = topo_node;
7024                                 }
7025                                 break;
7026                         }
7027                         default:
7028                                 break;
7029                         }
7030                 }
7031 
7032                 if (topo_head != NULL) {
7033                         /*
7034                          * Launch DR taskq to handle topology change
7035                          */
7036                         if ((ddi_taskq_dispatch(mpt->m_dr_taskq,
7037                             mptsas_handle_dr, (void *)topo_head,
7038                             DDI_NOSLEEP)) != DDI_SUCCESS) {






7039                                 mptsas_log(mpt, CE_NOTE, "mptsas start taskq "
7040                                     "for handle SAS DR event failed. \n");
7041                         }
7042                 }
7043                 break;
7044         }
7045         default:
7046                 return (DDI_FAILURE);
7047         }
7048 
7049         return (DDI_SUCCESS);
7050 }
7051 
7052 /*
7053  * handle events from ioc
7054  */
7055 static void
7056 mptsas_handle_event(void *args)
7057 {
7058         m_replyh_arg_t                  *replyh_arg;


7061         uint32_t                        status;
7062         uint8_t                         port;
7063         mptsas_t                        *mpt;
7064         uint_t                          iocstatus;
7065 
7066         replyh_arg = (m_replyh_arg_t *)args;
7067         rfm = replyh_arg->rfm;
7068         mpt = replyh_arg->mpt;
7069 
7070         mutex_enter(&mpt->m_mutex);
7071         /*
7072          * If HBA is being reset, drop incoming event.
7073          */
7074         if (mpt->m_in_reset) {
7075                 NDBG20(("dropping event received prior to reset"));
7076                 mutex_exit(&mpt->m_mutex);
7077                 return;
7078         }
7079 
7080         eventreply = (pMpi2EventNotificationReply_t)
7081             (mpt->m_reply_frame + (rfm - mpt->m_reply_frame_dma_addr));

7082         event = ddi_get16(mpt->m_acc_reply_frame_hdl, &eventreply->Event);
7083 
7084         if (iocstatus = ddi_get16(mpt->m_acc_reply_frame_hdl,
7085             &eventreply->IOCStatus)) {
7086                 if (iocstatus == MPI2_IOCSTATUS_FLAG_LOG_INFO_AVAILABLE) {
7087                         mptsas_log(mpt, CE_WARN,
7088                             "!mptsas_handle_event: IOCStatus=0x%x, "
7089                             "IOCLogInfo=0x%x", iocstatus,
7090                             ddi_get32(mpt->m_acc_reply_frame_hdl,
7091                             &eventreply->IOCLogInfo));
7092                 } else {
7093                         mptsas_log(mpt, CE_WARN,
7094                             "mptsas_handle_event: IOCStatus=0x%x, "
7095                             "IOCLogInfo=0x%x", iocstatus,
7096                             ddi_get32(mpt->m_acc_reply_frame_hdl,
7097                             &eventreply->IOCLogInfo));
7098                 }
7099         }
7100 
7101         /*
7102          * figure out what kind of event we got and handle accordingly
7103          */
7104         switch (event) {
7105         case MPI2_EVENT_LOG_ENTRY_ADDED:
7106                 break;
7107         case MPI2_EVENT_LOG_DATA:
7108                 iocloginfo = ddi_get32(mpt->m_acc_reply_frame_hdl,
7109                     &eventreply->IOCLogInfo);
7110                 NDBG20(("mptsas %d log info %x received.\n", mpt->m_instance,
7111                     iocloginfo));
7112                 break;
7113         case MPI2_EVENT_STATE_CHANGE:
7114                 NDBG20(("mptsas%d state change.", mpt->m_instance));
7115                 break;
7116         case MPI2_EVENT_HARD_RESET_RECEIVED:
7117                 NDBG20(("mptsas%d event change.", mpt->m_instance));
7118                 break;
7119         case MPI2_EVENT_SAS_DISCOVERY:
7120         {
7121                 MPI2_EVENT_DATA_SAS_DISCOVERY   *sasdiscovery;
7122                 char                            string[80];
7123                 uint8_t                         rc;
7124 
7125                 sasdiscovery =
7126                     (pMpi2EventDataSasDiscovery_t)eventreply->EventData;
7127 
7128                 rc = ddi_get8(mpt->m_acc_reply_frame_hdl,
7129                     &sasdiscovery->ReasonCode);
7130                 port = ddi_get8(mpt->m_acc_reply_frame_hdl,
7131                     &sasdiscovery->PhysicalPort);
7132                 status = ddi_get32(mpt->m_acc_reply_frame_hdl,
7133                     &sasdiscovery->DiscoveryStatus);
7134 
7135                 string[0] = 0;
7136                 switch (rc) {
7137                 case MPI2_EVENT_SAS_DISC_RC_STARTED:
7138                         (void) sprintf(string, "STARTING");
7139                         break;
7140                 case MPI2_EVENT_SAS_DISC_RC_COMPLETED:
7141                         (void) sprintf(string, "COMPLETED");
7142                         break;
7143                 default:
7144                         (void) sprintf(string, "UNKNOWN");
7145                         break;
7146                 }
7147 
7148                 NDBG20(("SAS DISCOVERY is %s for port %d, status %x", string,
7149                     port, status));
7150 
7151                 break;
7152         }
7153         case MPI2_EVENT_EVENT_CHANGE:
7154                 NDBG20(("mptsas%d event change.", mpt->m_instance));
7155                 break;
7156         case MPI2_EVENT_TASK_SET_FULL:
7157         {
7158                 pMpi2EventDataTaskSetFull_t     taskfull;
7159 
7160                 taskfull = (pMpi2EventDataTaskSetFull_t)eventreply->EventData;
7161 
7162                 NDBG20(("TASK_SET_FULL received for mptsas%d, depth %d\n",
7163                     mpt->m_instance,  ddi_get16(mpt->m_acc_reply_frame_hdl,
7164                     &taskfull->CurrentDepth)));
7165                 break;
7166         }
7167         case MPI2_EVENT_SAS_TOPOLOGY_CHANGE_LIST:
7168         {
7169                 /*
7170                  * SAS TOPOLOGY CHANGE LIST Event has already been handled
7171                  * in mptsas_handle_event_sync() of interrupt context
7172                  */
7173                 break;
7174         }
7175         case MPI2_EVENT_SAS_ENCL_DEVICE_STATUS_CHANGE:
7176         {
7177                 pMpi2EventDataSasEnclDevStatusChange_t  encstatus;
7178                 uint8_t                                 rc;
7179                 char                                    string[80];
7180 
7181                 encstatus = (pMpi2EventDataSasEnclDevStatusChange_t)
7182                     eventreply->EventData;
7183 
7184                 rc = ddi_get8(mpt->m_acc_reply_frame_hdl,
7185                     &encstatus->ReasonCode);
7186                 switch (rc) {
7187                 case MPI2_EVENT_SAS_ENCL_RC_ADDED:
7188                         (void) sprintf(string, "added");
7189                         break;
7190                 case MPI2_EVENT_SAS_ENCL_RC_NOT_RESPONDING:
7191                         (void) sprintf(string, ", not responding");
7192                         break;
7193                 default:
7194                 break;
7195                 }
7196                 NDBG20(("mptsas%d ENCLOSURE STATUS CHANGE for enclosure %x%s\n",
7197                     mpt->m_instance, ddi_get16(mpt->m_acc_reply_frame_hdl,

7198                     &encstatus->EnclosureHandle), string));
7199                 break;
7200         }
7201 
7202         /*
7203          * MPI2_EVENT_SAS_DEVICE_STATUS_CHANGE is handled by
7204          * mptsas_handle_event_sync,in here just send ack message.
7205          */
7206         case MPI2_EVENT_SAS_DEVICE_STATUS_CHANGE:
7207         {
7208                 pMpi2EventDataSasDeviceStatusChange_t   statuschange;
7209                 uint8_t                                 rc;
7210                 uint16_t                                devhdl;
7211                 uint64_t                                wwn = 0;
7212                 uint32_t                                wwn_lo, wwn_hi;
7213 
7214                 statuschange = (pMpi2EventDataSasDeviceStatusChange_t)
7215                     eventreply->EventData;
7216                 rc = ddi_get8(mpt->m_acc_reply_frame_hdl,
7217                     &statuschange->ReasonCode);


7302                     &irOpStatus->PercentComplete);
7303                 handle = ddi_get16(mpt->m_acc_reply_frame_hdl,
7304                     &irOpStatus->VolDevHandle);
7305 
7306                 switch (rc) {
7307                         case MPI2_EVENT_IR_RAIDOP_RESYNC:
7308                                 (void) sprintf(reason_str, "resync");
7309                                 break;
7310                         case MPI2_EVENT_IR_RAIDOP_ONLINE_CAP_EXPANSION:
7311                                 (void) sprintf(reason_str, "online capacity "
7312                                     "expansion");
7313                                 break;
7314                         case MPI2_EVENT_IR_RAIDOP_CONSISTENCY_CHECK:
7315                                 (void) sprintf(reason_str, "consistency check");
7316                                 break;
7317                         default:
7318                                 (void) sprintf(reason_str, "unknown reason %x",
7319                                     rc);
7320                 }
7321 
7322                 NDBG20(("mptsas%d raid operational status: (%s)"
7323                     "\thandle(0x%04x), percent complete(%d)\n",
7324                     mpt->m_instance, reason_str, handle, percent));
7325                 break;
7326         }
7327         case MPI2_EVENT_SAS_BROADCAST_PRIMITIVE:
7328         {
7329                 pMpi2EventDataSasBroadcastPrimitive_t   sas_broadcast;
7330                 uint8_t                                 phy_num;
7331                 uint8_t                                 primitive;
7332 
7333                 sas_broadcast = (pMpi2EventDataSasBroadcastPrimitive_t)
7334                     eventreply->EventData;
7335 
7336                 phy_num = ddi_get8(mpt->m_acc_reply_frame_hdl,
7337                     &sas_broadcast->PhyNum);
7338                 primitive = ddi_get8(mpt->m_acc_reply_frame_hdl,
7339                     &sas_broadcast->Primitive);
7340 
7341                 switch (primitive) {
7342                 case MPI2_EVENT_PRIMITIVE_CHANGE:


7371                         break;
7372                 case MPI2_EVENT_PRIMITIVE_RESERVED4:
7373                         mptsas_smhba_log_sysevent(mpt,
7374                             ESC_SAS_HBA_PORT_BROADCAST,
7375                             SAS_PORT_BROADCAST_D29_7,
7376                             &mpt->m_phy_info[phy_num].smhba_info);
7377                         break;
7378                 case MPI2_EVENT_PRIMITIVE_CHANGE0_RESERVED:
7379                         mptsas_smhba_log_sysevent(mpt,
7380                             ESC_SAS_HBA_PORT_BROADCAST,
7381                             SAS_PORT_BROADCAST_D24_0,
7382                             &mpt->m_phy_info[phy_num].smhba_info);
7383                         break;
7384                 case MPI2_EVENT_PRIMITIVE_CHANGE1_RESERVED:
7385                         mptsas_smhba_log_sysevent(mpt,
7386                             ESC_SAS_HBA_PORT_BROADCAST,
7387                             SAS_PORT_BROADCAST_D27_4,
7388                             &mpt->m_phy_info[phy_num].smhba_info);
7389                         break;
7390                 default:
7391                         NDBG20(("mptsas%d: unknown BROADCAST PRIMITIVE"
7392                             " %x received",
7393                             mpt->m_instance, primitive));
7394                         break;
7395                 }
7396                 NDBG20(("mptsas%d sas broadcast primitive: "
7397                     "\tprimitive(0x%04x), phy(%d) complete\n",
7398                     mpt->m_instance, primitive, phy_num));
7399                 break;
7400         }
7401         case MPI2_EVENT_IR_VOLUME:
7402         {
7403                 Mpi2EventDataIrVolume_t         *irVolume;
7404                 uint16_t                        devhandle;
7405                 uint32_t                        state;
7406                 int                             config, vol;
7407                 uint8_t                         found = FALSE;
7408 
7409                 irVolume = (pMpi2EventDataIrVolume_t)eventreply->EventData;
7410                 state = ddi_get32(mpt->m_acc_reply_frame_hdl,
7411                     &irVolume->NewValue);
7412                 devhandle = ddi_get16(mpt->m_acc_reply_frame_hdl,
7413                     &irVolume->VolDevHandle);
7414 
7415                 NDBG20(("EVENT_IR_VOLUME event is received"));
7416 


7582                             state == MPI2_RAID_PD_STATE_REBUILDING
7583                             ? "rebuilding" :
7584                             state == MPI2_RAID_PD_STATE_DEGRADED
7585                             ? "degraded" :
7586                             state == MPI2_RAID_PD_STATE_HOT_SPARE
7587                             ? "a hot spare" :
7588                             state == MPI2_RAID_PD_STATE_ONLINE
7589                             ? "online" :
7590                             state == MPI2_RAID_PD_STATE_OFFLINE
7591                             ? "offline" :
7592                             state == MPI2_RAID_PD_STATE_NOT_COMPATIBLE
7593                             ? "not compatible" :
7594                             state == MPI2_RAID_PD_STATE_NOT_CONFIGURED
7595                             ? "not configured" :
7596                             "state unknown");
7597                         break;
7598                 }
7599                 break;
7600         }
7601         default:
7602                 NDBG20(("mptsas%d: unknown event %x received",
7603                     mpt->m_instance, event));
7604                 break;
7605         }
7606 
7607         /*
7608          * Return the reply frame to the free queue.
7609          */
7610         ddi_put32(mpt->m_acc_free_queue_hdl,
7611             &((uint32_t *)(void *)mpt->m_free_queue)[mpt->m_free_index], rfm);
7612         (void) ddi_dma_sync(mpt->m_dma_free_queue_hdl, 0, 0,
7613             DDI_DMA_SYNC_FORDEV);
7614         if (++mpt->m_free_index == mpt->m_free_queue_depth) {
7615                 mpt->m_free_index = 0;
7616         }
7617         ddi_put32(mpt->m_datap, &mpt->m_reg->ReplyFreeHostIndex,
7618             mpt->m_free_index);
7619         mutex_exit(&mpt->m_mutex);
7620 }
7621 
7622 /*
7623  * invoked from timeout() to restart qfull cmds with throttle == 0
7624  */
7625 static void
7626 mptsas_restart_cmd(void *arg)
7627 {
7628         mptsas_t        *mpt = arg;
7629         mptsas_target_t *ptgt = NULL;
7630 
7631         mutex_enter(&mpt->m_mutex);
7632 
7633         mpt->m_restart_cmd_timeid = 0;
7634 
7635         for (ptgt = refhash_first(mpt->m_targets); ptgt != NULL;
7636             ptgt = refhash_next(mpt->m_targets, ptgt)) {

7637                 if (ptgt->m_reset_delay == 0) {
7638                         if (ptgt->m_t_throttle == QFULL_THROTTLE) {
7639                                 mptsas_set_throttle(mpt, ptgt,
7640                                     MAX_THROTTLE);
7641                         }
7642                 }

7643         }
7644         mptsas_restart_hba(mpt);
7645         mutex_exit(&mpt->m_mutex);
7646 }
7647 





























































7648 void
7649 mptsas_remove_cmd(mptsas_t *mpt, mptsas_cmd_t *cmd)
7650 {
7651         int             slot;
7652         mptsas_slots_t  *slots = mpt->m_active;
7653         int             t;
7654         mptsas_target_t *ptgt = cmd->cmd_tgt_addr;
7655 
7656         ASSERT(cmd != NULL);
7657         ASSERT(cmd->cmd_queued == FALSE);
7658 
7659         /*
7660          * Task Management cmds are removed in their own routines.  Also,
7661          * we don't want to modify timeout based on TM cmds.
7662          */
7663         if (cmd->cmd_flags & CFLAG_TM_CMD) {
7664                 return;
7665         }
7666 
7667         t = Tgt(cmd);
7668         slot = cmd->cmd_slot;
7669 
7670         /*
7671          * remove the cmd.
7672          */
7673         if (cmd == slots->m_slot[slot]) {
7674                 NDBG31(("mptsas_remove_cmd: removing cmd=0x%p", (void *)cmd));

7675                 slots->m_slot[slot] = NULL;
7676                 mpt->m_ncmds--;




7677 
7678                 /*
7679                  * only decrement per target ncmds if command
7680                  * has a target associated with it.
7681                  */
7682                 if ((cmd->cmd_flags & CFLAG_CMDIOC) == 0) {


7683                         ptgt->m_t_ncmds--;

7684                         /*
7685                          * reset throttle if we just ran an untagged command
7686                          * to a tagged target
7687                          */
7688                         if ((ptgt->m_t_ncmds == 0) &&
7689                             ((cmd->cmd_pkt_flags & FLAG_TAGMASK) == 0)) {
7690                                 mptsas_set_throttle(mpt, ptgt, MAX_THROTTLE);
7691                         }










7692                 }
7693 
7694         }
7695 
7696         /*
7697          * This is all we need to do for ioc commands.
7698          */
7699         if (cmd->cmd_flags & CFLAG_CMDIOC) {
7700                 mptsas_return_to_pool(mpt, cmd);
7701                 return;
7702         }
7703 
7704         /*
7705          * Figure out what to set tag Q timeout for...
7706          *
7707          * Optimize: If we have duplicate's of same timeout
7708          * we're using, then we'll use it again until we run
7709          * out of duplicates.  This should be the normal case
7710          * for block and raw I/O.
7711          * If no duplicates, we have to scan through tag que and
7712          * find the longest timeout value and use it.  This is
7713          * going to take a while...
7714          * Add 1 to m_n_normal to account for TM request.
7715          */
7716         if (cmd->cmd_pkt->pkt_time == ptgt->m_timebase) {
7717                 if (--(ptgt->m_dups) == 0) {
7718                         if (ptgt->m_t_ncmds) {
7719                                 mptsas_cmd_t *ssp;
7720                                 uint_t n = 0;
7721                                 ushort_t nslots = (slots->m_n_normal + 1);
7722                                 ushort_t i;
7723                                 /*
7724                                  * This crude check assumes we don't do
7725                                  * this too often which seems reasonable
7726                                  * for block and raw I/O.
7727                                  */
7728                                 for (i = 0; i < nslots; i++) {
7729                                         ssp = slots->m_slot[i];
7730                                         if (ssp && (Tgt(ssp) == t) &&
7731                                             (ssp->cmd_pkt->pkt_time > n)) {
7732                                                 n = ssp->cmd_pkt->pkt_time;
7733                                                 ptgt->m_dups = 1;
7734                                         } else if (ssp && (Tgt(ssp) == t) &&
7735                                             (ssp->cmd_pkt->pkt_time == n)) {
7736                                                 ptgt->m_dups++;
7737                                         }
7738                                 }
7739                                 ptgt->m_timebase = n;
7740                         } else {
7741                                 ptgt->m_dups = 0;
7742                                 ptgt->m_timebase = 0;
7743                         }
7744                 }
7745         }
7746         ptgt->m_timeout = ptgt->m_timebase;
7747 
7748         ASSERT(cmd != slots->m_slot[cmd->cmd_slot]);
7749 }
7750 
7751 /*
7752  * accept all cmds on the tx_waitq if any and then
7753  * start a fresh request from the top of the device queue.
7754  *
7755  * since there are always cmds queued on the tx_waitq, and rare cmds on
7756  * the instance waitq, so this function should not be invoked in the ISR,
7757  * the mptsas_restart_waitq() is invoked in the ISR instead. otherwise, the
7758  * burden belongs to the IO dispatch CPUs is moved the interrupt CPU.
7759  */
7760 static void
7761 mptsas_restart_hba(mptsas_t *mpt)
7762 {
7763         ASSERT(mutex_owned(&mpt->m_mutex));
7764 
7765         mutex_enter(&mpt->m_tx_waitq_mutex);
7766         if (mpt->m_tx_waitq) {
7767                 mptsas_accept_tx_waitq(mpt);
7768         }
7769         mutex_exit(&mpt->m_tx_waitq_mutex);
7770         mptsas_restart_waitq(mpt);
7771 }
7772 
7773 /*
7774  * start a fresh request from the top of the device queue
7775  */
7776 static void
7777 mptsas_restart_waitq(mptsas_t *mpt)
7778 {
7779         mptsas_cmd_t    *cmd, *next_cmd;
7780         mptsas_target_t *ptgt = NULL;
7781 
7782         NDBG1(("mptsas_restart_waitq: mpt=0x%p", (void *)mpt));
7783 
7784         ASSERT(mutex_owned(&mpt->m_mutex));
7785 
7786         /*
7787          * If there is a reset delay, don't start any cmds.  Otherwise, start
7788          * as many cmds as possible.
7789          * Since SMID 0 is reserved and the TM slot is reserved, the actual max


7817                                 mptsas_start_config_page_access(mpt, cmd);
7818                         }
7819                         cmd = next_cmd;
7820                         continue;
7821                 }
7822                 if (cmd->cmd_flags & CFLAG_FW_DIAG) {
7823                         if (mptsas_save_cmd(mpt, cmd) == TRUE) {
7824                                 /*
7825                                  * Send the FW Diag request and delete if from
7826                                  * the waitq.
7827                                  */
7828                                 cmd->cmd_flags |= CFLAG_PREPARED;
7829                                 mptsas_waitq_delete(mpt, cmd);
7830                                 mptsas_start_diag(mpt, cmd);
7831                         }
7832                         cmd = next_cmd;
7833                         continue;
7834                 }
7835 
7836                 ptgt = cmd->cmd_tgt_addr;
7837                 if (ptgt && (ptgt->m_t_throttle == DRAIN_THROTTLE) &&


7838                     (ptgt->m_t_ncmds == 0)) {
7839                         mptsas_set_throttle(mpt, ptgt, MAX_THROTTLE);
7840                 }
7841                 if ((mpt->m_ncmds <= (mpt->m_max_requests - 2)) &&
7842                     (ptgt && (ptgt->m_reset_delay == 0)) &&
7843                     (ptgt && (ptgt->m_t_ncmds <
7844                     ptgt->m_t_throttle))) {

7845                         if (mptsas_save_cmd(mpt, cmd) == TRUE) {
7846                                 mptsas_waitq_delete(mpt, cmd);

7847                                 (void) mptsas_start_cmd(mpt, cmd);






7848                         }
7849                 }
7850                 cmd = next_cmd;
7851         }
7852 }

7853 /*
7854  * Cmds are queued if tran_start() doesn't get the m_mutexlock(no wait).
7855  * Accept all those queued cmds before new cmd is accept so that the
7856  * cmds are sent in order.




7857  */
7858 static void
7859 mptsas_accept_tx_waitq(mptsas_t *mpt)
7860 {
7861         mptsas_cmd_t *cmd;





























































































7862 
7863         ASSERT(mutex_owned(&mpt->m_mutex));
7864         ASSERT(mutex_owned(&mpt->m_tx_waitq_mutex));



7865 
7866         /*
7867          * A Bus Reset could occur at any time and flush the tx_waitq,
7868          * so we cannot count on the tx_waitq to contain even one cmd.
7869          * And when the m_tx_waitq_mutex is released and run
7870          * mptsas_accept_pkt(), the tx_waitq may be flushed.
7871          */
7872         cmd = mpt->m_tx_waitq;
7873         for (;;) {
7874                 if ((cmd = mpt->m_tx_waitq) == NULL) {
7875                         mpt->m_tx_draining = 0;
7876                         break;




















7877                 }
7878                 if ((mpt->m_tx_waitq = cmd->cmd_linkp) == NULL) {
7879                         mpt->m_tx_waitqtail = &mpt->m_tx_waitq;
7880                 }
7881                 cmd->cmd_linkp = NULL;
7882                 mutex_exit(&mpt->m_tx_waitq_mutex);
7883                 if (mptsas_accept_pkt(mpt, cmd) != TRAN_ACCEPT)
7884                         cmn_err(CE_WARN, "mpt: mptsas_accept_tx_waitq: failed "
7885                             "to accept cmd on queue\n");
7886                 mutex_enter(&mpt->m_tx_waitq_mutex);
7887         }























7888 }
7889 











7890 
7891 /*
7892  * mpt tag type lookup
7893  */
7894 static char mptsas_tag_lookup[] =
7895         {0, MSG_HEAD_QTAG, MSG_ORDERED_QTAG, 0, MSG_SIMPLE_QTAG};
7896 
7897 static int
7898 mptsas_start_cmd(mptsas_t *mpt, mptsas_cmd_t *cmd)
7899 {
7900         struct scsi_pkt         *pkt = CMD2PKT(cmd);
7901         uint32_t                control = 0;
7902         int                     n;
7903         caddr_t                 mem;
7904         pMpi2SCSIIORequest_t    io_request;
7905         ddi_dma_handle_t        dma_hdl = mpt->m_dma_req_frame_hdl;
7906         ddi_acc_handle_t        acc_hdl = mpt->m_acc_req_frame_hdl;
7907         mptsas_target_t         *ptgt = cmd->cmd_tgt_addr;
7908         uint16_t                SMID, io_flags = 0;
7909         uint32_t                request_desc_low, request_desc_high;



7910 
7911         NDBG1(("mptsas_start_cmd: cmd=0x%p", (void *)cmd));

7912 
7913         /*
7914          * Set SMID and increment index.  Rollover to 1 instead of 0 if index
7915          * is at the max.  0 is an invalid SMID, so we call the first index 1.
7916          */
7917         SMID = cmd->cmd_slot;

7918 
7919         /*
7920          * It is possible for back to back device reset to
7921          * happen before the reset delay has expired.  That's
7922          * ok, just let the device reset go out on the bus.
7923          */
7924         if ((cmd->cmd_pkt_flags & FLAG_NOINTR) == 0) {
7925                 ASSERT(ptgt->m_reset_delay == 0);
7926         }
7927 
7928         /*
7929          * if a non-tagged cmd is submitted to an active tagged target
7930          * then drain before submitting this cmd; SCSI-2 allows RQSENSE
7931          * to be untagged
7932          */

7933         if (((cmd->cmd_pkt_flags & FLAG_TAGMASK) == 0) &&
7934             (ptgt->m_t_ncmds > 1) &&
7935             ((cmd->cmd_flags & CFLAG_TM_CMD) == 0) &&
7936             (*(cmd->cmd_pkt->pkt_cdbp) != SCMD_REQUEST_SENSE)) {
7937                 if ((cmd->cmd_pkt_flags & FLAG_NOINTR) == 0) {
7938                         NDBG23(("target=%d, untagged cmd, start draining\n",
7939                             ptgt->m_devhdl));
7940 
7941                         if (ptgt->m_reset_delay == 0) {
7942                                 mptsas_set_throttle(mpt, ptgt, DRAIN_THROTTLE);
7943                         }

7944 

7945                         mptsas_remove_cmd(mpt, cmd);
7946                         cmd->cmd_pkt_flags |= FLAG_HEAD;
7947                         mptsas_waitq_add(mpt, cmd);



7948                 }
7949                 return (DDI_FAILURE);
7950         }
7951 
7952         /*
7953          * Set correct tag bits.
7954          */
7955         if (cmd->cmd_pkt_flags & FLAG_TAGMASK) {
7956                 switch (mptsas_tag_lookup[((cmd->cmd_pkt_flags &
7957                     FLAG_TAGMASK) >> 12)]) {
7958                 case MSG_SIMPLE_QTAG:
7959                         control |= MPI2_SCSIIO_CONTROL_SIMPLEQ;
7960                         break;
7961                 case MSG_HEAD_QTAG:
7962                         control |= MPI2_SCSIIO_CONTROL_HEADOFQ;
7963                         break;
7964                 case MSG_ORDERED_QTAG:
7965                         control |= MPI2_SCSIIO_CONTROL_ORDEREDQ;
7966                         break;
7967                 default:
7968                         mptsas_log(mpt, CE_WARN, "mpt: Invalid tag type\n");
7969                         break;
7970                 }
7971         } else {
7972                 if (*(cmd->cmd_pkt->pkt_cdbp) != SCMD_REQUEST_SENSE) {
7973                                 ptgt->m_t_throttle = 1;
7974                 }
7975                 control |= MPI2_SCSIIO_CONTROL_SIMPLEQ;
7976         }
7977 






































7978         if (cmd->cmd_pkt_flags & FLAG_TLR) {
7979                 control |= MPI2_SCSIIO_CONTROL_TLR_ON;
7980         }
7981 
7982         mem = mpt->m_req_frame + (mpt->m_req_frame_size * SMID);
7983         io_request = (pMpi2SCSIIORequest_t)mem;
7984 

















7985         bzero(io_request, sizeof (Mpi2SCSIIORequest_t));


7986         ddi_put8(acc_hdl, &io_request->SGLOffset0, offsetof
7987             (MPI2_SCSI_IO_REQUEST, SGL) / 4);
7988         mptsas_init_std_hdr(acc_hdl, io_request, ptgt->m_devhdl, Lun(cmd), 0,
7989             MPI2_FUNCTION_SCSI_IO_REQUEST);
7990 
7991         (void) ddi_rep_put8(acc_hdl, (uint8_t *)pkt->pkt_cdbp,
7992             io_request->CDB.CDB32, cmd->cmd_cdblen, DDI_DEV_AUTOINCR);
7993 
7994         io_flags = cmd->cmd_cdblen;







7995         ddi_put16(acc_hdl, &io_request->IoFlags, io_flags);
7996         /*
7997          * setup the Scatter/Gather DMA list for this request
7998          */
7999         if (cmd->cmd_cookiec > 0) {
8000                 mptsas_sge_setup(mpt, cmd, &control, io_request, acc_hdl);
8001         } else {
8002                 ddi_put32(acc_hdl, &io_request->SGL.MpiSimple.FlagsLength,
8003                     ((uint32_t)MPI2_SGE_FLAGS_LAST_ELEMENT |
8004                     MPI2_SGE_FLAGS_END_OF_BUFFER |
8005                     MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
8006                     MPI2_SGE_FLAGS_END_OF_LIST) << MPI2_SGE_FLAGS_SHIFT);
8007         }
8008 
8009         /*
8010          * save ARQ information
8011          */
8012         ddi_put8(acc_hdl, &io_request->SenseBufferLength, cmd->cmd_rqslen);
8013         if ((cmd->cmd_flags & (CFLAG_SCBEXTERN | CFLAG_EXTARQBUFVALID)) ==
8014             (CFLAG_SCBEXTERN | CFLAG_EXTARQBUFVALID)) {
8015                 ddi_put32(acc_hdl, &io_request->SenseBufferLowAddress,
8016                     cmd->cmd_ext_arqcookie.dmac_address);
8017         } else {
8018                 ddi_put32(acc_hdl, &io_request->SenseBufferLowAddress,
8019                     cmd->cmd_arqcookie.dmac_address);
8020         }
8021 
8022         ddi_put32(acc_hdl, &io_request->Control, control);
8023 
8024         NDBG31(("starting message=0x%p, with cmd=0x%p",
8025             (void *)(uintptr_t)mpt->m_req_frame_dma_addr, (void *)cmd));
8026 
8027         (void) ddi_dma_sync(dma_hdl, 0, 0, DDI_DMA_SYNC_FORDEV);
8028 
8029         /*
8030          * Build request descriptor and write it to the request desc post reg.
8031          */
8032         request_desc_low = (SMID << 16) + MPI2_REQ_DESCRIPT_FLAGS_SCSI_IO;
8033         request_desc_high = ptgt->m_devhdl << 16;
8034         MPTSAS_START_CMD(mpt, request_desc_low, request_desc_high);
8035 
8036         /*
8037          * Start timeout.
8038          */
8039 #ifdef MPTSAS_TEST
8040         /*
8041          * Temporarily set timebase = 0;  needed for
8042          * timeout torture test.
8043          */
8044         if (mptsas_test_timeouts) {
8045                 ptgt->m_timebase = 0;
8046         }
8047 #endif
8048         n = pkt->pkt_time - ptgt->m_timebase;
8049 
8050         if (n == 0) {
8051                 (ptgt->m_dups)++;
8052                 ptgt->m_timeout = ptgt->m_timebase;
8053         } else if (n > 0) {
8054                 ptgt->m_timeout =
8055                     ptgt->m_timebase = pkt->pkt_time;
8056                 ptgt->m_dups = 1;
8057         } else if (n < 0) {
8058                 ptgt->m_timeout = ptgt->m_timebase;
8059         }
8060 #ifdef MPTSAS_TEST
8061         /*
8062          * Set back to a number higher than
8063          * mptsas_scsi_watchdog_tick
8064          * so timeouts will happen in mptsas_watchsubr
8065          */
8066         if (mptsas_test_timeouts) {
8067                 ptgt->m_timebase = 60;
8068         }
8069 #endif
8070 


8071         if ((mptsas_check_dma_handle(dma_hdl) != DDI_SUCCESS) ||
8072             (mptsas_check_acc_handle(acc_hdl) != DDI_SUCCESS)) {
8073                 ddi_fm_service_impact(mpt->m_dip, DDI_SERVICE_UNAFFECTED);
8074                 return (DDI_FAILURE);
8075         }

8076         return (DDI_SUCCESS);
8077 }
8078 
8079 /*
8080  * Select a helper thread to handle current doneq




8081  */
8082 static void
8083 mptsas_deliver_doneq_thread(mptsas_t *mpt)
8084 {
8085         uint64_t                        t, i;
8086         uint32_t                        min = 0xffffffff;
8087         mptsas_doneq_thread_list_t      *item;
8088 





8089         for (i = 0; i < mpt->m_doneq_thread_n; i++) {
8090                 item = &mpt->m_doneq_thread_id[i];

8091                 /*
8092                  * If the completed command on help thread[i] less than
8093                  * doneq_thread_threshold, then pick the thread[i]. Otherwise
8094                  * pick a thread which has least completed command.
8095                  */
8096 
8097                 mutex_enter(&item->mutex);
8098                 if (item->len < mpt->m_doneq_thread_threshold) {
8099                         t = i;
8100                         mutex_exit(&item->mutex);
8101                         break;
8102                 }
8103                 if (item->len < min) {
8104                         min = item->len;
8105                         t = i;




8106                 }




8107                 mutex_exit(&item->mutex);










8108         }
8109         mutex_enter(&mpt->m_doneq_thread_id[t].mutex);
8110         mptsas_doneq_mv(mpt, t);
8111         cv_signal(&mpt->m_doneq_thread_id[t].cv);
8112         mutex_exit(&mpt->m_doneq_thread_id[t].mutex);
8113 }
8114 
8115 /*
8116  * move the current global doneq to the doneq of thead[t]
8117  */
8118 static void
8119 mptsas_doneq_mv(mptsas_t *mpt, uint64_t t)
8120 {

8121         mptsas_cmd_t                    *cmd;
8122         mptsas_doneq_thread_list_t      *item = &mpt->m_doneq_thread_id[t];
8123 
8124         ASSERT(mutex_owned(&item->mutex));
8125         while ((cmd = mpt->m_doneq) != NULL) {
8126                 if ((mpt->m_doneq = cmd->cmd_linkp) == NULL) {
8127                         mpt->m_donetail = &mpt->m_doneq;
8128                 }
8129                 cmd->cmd_linkp = NULL;
8130                 *item->donetail = cmd;
8131                 item->donetail = &cmd->cmd_linkp;
8132                 mpt->m_doneq_len--;
8133                 item->len++;
8134         }
8135 }
8136 
8137 void
8138 mptsas_fma_check(mptsas_t *mpt, mptsas_cmd_t *cmd)
8139 {
8140         struct scsi_pkt *pkt = CMD2PKT(cmd);
8141 
8142         /* Check all acc and dma handles */
8143         if ((mptsas_check_acc_handle(mpt->m_datap) !=
8144             DDI_SUCCESS) ||
8145             (mptsas_check_acc_handle(mpt->m_acc_req_frame_hdl) !=
8146             DDI_SUCCESS) ||


8147             (mptsas_check_acc_handle(mpt->m_acc_reply_frame_hdl) !=
8148             DDI_SUCCESS) ||
8149             (mptsas_check_acc_handle(mpt->m_acc_free_queue_hdl) !=
8150             DDI_SUCCESS) ||
8151             (mptsas_check_acc_handle(mpt->m_acc_post_queue_hdl) !=
8152             DDI_SUCCESS) ||
8153             (mptsas_check_acc_handle(mpt->m_hshk_acc_hdl) !=
8154             DDI_SUCCESS) ||
8155             (mptsas_check_acc_handle(mpt->m_config_handle) !=
8156             DDI_SUCCESS)) {
8157                 ddi_fm_service_impact(mpt->m_dip,
8158                     DDI_SERVICE_UNAFFECTED);
8159                 ddi_fm_acc_err_clear(mpt->m_config_handle,
8160                     DDI_FME_VER0);
8161                 pkt->pkt_reason = CMD_TRAN_ERR;
8162                 pkt->pkt_statistics = 0;
8163         }
8164         if ((mptsas_check_dma_handle(mpt->m_dma_req_frame_hdl) !=
8165             DDI_SUCCESS) ||


8166             (mptsas_check_dma_handle(mpt->m_dma_reply_frame_hdl) !=
8167             DDI_SUCCESS) ||
8168             (mptsas_check_dma_handle(mpt->m_dma_free_queue_hdl) !=
8169             DDI_SUCCESS) ||
8170             (mptsas_check_dma_handle(mpt->m_dma_post_queue_hdl) !=
8171             DDI_SUCCESS) ||
8172             (mptsas_check_dma_handle(mpt->m_hshk_dma_hdl) !=
8173             DDI_SUCCESS)) {
8174                 ddi_fm_service_impact(mpt->m_dip,
8175                     DDI_SERVICE_UNAFFECTED);
8176                 pkt->pkt_reason = CMD_TRAN_ERR;
8177                 pkt->pkt_statistics = 0;
8178         }
8179         if (cmd->cmd_dmahandle &&
8180             (mptsas_check_dma_handle(cmd->cmd_dmahandle) != DDI_SUCCESS)) {
8181                 ddi_fm_service_impact(mpt->m_dip, DDI_SERVICE_UNAFFECTED);
8182                 pkt->pkt_reason = CMD_TRAN_ERR;
8183                 pkt->pkt_statistics = 0;
8184         }
8185         if ((cmd->cmd_extra_frames &&
8186             ((mptsas_check_dma_handle(cmd->cmd_extra_frames->m_dma_hdl) !=
8187             DDI_SUCCESS) ||
8188             (mptsas_check_acc_handle(cmd->cmd_extra_frames->m_acc_hdl) !=
8189             DDI_SUCCESS)))) {
8190                 ddi_fm_service_impact(mpt->m_dip, DDI_SERVICE_UNAFFECTED);
8191                 pkt->pkt_reason = CMD_TRAN_ERR;
8192                 pkt->pkt_statistics = 0;
8193         }
8194         if (cmd->cmd_arqhandle &&
8195             (mptsas_check_dma_handle(cmd->cmd_arqhandle) != DDI_SUCCESS)) {
8196                 ddi_fm_service_impact(mpt->m_dip, DDI_SERVICE_UNAFFECTED);
8197                 pkt->pkt_reason = CMD_TRAN_ERR;
8198                 pkt->pkt_statistics = 0;
8199         }
8200         if (cmd->cmd_ext_arqhandle &&
8201             (mptsas_check_dma_handle(cmd->cmd_ext_arqhandle) != DDI_SUCCESS)) {
8202                 ddi_fm_service_impact(mpt->m_dip, DDI_SERVICE_UNAFFECTED);
8203                 pkt->pkt_reason = CMD_TRAN_ERR;
8204                 pkt->pkt_statistics = 0;
8205         }
8206 }
8207 
8208 /*
8209  * These routines manipulate the queue of commands that
8210  * are waiting for their completion routines to be called.
8211  * The queue is usually in FIFO order but on an MP system
8212  * it's possible for the completion routines to get out
8213  * of order. If that's a problem you need to add a global
8214  * mutex around the code that calls the completion routine
8215  * in the interrupt handler.
8216  */
8217 static void
8218 mptsas_doneq_add(mptsas_t *mpt, mptsas_cmd_t *cmd)
8219 {
8220         struct scsi_pkt *pkt = CMD2PKT(cmd);
8221 
8222         NDBG31(("mptsas_doneq_add: cmd=0x%p", (void *)cmd));
8223 
8224         ASSERT((cmd->cmd_flags & CFLAG_COMPLETED) == 0);
8225         cmd->cmd_linkp = NULL;
8226         cmd->cmd_flags |= CFLAG_FINISHED;
8227         cmd->cmd_flags &= ~CFLAG_IN_TRANSPORT;
8228 
8229         mptsas_fma_check(mpt, cmd);
8230 
8231         /*
8232          * only add scsi pkts that have completion routines to
8233          * the doneq.  no intr cmds do not have callbacks.
8234          */
8235         if (pkt && (pkt->pkt_comp)) {
8236                 *mpt->m_donetail = cmd;
8237                 mpt->m_donetail = &cmd->cmd_linkp;
8238                 mpt->m_doneq_len++;


























8239         }
8240 }
8241 
8242 static mptsas_cmd_t *
8243 mptsas_doneq_thread_rm(mptsas_t *mpt, uint64_t t)
8244 {
8245         mptsas_cmd_t                    *cmd;
8246         mptsas_doneq_thread_list_t      *item = &mpt->m_doneq_thread_id[t];
8247 
8248         /* pop one off the done queue */
8249         if ((cmd = item->doneq) != NULL) {
8250                 /* if the queue is now empty fix the tail pointer */
8251                 NDBG31(("mptsas_doneq_thread_rm: cmd=0x%p", (void *)cmd));
8252                 if ((item->doneq = cmd->cmd_linkp) == NULL) {
8253                         item->donetail = &item->doneq;
8254                 }
8255                 cmd->cmd_linkp = NULL;
8256                 item->len--;
8257         }
8258         return (cmd);
8259 }
8260 
8261 static void
8262 mptsas_doneq_empty(mptsas_t *mpt)
8263 {
8264         if (mpt->m_doneq && !mpt->m_in_callback) {
8265                 mptsas_cmd_t    *cmd, *next;
8266                 struct scsi_pkt *pkt;
8267 
8268                 mpt->m_in_callback = 1;
8269                 cmd = mpt->m_doneq;
8270                 mpt->m_doneq = NULL;
8271                 mpt->m_donetail = &mpt->m_doneq;
8272                 mpt->m_doneq_len = 0;
8273 
8274                 mutex_exit(&mpt->m_mutex);
8275                 /*
8276                  * run the completion routines of all the
8277                  * completed commands
8278                  */
8279                 while (cmd != NULL) {
8280                         next = cmd->cmd_linkp;
8281                         cmd->cmd_linkp = NULL;
8282                         /* run this command's completion routine */
8283                         cmd->cmd_flags |= CFLAG_COMPLETED;
8284                         pkt = CMD2PKT(cmd);
8285                         mptsas_pkt_comp(pkt, cmd);
8286                         cmd = next;
8287                 }
8288                 mutex_enter(&mpt->m_mutex);
8289                 mpt->m_in_callback = 0;





























8290         }
8291 }
8292 
8293 /*
8294  * These routines manipulate the target's queue of pending requests
8295  */
8296 void
8297 mptsas_waitq_add(mptsas_t *mpt, mptsas_cmd_t *cmd)
8298 {
8299         NDBG7(("mptsas_waitq_add: cmd=0x%p", (void *)cmd));
8300         mptsas_target_t *ptgt = cmd->cmd_tgt_addr;
8301         cmd->cmd_queued = TRUE;
8302         if (ptgt)
8303                 ptgt->m_t_nwait++;
8304         if (cmd->cmd_pkt_flags & FLAG_HEAD) {
8305                 if ((cmd->cmd_linkp = mpt->m_waitq) == NULL) {
8306                         mpt->m_waitqtail = &cmd->cmd_linkp;
8307                 }
8308                 mpt->m_waitq = cmd;
8309         } else {


8359                     (void *)mpt, (void *)cmd));
8360                 return;
8361         }
8362 
8363         while (prevp != NULL) {
8364                 if (prevp->cmd_linkp == cmd) {
8365                         if ((prevp->cmd_linkp = cmd->cmd_linkp) == NULL)
8366                                 mpt->m_waitqtail = &prevp->cmd_linkp;
8367 
8368                         cmd->cmd_linkp = NULL;
8369                         cmd->cmd_queued = FALSE;
8370                         NDBG7(("mptsas_waitq_delete: mpt=0x%p cmd=0x%p",
8371                             (void *)mpt, (void *)cmd));
8372                         return;
8373                 }
8374                 prevp = prevp->cmd_linkp;
8375         }
8376         cmn_err(CE_PANIC, "mpt: mptsas_waitq_delete: queue botch");
8377 }
8378 
8379 static mptsas_cmd_t *
8380 mptsas_tx_waitq_rm(mptsas_t *mpt)
8381 {
8382         mptsas_cmd_t *cmd;
8383         NDBG7(("mptsas_tx_waitq_rm"));
8384 
8385         MPTSAS_TX_WAITQ_RM(mpt, cmd);
8386 
8387         NDBG7(("mptsas_tx_waitq_rm: cmd=0x%p", (void *)cmd));
8388 
8389         return (cmd);
8390 }
8391 
8392 /*
8393  * remove specified cmd from the middle of the tx_waitq.
8394  */
8395 static void
8396 mptsas_tx_waitq_delete(mptsas_t *mpt, mptsas_cmd_t *cmd)
8397 {
8398         mptsas_cmd_t *prevp = mpt->m_tx_waitq;
8399 
8400         NDBG7(("mptsas_tx_waitq_delete: mpt=0x%p cmd=0x%p",
8401             (void *)mpt, (void *)cmd));
8402 
8403         if (prevp == cmd) {
8404                 if ((mpt->m_tx_waitq = cmd->cmd_linkp) == NULL)
8405                         mpt->m_tx_waitqtail = &mpt->m_tx_waitq;
8406 
8407                 cmd->cmd_linkp = NULL;
8408                 cmd->cmd_queued = FALSE;
8409                 NDBG7(("mptsas_tx_waitq_delete: mpt=0x%p cmd=0x%p",
8410                     (void *)mpt, (void *)cmd));
8411                 return;
8412         }
8413 
8414         while (prevp != NULL) {
8415                 if (prevp->cmd_linkp == cmd) {
8416                         if ((prevp->cmd_linkp = cmd->cmd_linkp) == NULL)
8417                                 mpt->m_tx_waitqtail = &prevp->cmd_linkp;
8418 
8419                         cmd->cmd_linkp = NULL;
8420                         cmd->cmd_queued = FALSE;
8421                         NDBG7(("mptsas_tx_waitq_delete: mpt=0x%p cmd=0x%p",
8422                             (void *)mpt, (void *)cmd));
8423                         return;
8424                 }
8425                 prevp = prevp->cmd_linkp;
8426         }
8427         cmn_err(CE_PANIC, "mpt: mptsas_tx_waitq_delete: queue botch");
8428 }
8429 
8430 /*
8431  * device and bus reset handling
8432  *
8433  * Notes:
8434  *      - RESET_ALL:    reset the controller
8435  *      - RESET_TARGET: reset the target specified in scsi_address
8436  */
8437 static int
8438 mptsas_scsi_reset(struct scsi_address *ap, int level)
8439 {
8440         mptsas_t                *mpt = ADDR2MPT(ap);
8441         int                     rval;
8442         mptsas_tgt_private_t    *tgt_private;
8443         mptsas_target_t         *ptgt = NULL;
8444 
8445         tgt_private = (mptsas_tgt_private_t *)ap->a_hba_tran->tran_tgt_private;
8446         ptgt = tgt_private->t_private;
8447         if (ptgt == NULL) {
8448                 return (FALSE);
8449         }


8525         dev_info_t      *lun_dip = NULL;
8526 
8527         ASSERT(sd != NULL);
8528         ASSERT(name != NULL);
8529         lun_dip = sd->sd_dev;
8530         ASSERT(lun_dip != NULL);
8531 
8532         if (mptsas_name_child(lun_dip, name, len) == DDI_SUCCESS) {
8533                 return (1);
8534         } else {
8535                 return (0);
8536         }
8537 }
8538 
8539 static int
8540 mptsas_get_bus_addr(struct scsi_device *sd, char *name, int len)
8541 {
8542         return (mptsas_get_name(sd, name, len));
8543 }
8544 
8545 void
8546 mptsas_set_throttle(mptsas_t *mpt, mptsas_target_t *ptgt, int what)
8547 {
8548 
8549         NDBG25(("mptsas_set_throttle: throttle=%x", what));
8550 
8551         /*
8552          * if the bus is draining/quiesced, no changes to the throttles
8553          * are allowed. Not allowing change of throttles during draining
8554          * limits error recovery but will reduce draining time
8555          *
8556          * all throttles should have been set to HOLD_THROTTLE
8557          */
8558         if (mpt->m_softstate & (MPTSAS_SS_QUIESCED | MPTSAS_SS_DRAINING)) {
8559                 return;
8560         }
8561 
8562         if (what == HOLD_THROTTLE) {
8563                 ptgt->m_t_throttle = HOLD_THROTTLE;
8564         } else if (ptgt->m_reset_delay == 0) {
8565                 ptgt->m_t_throttle = what;
8566         }
8567 }
8568 


















































8569 /*
8570  * Clean up from a device reset.
8571  * For the case of target reset, this function clears the waitq of all
8572  * commands for a particular target.   For the case of abort task set, this
8573  * function clears the waitq of all commonds for a particular target/lun.
8574  */
8575 static void
8576 mptsas_flush_target(mptsas_t *mpt, ushort_t target, int lun, uint8_t tasktype)
8577 {
8578         mptsas_slots_t  *slots = mpt->m_active;
8579         mptsas_cmd_t    *cmd, *next_cmd;
8580         int             slot;
8581         uchar_t         reason;
8582         uint_t          stat;

8583 
8584         NDBG25(("mptsas_flush_target: target=%d lun=%d", target, lun));
8585 


8586         /*
8587          * Make sure the I/O Controller has flushed all cmds
8588          * that are associated with this target for a target reset
8589          * and target/lun for abort task set.
8590          * Account for TM requests, which use the last SMID.
8591          */
8592         for (slot = 0; slot <= mpt->m_active->m_n_normal; slot++) {
8593                 if ((cmd = slots->m_slot[slot]) == NULL)
8594                         continue;
8595                 reason = CMD_RESET;
8596                 stat = STAT_DEV_RESET;
8597                 switch (tasktype) {
8598                 case MPI2_SCSITASKMGMT_TASKTYPE_TARGET_RESET:
8599                         if (Tgt(cmd) == target) {









8600                                 NDBG25(("mptsas_flush_target discovered non-"
8601                                     "NULL cmd in slot %d, tasktype 0x%x", slot,
8602                                     tasktype));
8603                                 mptsas_dump_cmd(mpt, cmd);
8604                                 mptsas_remove_cmd(mpt, cmd);
8605                                 mptsas_set_pkt_reason(mpt, cmd, reason, stat);
8606                                 mptsas_doneq_add(mpt, cmd);
8607                         }
8608                         break;
8609                 case MPI2_SCSITASKMGMT_TASKTYPE_ABRT_TASK_SET:
8610                         reason = CMD_ABORTED;
8611                         stat = STAT_ABORTED;
8612                         /*FALLTHROUGH*/
8613                 case MPI2_SCSITASKMGMT_TASKTYPE_LOGICAL_UNIT_RESET:
8614                         if ((Tgt(cmd) == target) && (Lun(cmd) == lun)) {



8615 
8616                                 NDBG25(("mptsas_flush_target discovered non-"
8617                                     "NULL cmd in slot %d, tasktype 0x%x", slot,
8618                                     tasktype));
8619                                 mptsas_dump_cmd(mpt, cmd);
8620                                 mptsas_remove_cmd(mpt, cmd);
8621                                 mptsas_set_pkt_reason(mpt, cmd, reason,
8622                                     stat);
8623                                 mptsas_doneq_add(mpt, cmd);
8624                         }
8625                         break;
8626                 default:
8627                         break;
8628                 }
8629         }
8630 
8631         /*
8632          * Flush the waitq and tx_waitq of this target's cmds
8633          */
8634         cmd = mpt->m_waitq;
8635 
8636         reason = CMD_RESET;
8637         stat = STAT_DEV_RESET;
8638 
8639         switch (tasktype) {
8640         case MPI2_SCSITASKMGMT_TASKTYPE_TARGET_RESET:
8641                 while (cmd != NULL) {
8642                         next_cmd = cmd->cmd_linkp;
8643                         if (Tgt(cmd) == target) {
8644                                 mptsas_waitq_delete(mpt, cmd);
8645                                 mptsas_set_pkt_reason(mpt, cmd,
8646                                     reason, stat);
8647                                 mptsas_doneq_add(mpt, cmd);
8648                         }
8649                         cmd = next_cmd;
8650                 }
8651                 mutex_enter(&mpt->m_tx_waitq_mutex);
8652                 cmd = mpt->m_tx_waitq;
8653                 while (cmd != NULL) {
8654                         next_cmd = cmd->cmd_linkp;
8655                         if (Tgt(cmd) == target) {
8656                                 mptsas_tx_waitq_delete(mpt, cmd);
8657                                 mutex_exit(&mpt->m_tx_waitq_mutex);
8658                                 mptsas_set_pkt_reason(mpt, cmd,
8659                                     reason, stat);
8660                                 mptsas_doneq_add(mpt, cmd);
8661                                 mutex_enter(&mpt->m_tx_waitq_mutex);
8662                         }
8663                         cmd = next_cmd;
8664                 }
8665                 mutex_exit(&mpt->m_tx_waitq_mutex);
8666                 break;
8667         case MPI2_SCSITASKMGMT_TASKTYPE_ABRT_TASK_SET:
8668                 reason = CMD_ABORTED;
8669                 stat =  STAT_ABORTED;
8670                 /*FALLTHROUGH*/
8671         case MPI2_SCSITASKMGMT_TASKTYPE_LOGICAL_UNIT_RESET:
8672                 while (cmd != NULL) {
8673                         next_cmd = cmd->cmd_linkp;
8674                         if ((Tgt(cmd) == target) && (Lun(cmd) == lun)) {
8675                                 mptsas_waitq_delete(mpt, cmd);
8676                                 mptsas_set_pkt_reason(mpt, cmd,
8677                                     reason, stat);
8678                                 mptsas_doneq_add(mpt, cmd);
8679                         }
8680                         cmd = next_cmd;
8681                 }
8682                 mutex_enter(&mpt->m_tx_waitq_mutex);
8683                 cmd = mpt->m_tx_waitq;
8684                 while (cmd != NULL) {
8685                         next_cmd = cmd->cmd_linkp;
8686                         if ((Tgt(cmd) == target) && (Lun(cmd) == lun)) {
8687                                 mptsas_tx_waitq_delete(mpt, cmd);
8688                                 mutex_exit(&mpt->m_tx_waitq_mutex);
8689                                 mptsas_set_pkt_reason(mpt, cmd,
8690                                     reason, stat);
8691                                 mptsas_doneq_add(mpt, cmd);
8692                                 mutex_enter(&mpt->m_tx_waitq_mutex);
8693                         }
8694                         cmd = next_cmd;
8695                 }
8696                 mutex_exit(&mpt->m_tx_waitq_mutex);
8697                 break;
8698         default:
8699                 mptsas_log(mpt, CE_WARN, "Unknown task management type %d.",
8700                     tasktype);
8701                 break;
8702         }
8703 }
8704 
8705 /*
8706  * Clean up hba state, abort all outstanding command and commands in waitq
8707  * reset timeout of all targets.
8708  */
8709 static void
8710 mptsas_flush_hba(mptsas_t *mpt)
8711 {
8712         mptsas_slots_t  *slots = mpt->m_active;
8713         mptsas_cmd_t    *cmd;
8714         int             slot;
8715 
8716         NDBG25(("mptsas_flush_hba"));
8717 
8718         /*
8719          * The I/O Controller should have already sent back
8720          * all commands via the scsi I/O reply frame.  Make
8721          * sure all commands have been flushed.
8722          * Account for TM request, which use the last SMID.
8723          */
8724         for (slot = 0; slot <= mpt->m_active->m_n_normal; slot++) {
8725                 if ((cmd = slots->m_slot[slot]) == NULL)
8726                         continue;
8727 
8728                 if (cmd->cmd_flags & CFLAG_CMDIOC) {
8729                         /*
8730                          * Need to make sure to tell everyone that might be
8731                          * waiting on this command that it's going to fail.  If
8732                          * we get here, this command will never timeout because
8733                          * the active command table is going to be re-allocated,
8734                          * so there will be nothing to check against a time out.
8735                          * Instead, mark the command as failed due to reset.
8736                          */
8737                         mptsas_set_pkt_reason(mpt, cmd, CMD_RESET,
8738                             STAT_BUS_RESET);
8739                         if ((cmd->cmd_flags & CFLAG_PASSTHRU) ||
8740                             (cmd->cmd_flags & CFLAG_CONFIG) ||
8741                             (cmd->cmd_flags & CFLAG_FW_DIAG)) {
8742                                 cmd->cmd_flags |= CFLAG_FINISHED;
8743                                 cv_broadcast(&mpt->m_passthru_cv);
8744                                 cv_broadcast(&mpt->m_config_cv);
8745                                 cv_broadcast(&mpt->m_fw_diag_cv);
8746                         }
8747                         continue;
8748                 }
8749 
8750                 NDBG25(("mptsas_flush_hba discovered non-NULL cmd in slot %d",
8751                     slot));
8752                 mptsas_dump_cmd(mpt, cmd);
8753 
8754                 mptsas_remove_cmd(mpt, cmd);
8755                 mptsas_set_pkt_reason(mpt, cmd, CMD_RESET, STAT_BUS_RESET);
8756                 mptsas_doneq_add(mpt, cmd);
8757         }
8758 
8759         /*
8760          * Flush the waitq.
8761          */
8762         while ((cmd = mptsas_waitq_rm(mpt)) != NULL) {
8763                 mptsas_set_pkt_reason(mpt, cmd, CMD_RESET, STAT_BUS_RESET);
8764                 if ((cmd->cmd_flags & CFLAG_PASSTHRU) ||
8765                     (cmd->cmd_flags & CFLAG_CONFIG) ||
8766                     (cmd->cmd_flags & CFLAG_FW_DIAG)) {
8767                         cmd->cmd_flags |= CFLAG_FINISHED;
8768                         cv_broadcast(&mpt->m_passthru_cv);
8769                         cv_broadcast(&mpt->m_config_cv);
8770                         cv_broadcast(&mpt->m_fw_diag_cv);
8771                 } else {
8772                         mptsas_doneq_add(mpt, cmd);
8773                 }
8774         }
8775 
8776         /*
8777          * Flush the tx_waitq
8778          */
8779         mutex_enter(&mpt->m_tx_waitq_mutex);
8780         while ((cmd = mptsas_tx_waitq_rm(mpt)) != NULL) {
8781                 mutex_exit(&mpt->m_tx_waitq_mutex);
8782                 mptsas_set_pkt_reason(mpt, cmd, CMD_RESET, STAT_BUS_RESET);






8783                 mptsas_doneq_add(mpt, cmd);
8784                 mutex_enter(&mpt->m_tx_waitq_mutex);

8785         }
8786         mutex_exit(&mpt->m_tx_waitq_mutex);
8787 
8788         /*
8789          * Drain the taskqs prior to reallocating resources.
8790          */
8791         mutex_exit(&mpt->m_mutex);
8792         ddi_taskq_wait(mpt->m_event_taskq);
8793         ddi_taskq_wait(mpt->m_dr_taskq);
8794         mutex_enter(&mpt->m_mutex);
8795 }
8796 
8797 /*
8798  * set pkt_reason and OR in pkt_statistics flag
8799  */
8800 static void
8801 mptsas_set_pkt_reason(mptsas_t *mpt, mptsas_cmd_t *cmd, uchar_t reason,
8802     uint_t stat)
8803 {
8804 #ifndef __lock_lint
8805         _NOTE(ARGUNUSED(mpt))
8806 #endif


8824         mutex_enter(&mptsas_global_mutex);
8825         if (mptsas_reset_watch == NULL && mptsas_timeouts_enabled) {
8826                 mptsas_reset_watch = timeout(mptsas_watch_reset_delay, NULL,
8827                     drv_usectohz((clock_t)
8828                     MPTSAS_WATCH_RESET_DELAY_TICK * 1000));
8829                 ASSERT(mptsas_reset_watch != NULL);
8830         }
8831         mutex_exit(&mptsas_global_mutex);
8832 }
8833 
8834 static void
8835 mptsas_setup_bus_reset_delay(mptsas_t *mpt)
8836 {
8837         mptsas_target_t *ptgt = NULL;
8838 
8839         ASSERT(MUTEX_HELD(&mpt->m_mutex));
8840 
8841         NDBG22(("mptsas_setup_bus_reset_delay"));
8842         for (ptgt = refhash_first(mpt->m_targets); ptgt != NULL;
8843             ptgt = refhash_next(mpt->m_targets, ptgt)) {

8844                 mptsas_set_throttle(mpt, ptgt, HOLD_THROTTLE);
8845                 ptgt->m_reset_delay = mpt->m_scsi_reset_delay;

8846         }
8847 
8848         mptsas_start_watch_reset_delay();
8849 }
8850 
8851 /*
8852  * mptsas_watch_reset_delay(_subr) is invoked by timeout() and checks every
8853  * mpt instance for active reset delays
8854  */
8855 static void
8856 mptsas_watch_reset_delay(void *arg)
8857 {
8858 #ifndef __lock_lint
8859         _NOTE(ARGUNUSED(arg))
8860 #endif
8861 
8862         mptsas_t        *mpt;
8863         int             not_done = 0;
8864 
8865         NDBG22(("mptsas_watch_reset_delay"));


8879         rw_exit(&mptsas_global_rwlock);
8880 
8881         if (not_done) {
8882                 mptsas_start_watch_reset_delay();
8883         }
8884 }
8885 
8886 static int
8887 mptsas_watch_reset_delay_subr(mptsas_t *mpt)
8888 {
8889         int             done = 0;
8890         int             restart = 0;
8891         mptsas_target_t *ptgt = NULL;
8892 
8893         NDBG22(("mptsas_watch_reset_delay_subr: mpt=0x%p", (void *)mpt));
8894 
8895         ASSERT(mutex_owned(&mpt->m_mutex));
8896 
8897         for (ptgt = refhash_first(mpt->m_targets); ptgt != NULL;
8898             ptgt = refhash_next(mpt->m_targets, ptgt)) {

8899                 if (ptgt->m_reset_delay != 0) {
8900                         ptgt->m_reset_delay -=
8901                             MPTSAS_WATCH_RESET_DELAY_TICK;
8902                         if (ptgt->m_reset_delay <= 0) {
8903                                 ptgt->m_reset_delay = 0;
8904                                 mptsas_set_throttle(mpt, ptgt,
8905                                     MAX_THROTTLE);
8906                                 restart++;
8907                         } else {
8908                                 done = -1;
8909                         }
8910                 }

8911         }
8912 
8913         if (restart > 0) {
8914                 mptsas_restart_hba(mpt);
8915         }
8916         return (done);
8917 }
8918 
8919 #ifdef MPTSAS_TEST
8920 static void
8921 mptsas_test_reset(mptsas_t *mpt, int target)
8922 {
8923         mptsas_target_t    *ptgt = NULL;
8924 
8925         if (mptsas_rtest == target) {
8926                 if (mptsas_do_scsi_reset(mpt, target) == TRUE) {
8927                         mptsas_rtest = -1;
8928                 }
8929                 if (mptsas_rtest == -1) {
8930                         NDBG22(("mptsas_test_reset success"));


9107                         rval = FALSE;
9108                 break;
9109         default:
9110                 rval = UNDEFINED;
9111                 break;
9112         }
9113 
9114         NDBG24(("mptsas_scsi_getcap: %s, rval=%x", cap, rval));
9115 
9116         mutex_exit(&mpt->m_mutex);
9117         return (rval);
9118 }
9119 
9120 /*
9121  * (*tran_setcap).  Set the capability named to the value given.
9122  */
9123 static int
9124 mptsas_scsi_setcap(struct scsi_address *ap, char *cap, int value, int tgtonly)
9125 {
9126         mptsas_t        *mpt = ADDR2MPT(ap);

9127         int             ckey;
9128         int             rval = FALSE;
9129 
9130         NDBG24(("mptsas_scsi_setcap: target=%d, cap=%s value=%x tgtonly=%x",
9131             ap->a_target, cap, value, tgtonly));
9132 
9133         if (!tgtonly) {
9134                 return (rval);
9135         }
9136 
9137         mutex_enter(&mpt->m_mutex);
9138 
9139         if ((mptsas_scsi_capchk(cap, tgtonly, &ckey)) != TRUE) {
9140                 mutex_exit(&mpt->m_mutex);
9141                 return (UNDEFINED);
9142         }
9143 
9144         switch (ckey) {
9145         case SCSI_CAP_DMA_MAX:
9146         case SCSI_CAP_MSG_OUT:


9148         case SCSI_CAP_INITIATOR_ID:
9149         case SCSI_CAP_LINKED_CMDS:
9150         case SCSI_CAP_UNTAGGED_QING:
9151         case SCSI_CAP_RESET_NOTIFICATION:
9152                 /*
9153                  * None of these are settable via
9154                  * the capability interface.
9155                  */
9156                 break;
9157         case SCSI_CAP_ARQ:
9158                 /*
9159                  * We cannot turn off arq so return false if asked to
9160                  */
9161                 if (value) {
9162                         rval = TRUE;
9163                 } else {
9164                         rval = FALSE;
9165                 }
9166                 break;
9167         case SCSI_CAP_TAGGED_QING:
9168                 mptsas_set_throttle(mpt, ((mptsas_tgt_private_t *)
9169                     (ap->a_hba_tran->tran_tgt_private))->t_private,
9170                     MAX_THROTTLE);
9171                 rval = TRUE;
9172                 break;
9173         case SCSI_CAP_QFULL_RETRIES:
9174                 ((mptsas_tgt_private_t *)(ap->a_hba_tran->tran_tgt_private))->
9175                     t_private->m_qfull_retries = (uchar_t)value;
9176                 rval = TRUE;
9177                 break;
9178         case SCSI_CAP_QFULL_RETRY_INTERVAL:
9179                 ((mptsas_tgt_private_t *)(ap->a_hba_tran->tran_tgt_private))->
9180                     t_private->m_qfull_retry_interval =
9181                     drv_usectohz(value * 1000);
9182                 rval = TRUE;
9183                 break;
9184         default:
9185                 rval = UNDEFINED;
9186                 break;
9187         }
9188         mutex_exit(&mpt->m_mutex);
9189         return (rval);
9190 }


9238 
9239         return (0);
9240 }
9241 
9242 static void
9243 mptsas_free_active_slots(mptsas_t *mpt)
9244 {
9245         mptsas_slots_t  *active = mpt->m_active;
9246         size_t          size;
9247 
9248         if (active == NULL)
9249                 return;
9250         size = active->m_size;
9251         kmem_free(active, size);
9252         mpt->m_active = NULL;
9253 }
9254 
9255 /*
9256  * Error logging, printing, and debug print routines.
9257  */
9258 static char *mptsas_label = "mpt_sas";
9259 
9260 /*PRINTFLIKE3*/
9261 void
9262 mptsas_log(mptsas_t *mpt, int level, char *fmt, ...)
9263 {
9264         dev_info_t      *dev;
9265         va_list         ap;
9266 
9267         if (mpt) {
9268                 dev = mpt->m_dip;
9269         } else {
9270                 dev = 0;
9271         }
9272 
9273         mutex_enter(&mptsas_log_mutex);
9274 
9275         va_start(ap, fmt);
9276         (void) vsprintf(mptsas_log_buf, fmt, ap);
9277         va_end(ap);
9278 
9279         if (level == CE_CONT) {
9280                 scsi_log(dev, mptsas_label, level, "%s\n", mptsas_log_buf);
9281         } else {
9282                 scsi_log(dev, mptsas_label, level, "%s", mptsas_log_buf);
9283         }
9284 
9285         mutex_exit(&mptsas_log_mutex);
9286 }
9287 
9288 #ifdef MPTSAS_DEBUG


























9289 /*PRINTFLIKE1*/
9290 void
9291 mptsas_printf(char *fmt, ...)
9292 {
9293         dev_info_t      *dev = 0;
9294         va_list         ap;
9295 
9296         mutex_enter(&mptsas_log_mutex);
9297 
9298         va_start(ap, fmt);
9299         (void) vsprintf(mptsas_log_buf, fmt, ap);
9300         va_end(ap);
9301 
9302 #ifdef PROM_PRINTF
9303         prom_printf("%s:\t%s\n", mptsas_label, mptsas_log_buf);
9304 #else
9305         scsi_log(dev, mptsas_label, SCSI_DEBUG, "%s\n", mptsas_log_buf);
9306 #endif
9307         mutex_exit(&mptsas_log_mutex);
9308 }
9309 #endif
9310 
9311 /*
9312  * timeout handling
9313  */
9314 static void
9315 mptsas_watch(void *arg)
9316 {
9317 #ifndef __lock_lint
9318         _NOTE(ARGUNUSED(arg))
9319 #endif
9320 
9321         mptsas_t        *mpt;
9322         uint32_t        doorbell;
9323 
9324         NDBG30(("mptsas_watch"));
9325 


9357                 /*
9358                  * For now, always call mptsas_watchsubr.
9359                  */
9360                 mptsas_watchsubr(mpt);
9361 
9362                 if (mpt->m_options & MPTSAS_OPT_PM) {
9363                         mpt->m_busy = 0;
9364                         (void) pm_idle_component(mpt->m_dip, 0);
9365                 }
9366 
9367                 mutex_exit(&mpt->m_mutex);
9368         }
9369         rw_exit(&mptsas_global_rwlock);
9370 
9371         mutex_enter(&mptsas_global_mutex);
9372         if (mptsas_timeouts_enabled)
9373                 mptsas_timeout_id = timeout(mptsas_watch, NULL, mptsas_tick);
9374         mutex_exit(&mptsas_global_mutex);
9375 }
9376 

9377 static void
9378 mptsas_watchsubr(mptsas_t *mpt)
9379 {
9380         int             i;
9381         mptsas_cmd_t    *cmd;
9382         mptsas_target_t *ptgt = NULL;


9383 
9384         ASSERT(MUTEX_HELD(&mpt->m_mutex));
9385 
9386         NDBG30(("mptsas_watchsubr: mpt=0x%p", (void *)mpt));

9387 
9388 #ifdef MPTSAS_TEST
9389         if (mptsas_enable_untagged) {
9390                 mptsas_test_untagged++;





9391         }
9392 #endif

9393 
9394         /*
9395          * Check for commands stuck in active slot
9396          * Account for TM requests, which use the last SMID.
9397          */
9398         for (i = 0; i <= mpt->m_active->m_n_normal; i++) {
9399                 if ((cmd = mpt->m_active->m_slot[i]) != NULL) {

9400                         if ((cmd->cmd_flags & CFLAG_CMDIOC) == 0) {
9401                                 cmd->cmd_active_timeout -=
9402                                     mptsas_scsi_watchdog_tick;
9403                                 if (cmd->cmd_active_timeout <= 0) {
9404                                         /*
9405                                          * There seems to be a command stuck
9406                                          * in the active slot.  Drain throttle.
9407                                          */
9408                                         mptsas_set_throttle(mpt,
9409                                             cmd->cmd_tgt_addr,
9410                                             DRAIN_THROTTLE);
9411                                 }
9412                         }
9413                         if ((cmd->cmd_flags & CFLAG_PASSTHRU) ||
9414                             (cmd->cmd_flags & CFLAG_CONFIG) ||
9415                             (cmd->cmd_flags & CFLAG_FW_DIAG)) {
9416                                 cmd->cmd_active_timeout -=
9417                                     mptsas_scsi_watchdog_tick;
9418                                 if (cmd->cmd_active_timeout <= 0) {
9419                                         /*
9420                                          * passthrough command timeout
9421                                          */
9422                                         cmd->cmd_flags |= (CFLAG_FINISHED |
9423                                             CFLAG_TIMEOUT);
9424                                         cv_broadcast(&mpt->m_passthru_cv);
9425                                         cv_broadcast(&mpt->m_config_cv);
9426                                         cv_broadcast(&mpt->m_fw_diag_cv);
9427                                 }
9428                         }
9429                 }
9430         }
9431 
9432         for (ptgt = refhash_first(mpt->m_targets); ptgt != NULL;
9433             ptgt = refhash_next(mpt->m_targets, ptgt)) {

9434                 /*
9435                  * If we were draining due to a qfull condition,
9436                  * go back to full throttle.
9437                  */
9438                 if ((ptgt->m_t_throttle < MAX_THROTTLE) &&
9439                     (ptgt->m_t_throttle > HOLD_THROTTLE) &&
9440                     (ptgt->m_t_ncmds < ptgt->m_t_throttle)) {
9441                         mptsas_set_throttle(mpt, ptgt, MAX_THROTTLE);
9442                         mptsas_restart_hba(mpt);
9443                 }
9444 
9445                 if ((ptgt->m_t_ncmds > 0) &&
9446                     (ptgt->m_timebase)) {






9447 
9448                         if (ptgt->m_timebase <=
9449                             mptsas_scsi_watchdog_tick) {
9450                                 ptgt->m_timebase +=
9451                                     mptsas_scsi_watchdog_tick;
9452                                 continue;
9453                         }







9454 
9455                         ptgt->m_timeout -= mptsas_scsi_watchdog_tick;









9456 
9457                         if (ptgt->m_timeout < 0) {
9458                                 mptsas_cmd_timeout(mpt, ptgt->m_devhdl);
9459                                 continue;
9460                         }
9461 
9462                         if ((ptgt->m_timeout) <=
9463                             mptsas_scsi_watchdog_tick) {
9464                                 NDBG23(("pending timeout"));
9465                                 mptsas_set_throttle(mpt, ptgt,
9466                                     DRAIN_THROTTLE);
9467                         }

9468                 }


9469         }
9470 }
9471 
9472 /*
9473  * timeout recovery
9474  */
9475 static void
9476 mptsas_cmd_timeout(mptsas_t *mpt, uint16_t devhdl)
9477 {













9478 
9479         NDBG29(("mptsas_cmd_timeout: target=%d", devhdl));
9480         mptsas_log(mpt, CE_WARN, "Disconnected command timeout for "
9481             "Target %d", devhdl);

9482 
9483         /*
9484          * If the current target is not the target passed in,
9485          * try to reset that target.
9486          */
9487         NDBG29(("mptsas_cmd_timeout: device reset"));
9488         if (mptsas_do_scsi_reset(mpt, devhdl) != TRUE) {
9489                 mptsas_log(mpt, CE_WARN, "Target %d reset for command timeout "
9490                     "recovery failed!", devhdl);
9491         }
9492 }
9493 
9494 /*
9495  * Device / Hotplug control
9496  */
9497 static int
9498 mptsas_scsi_quiesce(dev_info_t *dip)
9499 {
9500         mptsas_t        *mpt;
9501         scsi_hba_tran_t *tran;
9502 
9503         tran = ddi_get_driver_private(dip);
9504         if (tran == NULL || (mpt = TRAN2MPT(tran)) == NULL)
9505                 return (-1);


9514         scsi_hba_tran_t *tran;
9515 
9516         tran = ddi_get_driver_private(dip);
9517         if (tran == NULL || (mpt = TRAN2MPT(tran)) == NULL)
9518                 return (-1);
9519 
9520         return (mptsas_unquiesce_bus(mpt));
9521 }
9522 
9523 static int
9524 mptsas_quiesce_bus(mptsas_t *mpt)
9525 {
9526         mptsas_target_t *ptgt = NULL;
9527 
9528         NDBG28(("mptsas_quiesce_bus"));
9529         mutex_enter(&mpt->m_mutex);
9530 
9531         /* Set all the throttles to zero */
9532         for (ptgt = refhash_first(mpt->m_targets); ptgt != NULL;
9533             ptgt = refhash_next(mpt->m_targets, ptgt)) {
9534                 mptsas_set_throttle(mpt, ptgt, HOLD_THROTTLE);
9535         }
9536 
9537         /* If there are any outstanding commands in the queue */
9538         if (mpt->m_ncmds) {
9539                 mpt->m_softstate |= MPTSAS_SS_DRAINING;
9540                 mpt->m_quiesce_timeid = timeout(mptsas_ncmds_checkdrain,
9541                     mpt, (MPTSAS_QUIESCE_TIMEOUT * drv_usectohz(1000000)));
9542                 if (cv_wait_sig(&mpt->m_cv, &mpt->m_mutex) == 0) {
9543                         /*
9544                          * Quiesce has been interrupted
9545                          */
9546                         mpt->m_softstate &= ~MPTSAS_SS_DRAINING;
9547                         for (ptgt = refhash_first(mpt->m_targets); ptgt != NULL;
9548                             ptgt = refhash_next(mpt->m_targets, ptgt)) {
9549                                 mptsas_set_throttle(mpt, ptgt, MAX_THROTTLE);

9550                         }
9551                         mptsas_restart_hba(mpt);
9552                         if (mpt->m_quiesce_timeid != 0) {
9553                                 timeout_id_t tid = mpt->m_quiesce_timeid;
9554                                 mpt->m_quiesce_timeid = 0;
9555                                 mutex_exit(&mpt->m_mutex);
9556                                 (void) untimeout(tid);
9557                                 return (-1);
9558                         }
9559                         mutex_exit(&mpt->m_mutex);
9560                         return (-1);
9561                 } else {
9562                         /* Bus has been quiesced */
9563                         ASSERT(mpt->m_quiesce_timeid == 0);
9564                         mpt->m_softstate &= ~MPTSAS_SS_DRAINING;
9565                         mpt->m_softstate |= MPTSAS_SS_QUIESCED;
9566                         mutex_exit(&mpt->m_mutex);
9567                         return (0);
9568                 }
9569         }
9570         /* Bus was not busy - QUIESCED */
9571         mutex_exit(&mpt->m_mutex);
9572 
9573         return (0);
9574 }
9575 
9576 static int
9577 mptsas_unquiesce_bus(mptsas_t *mpt)
9578 {
9579         mptsas_target_t *ptgt = NULL;
9580 
9581         NDBG28(("mptsas_unquiesce_bus"));
9582         mutex_enter(&mpt->m_mutex);
9583         mpt->m_softstate &= ~MPTSAS_SS_QUIESCED;
9584         for (ptgt = refhash_first(mpt->m_targets); ptgt != NULL;
9585             ptgt = refhash_next(mpt->m_targets, ptgt)) {
9586                 mptsas_set_throttle(mpt, ptgt, MAX_THROTTLE);
9587         }
9588         mptsas_restart_hba(mpt);
9589         mutex_exit(&mpt->m_mutex);
9590         return (0);
9591 }
9592 
9593 static void
9594 mptsas_ncmds_checkdrain(void *arg)
9595 {
9596         mptsas_t        *mpt = arg;
9597         mptsas_target_t *ptgt = NULL;
9598 
9599         mutex_enter(&mpt->m_mutex);
9600         if (mpt->m_softstate & MPTSAS_SS_DRAINING) {
9601                 mpt->m_quiesce_timeid = 0;
9602                 if (mpt->m_ncmds == 0) {
9603                         /* Command queue has been drained */
9604                         cv_signal(&mpt->m_cv);
9605                 } else {
9606                         /*
9607                          * The throttle may have been reset because
9608                          * of a SCSI bus reset
9609                          */
9610                         for (ptgt = refhash_first(mpt->m_targets); ptgt != NULL;
9611                             ptgt = refhash_next(mpt->m_targets, ptgt)) {
9612                                 mptsas_set_throttle(mpt, ptgt, HOLD_THROTTLE);

9613                         }
9614 
9615                         mpt->m_quiesce_timeid = timeout(mptsas_ncmds_checkdrain,
9616                             mpt, (MPTSAS_QUIESCE_TIMEOUT *
9617                             drv_usectohz(1000000)));
9618                 }
9619         }
9620         mutex_exit(&mpt->m_mutex);
9621 }
9622 
9623 /*ARGSUSED*/
9624 static void
9625 mptsas_dump_cmd(mptsas_t *mpt, mptsas_cmd_t *cmd)
9626 {
9627         int     i;
9628         uint8_t *cp = (uchar_t *)cmd->cmd_pkt->pkt_cdbp;
9629         char    buf[128];
9630 
9631         buf[0] = '\0';
9632         NDBG25(("?Cmd (0x%p) dump for Target %d Lun %d:\n", (void *)cmd,
9633             Tgt(cmd), Lun(cmd)));
9634         (void) sprintf(&buf[0], "\tcdb=[");
9635         for (i = 0; i < (int)cmd->cmd_cdblen; i++) {
9636                 (void) sprintf(&buf[strlen(buf)], " 0x%x", *cp++);
9637         }
9638         (void) sprintf(&buf[strlen(buf)], " ]");
9639         NDBG25(("?%s\n", buf));
9640         NDBG25(("?pkt_flags=0x%x pkt_statistics=0x%x pkt_state=0x%x\n",
9641             cmd->cmd_pkt->pkt_flags, cmd->cmd_pkt->pkt_statistics,
9642             cmd->cmd_pkt->pkt_state));
9643         NDBG25(("?pkt_scbp=0x%x cmd_flags=0x%x\n", cmd->cmd_pkt->pkt_scbp ?
9644             *(cmd->cmd_pkt->pkt_scbp) : 0, cmd->cmd_flags));
9645 }
9646 
9647 static void




















































































9648 mptsas_start_passthru(mptsas_t *mpt, mptsas_cmd_t *cmd)
9649 {
9650         caddr_t                 memp;
9651         pMPI2RequestHeader_t    request_hdrp;
9652         struct scsi_pkt         *pkt = cmd->cmd_pkt;
9653         mptsas_pt_request_t     *pt = pkt->pkt_ha_private;
9654         uint32_t                request_size, data_size, dataout_size;
9655         uint32_t                direction;
9656         ddi_dma_cookie_t        data_cookie;
9657         ddi_dma_cookie_t        dataout_cookie;
9658         uint32_t                request_desc_low, request_desc_high = 0;
9659         uint32_t                i, sense_bufp;
9660         uint8_t                 desc_type;
9661         uint8_t                 *request, function;
9662         ddi_dma_handle_t        dma_hdl = mpt->m_dma_req_frame_hdl;
9663         ddi_acc_handle_t        acc_hdl = mpt->m_acc_req_frame_hdl;
9664 
9665         desc_type = MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE;
9666 
9667         request = pt->request;
9668         direction = pt->direction;
9669         request_size = pt->request_size;
9670         data_size = pt->data_size;
9671         dataout_size = pt->dataout_size;
9672         data_cookie = pt->data_cookie;
9673         dataout_cookie = pt->dataout_cookie;
9674 
9675         /*
9676          * Store the passthrough message in memory location
9677          * corresponding to our slot number
9678          */
9679         memp = mpt->m_req_frame + (mpt->m_req_frame_size * cmd->cmd_slot);
9680         request_hdrp = (pMPI2RequestHeader_t)memp;
9681         bzero(memp, mpt->m_req_frame_size);
9682 
9683         for (i = 0; i < request_size; i++) {
9684                 bcopy(request + i, memp + i, 1);
9685         }
9686 
9687         if (data_size || dataout_size) {
9688                 pMpi2SGESimple64_t      sgep;
9689                 uint32_t                sge_flags;
9690 
9691                 sgep = (pMpi2SGESimple64_t)((uint8_t *)request_hdrp +
9692                     request_size);
9693                 if (dataout_size) {

9694 
9695                         sge_flags = dataout_size |
9696                             ((uint32_t)(MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
9697                             MPI2_SGE_FLAGS_END_OF_BUFFER |
9698                             MPI2_SGE_FLAGS_HOST_TO_IOC |
9699                             MPI2_SGE_FLAGS_64_BIT_ADDRESSING) <<
9700                             MPI2_SGE_FLAGS_SHIFT);
9701                         ddi_put32(acc_hdl, &sgep->FlagsLength, sge_flags);
9702                         ddi_put32(acc_hdl, &sgep->Address.Low,
9703                             (uint32_t)(dataout_cookie.dmac_laddress &
9704                             0xffffffffull));
9705                         ddi_put32(acc_hdl, &sgep->Address.High,
9706                             (uint32_t)(dataout_cookie.dmac_laddress
9707                             >> 32));
9708                         sgep++;
9709                 }
9710                 sge_flags = data_size;
9711                 sge_flags |= ((uint32_t)(MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
9712                     MPI2_SGE_FLAGS_LAST_ELEMENT |
9713                     MPI2_SGE_FLAGS_END_OF_BUFFER |
9714                     MPI2_SGE_FLAGS_END_OF_LIST |
9715                     MPI2_SGE_FLAGS_64_BIT_ADDRESSING) <<
9716                     MPI2_SGE_FLAGS_SHIFT);
9717                 if (direction == MPTSAS_PASS_THRU_DIRECTION_WRITE) {
9718                         sge_flags |= ((uint32_t)(MPI2_SGE_FLAGS_HOST_TO_IOC) <<
9719                             MPI2_SGE_FLAGS_SHIFT);
9720                 } else {
9721                         sge_flags |= ((uint32_t)(MPI2_SGE_FLAGS_IOC_TO_HOST) <<
9722                             MPI2_SGE_FLAGS_SHIFT);
9723                 }
9724                 ddi_put32(acc_hdl, &sgep->FlagsLength,
9725                     sge_flags);
9726                 ddi_put32(acc_hdl, &sgep->Address.Low,
9727                     (uint32_t)(data_cookie.dmac_laddress &
9728                     0xffffffffull));
9729                 ddi_put32(acc_hdl, &sgep->Address.High,
9730                     (uint32_t)(data_cookie.dmac_laddress >> 32));
9731         }
9732 
9733         function = request_hdrp->Function;
9734         if ((function == MPI2_FUNCTION_SCSI_IO_REQUEST) ||
9735             (function == MPI2_FUNCTION_RAID_SCSI_IO_PASSTHROUGH)) {
9736                 pMpi2SCSIIORequest_t    scsi_io_req;
9737 

9738                 scsi_io_req = (pMpi2SCSIIORequest_t)request_hdrp;
9739                 /*
9740                  * Put SGE for data and data_out buffer at the end of
9741                  * scsi_io_request message header.(64 bytes in total)
9742                  * Following above SGEs, the residual space will be
9743                  * used by sense data.
9744                  */
9745                 ddi_put8(acc_hdl,
9746                     &scsi_io_req->SenseBufferLength,
9747                     (uint8_t)(request_size - 64));
9748 
9749                 sense_bufp = mpt->m_req_frame_dma_addr +
9750                     (mpt->m_req_frame_size * cmd->cmd_slot);
9751                 sense_bufp += 64;
9752                 ddi_put32(acc_hdl,
9753                     &scsi_io_req->SenseBufferLowAddress, sense_bufp);
9754 
9755                 /*
9756                  * Set SGLOffset0 value
9757                  */
9758                 ddi_put8(acc_hdl, &scsi_io_req->SGLOffset0,
9759                     offsetof(MPI2_SCSI_IO_REQUEST, SGL) / 4);
9760 
9761                 /*
9762                  * Setup descriptor info.  RAID passthrough must use the
9763                  * default request descriptor which is already set, so if this
9764                  * is a SCSI IO request, change the descriptor to SCSI IO.
9765                  */
9766                 if (function == MPI2_FUNCTION_SCSI_IO_REQUEST) {
9767                         desc_type = MPI2_REQ_DESCRIPT_FLAGS_SCSI_IO;
9768                         request_desc_high = (ddi_get16(acc_hdl,
9769                             &scsi_io_req->DevHandle) << 16);
9770                 }
9771         }
9772 
9773         /*
9774          * We must wait till the message has been completed before
9775          * beginning the next message so we wait for this one to
9776          * finish.
9777          */
9778         (void) ddi_dma_sync(dma_hdl, 0, 0, DDI_DMA_SYNC_FORDEV);
9779         request_desc_low = (cmd->cmd_slot << 16) + desc_type;
9780         cmd->cmd_rfm = NULL;
9781         MPTSAS_START_CMD(mpt, request_desc_low, request_desc_high);
9782         if ((mptsas_check_dma_handle(dma_hdl) != DDI_SUCCESS) ||
9783             (mptsas_check_acc_handle(acc_hdl) != DDI_SUCCESS)) {
9784                 ddi_fm_service_impact(mpt->m_dip, DDI_SERVICE_UNAFFECTED);
9785         }
9786 }
9787 









































































































































































































































































































































































9788 
9789 
9790 static int
9791 mptsas_do_passthru(mptsas_t *mpt, uint8_t *request, uint8_t *reply,
9792     uint8_t *data, uint32_t request_size, uint32_t reply_size,
9793     uint32_t data_size, uint32_t direction, uint8_t *dataout,
9794     uint32_t dataout_size, short timeout, int mode)
9795 {
9796         mptsas_pt_request_t             pt;
9797         mptsas_dma_alloc_state_t        data_dma_state;
9798         mptsas_dma_alloc_state_t        dataout_dma_state;
9799         caddr_t                         memp;
9800         mptsas_cmd_t                    *cmd = NULL;
9801         struct scsi_pkt                 *pkt;
9802         uint32_t                        reply_len = 0, sense_len = 0;
9803         pMPI2RequestHeader_t            request_hdrp;
9804         pMPI2RequestHeader_t            request_msg;
9805         pMPI2DefaultReply_t             reply_msg;
9806         Mpi2SCSIIOReply_t               rep_msg;
9807         int                             i, status = 0, pt_flags = 0, rv = 0;
9808         int                             rvalue;
9809         uint8_t                         function;
9810 
9811         ASSERT(mutex_owned(&mpt->m_mutex));
9812 
9813         reply_msg = (pMPI2DefaultReply_t)(&rep_msg);


9850                         mptsas_log(mpt, CE_WARN, "failed to alloc DMA "
9851                             "resource");
9852                         goto out;
9853                 }
9854                 pt_flags |= MPTSAS_DATA_ALLOCATED;
9855                 if (direction == MPTSAS_PASS_THRU_DIRECTION_WRITE) {
9856                         mutex_exit(&mpt->m_mutex);
9857                         for (i = 0; i < data_size; i++) {
9858                                 if (ddi_copyin(data + i, (uint8_t *)
9859                                     data_dma_state.memp + i, 1, mode)) {
9860                                         mutex_enter(&mpt->m_mutex);
9861                                         status = EFAULT;
9862                                         mptsas_log(mpt, CE_WARN, "failed to "
9863                                             "copy read data");
9864                                         goto out;
9865                                 }
9866                         }
9867                         mutex_enter(&mpt->m_mutex);
9868                 }
9869         }


9870 
9871         if (dataout_size != 0) {
9872                 dataout_dma_state.size = dataout_size;
9873                 if (mptsas_dma_alloc(mpt, &dataout_dma_state) != DDI_SUCCESS) {
9874                         status = ENOMEM;
9875                         mptsas_log(mpt, CE_WARN, "failed to alloc DMA "
9876                             "resource");
9877                         goto out;
9878                 }
9879                 pt_flags |= MPTSAS_DATAOUT_ALLOCATED;
9880                 mutex_exit(&mpt->m_mutex);
9881                 for (i = 0; i < dataout_size; i++) {
9882                         if (ddi_copyin(dataout + i, (uint8_t *)
9883                             dataout_dma_state.memp + i, 1, mode)) {
9884                                 mutex_enter(&mpt->m_mutex);
9885                                 mptsas_log(mpt, CE_WARN, "failed to copy out"
9886                                     " data");
9887                                 status = EFAULT;
9888                                 goto out;
9889                         }
9890                 }
9891                 mutex_enter(&mpt->m_mutex);
9892         }


9893 
9894         if ((rvalue = (mptsas_request_from_pool(mpt, &cmd, &pkt))) == -1) {
9895                 status = EAGAIN;
9896                 mptsas_log(mpt, CE_NOTE, "event ack command pool is full");
9897                 goto out;
9898         }
9899         pt_flags |= MPTSAS_REQUEST_POOL_CMD;
9900 
9901         bzero((caddr_t)cmd, sizeof (*cmd));
9902         bzero((caddr_t)pkt, scsi_pkt_size());
9903         bzero((caddr_t)&pt, sizeof (pt));
9904 
9905         cmd->ioc_cmd_slot = (uint32_t)(rvalue);
9906 
9907         pt.request = (uint8_t *)request_msg;
9908         pt.direction = direction;

9909         pt.request_size = request_size;
9910         pt.data_size = data_size;
9911         pt.dataout_size = dataout_size;
9912         pt.data_cookie = data_dma_state.cookie;
9913         pt.dataout_cookie = dataout_dma_state.cookie;

9914 
9915         /*
9916          * Form a blank cmd/pkt to store the acknowledgement message
9917          */
9918         pkt->pkt_cdbp                = (opaque_t)&cmd->cmd_cdb[0];
9919         pkt->pkt_scbp                = (opaque_t)&cmd->cmd_scb;
9920         pkt->pkt_ha_private  = (opaque_t)&pt;
9921         pkt->pkt_flags               = FLAG_HEAD;
9922         pkt->pkt_time                = timeout;
9923         cmd->cmd_pkt         = pkt;
9924         cmd->cmd_flags               = CFLAG_CMDIOC | CFLAG_PASSTHRU;
9925 
9926         /*
9927          * Save the command in a slot
9928          */
9929         if (mptsas_save_cmd(mpt, cmd) == TRUE) {
9930                 /*
9931                  * Once passthru command get slot, set cmd_flags
9932                  * CFLAG_PREPARED.
9933                  */


9950         if (cmd->cmd_flags & CFLAG_TIMEOUT) {
9951                 status = ETIMEDOUT;
9952                 mptsas_log(mpt, CE_WARN, "passthrough command timeout");
9953                 pt_flags |= MPTSAS_CMD_TIMEOUT;
9954                 goto out;
9955         }
9956 
9957         if (cmd->cmd_rfm) {
9958                 /*
9959                  * cmd_rfm is zero means the command reply is a CONTEXT
9960                  * reply and no PCI Write to post the free reply SMFA
9961                  * because no reply message frame is used.
9962                  * cmd_rfm is non-zero means the reply is a ADDRESS
9963                  * reply and reply message frame is used.
9964                  */
9965                 pt_flags |= MPTSAS_ADDRESS_REPLY;
9966                 (void) ddi_dma_sync(mpt->m_dma_reply_frame_hdl, 0, 0,
9967                     DDI_DMA_SYNC_FORCPU);
9968                 reply_msg = (pMPI2DefaultReply_t)
9969                     (mpt->m_reply_frame + (cmd->cmd_rfm -
9970                     mpt->m_reply_frame_dma_addr));
9971         }
9972 
9973         mptsas_fma_check(mpt, cmd);
9974         if (pkt->pkt_reason == CMD_TRAN_ERR) {
9975                 status = EAGAIN;
9976                 mptsas_log(mpt, CE_WARN, "passthru fma error");
9977                 goto out;
9978         }
9979         if (pkt->pkt_reason == CMD_RESET) {
9980                 status = EAGAIN;
9981                 mptsas_log(mpt, CE_WARN, "ioc reset abort passthru");
9982                 goto out;
9983         }
9984 
9985         if (pkt->pkt_reason == CMD_INCOMPLETE) {
9986                 status = EIO;
9987                 mptsas_log(mpt, CE_WARN, "passthrough command incomplete");
9988                 goto out;
9989         }
9990 


10106         if (((data->DataSize == 0) &&
10107             (data->DataDirection == MPTSAS_PASS_THRU_DIRECTION_NONE)) ||
10108             ((data->DataSize != 0) &&
10109             ((data->DataDirection == MPTSAS_PASS_THRU_DIRECTION_READ) ||
10110             (data->DataDirection == MPTSAS_PASS_THRU_DIRECTION_WRITE) ||
10111             ((data->DataDirection == MPTSAS_PASS_THRU_DIRECTION_BOTH) &&
10112             (data->DataOutSize != 0))))) {
10113                 if (data->DataDirection == MPTSAS_PASS_THRU_DIRECTION_BOTH) {
10114                         data->DataDirection = MPTSAS_PASS_THRU_DIRECTION_READ;
10115                 } else {
10116                         data->DataOutSize = 0;
10117                 }
10118                 /*
10119                  * Send passthru request messages
10120                  */
10121                 return (mptsas_do_passthru(mpt,
10122                     (uint8_t *)((uintptr_t)data->PtrRequest),
10123                     (uint8_t *)((uintptr_t)data->PtrReply),
10124                     (uint8_t *)((uintptr_t)data->PtrData),
10125                     data->RequestSize, data->ReplySize,
10126                     data->DataSize, data->DataDirection,
10127                     (uint8_t *)((uintptr_t)data->PtrDataOut),
10128                     data->DataOutSize, data->Timeout, mode));
10129         } else {
10130                 return (EINVAL);
10131         }
10132 }
10133 
10134 static uint8_t
10135 mptsas_get_fw_diag_buffer_number(mptsas_t *mpt, uint32_t unique_id)
10136 {
10137         uint8_t index;
10138 
10139         for (index = 0; index < MPI2_DIAG_BUF_TYPE_COUNT; index++) {
10140                 if (mpt->m_fw_diag_buffer_list[index].unique_id == unique_id) {
10141                         return (index);
10142                 }
10143         }
10144 
10145         return (MPTSAS_FW_DIAGNOSTIC_UID_NOT_FOUND);
10146 }
10147 
10148 static void
10149 mptsas_start_diag(mptsas_t *mpt, mptsas_cmd_t *cmd)
10150 {
10151         pMpi2DiagBufferPostRequest_t    pDiag_post_msg;
10152         pMpi2DiagReleaseRequest_t       pDiag_release_msg;
10153         struct scsi_pkt                 *pkt = cmd->cmd_pkt;
10154         mptsas_diag_request_t           *diag = pkt->pkt_ha_private;
10155         uint32_t                        request_desc_low, i;

10156 
10157         ASSERT(mutex_owned(&mpt->m_mutex));
10158 
10159         /*
10160          * Form the diag message depending on the post or release function.
10161          */
10162         if (diag->function == MPI2_FUNCTION_DIAG_BUFFER_POST) {
10163                 pDiag_post_msg = (pMpi2DiagBufferPostRequest_t)
10164                     (mpt->m_req_frame + (mpt->m_req_frame_size *
10165                     cmd->cmd_slot));
10166                 bzero(pDiag_post_msg, mpt->m_req_frame_size);
10167                 ddi_put8(mpt->m_acc_req_frame_hdl, &pDiag_post_msg->Function,
10168                     diag->function);
10169                 ddi_put8(mpt->m_acc_req_frame_hdl, &pDiag_post_msg->BufferType,
10170                     diag->pBuffer->buffer_type);
10171                 ddi_put8(mpt->m_acc_req_frame_hdl,
10172                     &pDiag_post_msg->ExtendedType,
10173                     diag->pBuffer->extended_type);
10174                 ddi_put32(mpt->m_acc_req_frame_hdl,
10175                     &pDiag_post_msg->BufferLength,


10188                     &pDiag_post_msg->BufferAddress.High,
10189                     (uint32_t)(diag->pBuffer->buffer_data.cookie.dmac_laddress
10190                     >> 32));
10191         } else {
10192                 pDiag_release_msg = (pMpi2DiagReleaseRequest_t)
10193                     (mpt->m_req_frame + (mpt->m_req_frame_size *
10194                     cmd->cmd_slot));
10195                 bzero(pDiag_release_msg, mpt->m_req_frame_size);
10196                 ddi_put8(mpt->m_acc_req_frame_hdl,
10197                     &pDiag_release_msg->Function, diag->function);
10198                 ddi_put8(mpt->m_acc_req_frame_hdl,
10199                     &pDiag_release_msg->BufferType,
10200                     diag->pBuffer->buffer_type);
10201         }
10202 
10203         /*
10204          * Send the message
10205          */
10206         (void) ddi_dma_sync(mpt->m_dma_req_frame_hdl, 0, 0,
10207             DDI_DMA_SYNC_FORDEV);
10208         request_desc_low = (cmd->cmd_slot << 16) +
10209             MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE;
10210         cmd->cmd_rfm = NULL;
10211         MPTSAS_START_CMD(mpt, request_desc_low, 0);
10212         if ((mptsas_check_dma_handle(mpt->m_dma_req_frame_hdl) !=
10213             DDI_SUCCESS) ||
10214             (mptsas_check_acc_handle(mpt->m_acc_req_frame_hdl) !=
10215             DDI_SUCCESS)) {
10216                 ddi_fm_service_impact(mpt->m_dip, DDI_SERVICE_UNAFFECTED);
10217         }
10218 }
10219 
10220 static int
10221 mptsas_post_fw_diag_buffer(mptsas_t *mpt,
10222     mptsas_fw_diagnostic_buffer_t *pBuffer, uint32_t *return_code)
10223 {
10224         mptsas_diag_request_t           diag;
10225         int                             status, slot_num, post_flags = 0;
10226         mptsas_cmd_t                    *cmd = NULL;
10227         struct scsi_pkt                 *pkt;
10228         pMpi2DiagBufferPostReply_t      reply;
10229         uint16_t                        iocstatus;
10230         uint32_t                        iocloginfo, transfer_length;
10231 


10289         while ((cmd->cmd_flags & CFLAG_FINISHED) == 0) {
10290                 cv_wait(&mpt->m_fw_diag_cv, &mpt->m_mutex);
10291         }
10292 
10293         if (cmd->cmd_flags & CFLAG_TIMEOUT) {
10294                 status = DDI_FAILURE;
10295                 mptsas_log(mpt, CE_WARN, "Post FW Diag command timeout");
10296                 goto out;
10297         }
10298 
10299         /*
10300          * cmd_rfm points to the reply message if a reply was given.  Check the
10301          * IOCStatus to make sure everything went OK with the FW diag request
10302          * and set buffer flags.
10303          */
10304         if (cmd->cmd_rfm) {
10305                 post_flags |= MPTSAS_ADDRESS_REPLY;
10306                 (void) ddi_dma_sync(mpt->m_dma_reply_frame_hdl, 0, 0,
10307                     DDI_DMA_SYNC_FORCPU);
10308                 reply = (pMpi2DiagBufferPostReply_t)(mpt->m_reply_frame +
10309                     (cmd->cmd_rfm - mpt->m_reply_frame_dma_addr));

10310 
10311                 /*
10312                  * Get the reply message data
10313                  */
10314                 iocstatus = ddi_get16(mpt->m_acc_reply_frame_hdl,
10315                     &reply->IOCStatus);
10316                 iocloginfo = ddi_get32(mpt->m_acc_reply_frame_hdl,
10317                     &reply->IOCLogInfo);
10318                 transfer_length = ddi_get32(mpt->m_acc_reply_frame_hdl,
10319                     &reply->TransferLength);
10320 
10321                 /*
10322                  * If post failed quit.
10323                  */
10324                 if (iocstatus != MPI2_IOCSTATUS_SUCCESS) {
10325                         status = DDI_FAILURE;
10326                         NDBG13(("post FW Diag Buffer failed: IOCStatus=0x%x, "
10327                             "IOCLogInfo=0x%x, TransferLength=0x%x", iocstatus,
10328                             iocloginfo, transfer_length));
10329                         goto out;


10443         while ((cmd->cmd_flags & CFLAG_FINISHED) == 0) {
10444                 cv_wait(&mpt->m_fw_diag_cv, &mpt->m_mutex);
10445         }
10446 
10447         if (cmd->cmd_flags & CFLAG_TIMEOUT) {
10448                 status = DDI_FAILURE;
10449                 mptsas_log(mpt, CE_WARN, "Release FW Diag command timeout");
10450                 goto out;
10451         }
10452 
10453         /*
10454          * cmd_rfm points to the reply message if a reply was given.  Check the
10455          * IOCStatus to make sure everything went OK with the FW diag request
10456          * and set buffer flags.
10457          */
10458         if (cmd->cmd_rfm) {
10459                 rel_flags |= MPTSAS_ADDRESS_REPLY;
10460                 (void) ddi_dma_sync(mpt->m_dma_reply_frame_hdl, 0, 0,
10461                     DDI_DMA_SYNC_FORCPU);
10462                 reply = (pMpi2DiagReleaseReply_t)(mpt->m_reply_frame +
10463                     (cmd->cmd_rfm - mpt->m_reply_frame_dma_addr));

10464 
10465                 /*
10466                  * Get the reply message data
10467                  */
10468                 iocstatus = ddi_get16(mpt->m_acc_reply_frame_hdl,
10469                     &reply->IOCStatus);
10470                 iocloginfo = ddi_get32(mpt->m_acc_reply_frame_hdl,
10471                     &reply->IOCLogInfo);
10472 
10473                 /*
10474                  * If release failed quit.
10475                  */
10476                 if ((iocstatus != MPI2_IOCSTATUS_SUCCESS) ||
10477                     pBuffer->owned_by_firmware) {
10478                         status = DDI_FAILURE;
10479                         NDBG13(("release FW Diag Buffer failed: "
10480                             "IOCStatus=0x%x, IOCLogInfo=0x%x", iocstatus,
10481                             iocloginfo));
10482                         goto out;
10483                 }


11191                  * If we can't determine the PCI data then we fill in FF's for
11192                  * the data to indicate this.
11193                  */
11194                 adapter_data->PCIDeviceHwId = 0xFFFFFFFF;
11195                 adapter_data->MpiPortNumber = 0xFFFFFFFF;
11196                 adapter_data->PciInformation.u.AsDWORD = 0xFFFFFFFF;
11197         }
11198 
11199         /*
11200          * Saved in the mpt->m_fwversion
11201          */
11202         adapter_data->MpiFirmwareVersion = mpt->m_fwversion;
11203 }
11204 
11205 static void
11206 mptsas_read_adapter_data(mptsas_t *mpt, mptsas_adapter_data_t *adapter_data)
11207 {
11208         char    *driver_verstr = MPTSAS_MOD_STRING;
11209 
11210         mptsas_lookup_pci_data(mpt, adapter_data);
11211         adapter_data->AdapterType = MPTIOCTL_ADAPTER_TYPE_SAS2;
11212         adapter_data->PCIDeviceHwId = (uint32_t)mpt->m_devid;
11213         adapter_data->PCIDeviceHwRev = (uint32_t)mpt->m_revid;
11214         adapter_data->SubSystemId = (uint32_t)mpt->m_ssid;
11215         adapter_data->SubsystemVendorId = (uint32_t)mpt->m_svid;
11216         (void) strcpy((char *)&adapter_data->DriverVersion[0], driver_verstr);
11217         adapter_data->BiosVersion = 0;
11218         (void) mptsas_get_bios_page3(mpt, &adapter_data->BiosVersion);
11219 }
11220 
11221 static void
11222 mptsas_read_pci_info(mptsas_t *mpt, mptsas_pci_info_t *pci_info)
11223 {
11224         int     *reg_data, i;
11225         uint_t  reglen;
11226 
11227         /*
11228          * Lookup the 'reg' property and extract the other data
11229          */
11230         if (ddi_prop_lookup_int_array(DDI_DEV_T_ANY, mpt->m_dip,
11231             DDI_PROP_DONTPASS, "reg", &reg_data, &reglen) ==


11465         int                     status = 0;
11466         mptsas_t                *mpt;
11467         mptsas_update_flash_t   flashdata;
11468         mptsas_pass_thru_t      passthru_data;
11469         mptsas_adapter_data_t   adapter_data;
11470         mptsas_pci_info_t       pci_info;
11471         int                     copylen;
11472 
11473         int                     iport_flag = 0;
11474         dev_info_t              *dip = NULL;
11475         mptsas_phymask_t        phymask = 0;
11476         struct devctl_iocdata   *dcp = NULL;
11477         char                    *addr = NULL;
11478         mptsas_target_t         *ptgt = NULL;
11479 
11480         *rval = MPTIOCTL_STATUS_GOOD;
11481         if (secpolicy_sys_config(credp, B_FALSE) != 0) {
11482                 return (EPERM);
11483         }
11484 
11485         mpt = ddi_get_soft_state(mptsas_state, MINOR2INST(getminor(dev)));
11486         if (mpt == NULL) {
11487                 /*
11488                  * Called from iport node, get the states
11489                  */
11490                 iport_flag = 1;
11491                 dip = mptsas_get_dip_from_dev(dev, &phymask);
11492                 if (dip == NULL) {
11493                         return (ENXIO);
11494                 }
11495                 mpt = DIP2MPT(dip);
11496         }
11497         /* Make sure power level is D0 before accessing registers */
11498         mutex_enter(&mpt->m_mutex);
11499         if (mpt->m_options & MPTSAS_OPT_PM) {
11500                 (void) pm_busy_component(mpt->m_dip, 0);
11501                 if (mpt->m_power_level != PM_LEVEL_D0) {
11502                         mutex_exit(&mpt->m_mutex);
11503                         if (pm_raise_power(mpt->m_dip, 0, PM_LEVEL_D0) !=
11504                             DDI_SUCCESS) {
11505                                 mptsas_log(mpt, CE_WARN,
11506                                     "mptsas%d: mptsas_ioctl: Raise power "
11507                                     "request failed.", mpt->m_instance);
11508                                 (void) pm_idle_component(mpt->m_dip, 0);
11509                                 return (ENXIO);
11510                         }
11511                 } else {
11512                         mutex_exit(&mpt->m_mutex);
11513                 }
11514         } else {
11515                 mutex_exit(&mpt->m_mutex);
11516         }
11517 
11518         if (iport_flag) {
11519                 status = scsi_hba_ioctl(dev, cmd, data, mode, credp, rval);
11520                 if (status != 0) {
11521                         goto out;
11522                 }
11523                 /*
11524                  * The following code control the OK2RM LED, it doesn't affect
11525                  * the ioctl return status.
11526                  */


11726 {
11727         int             rval = DDI_SUCCESS;
11728         mptsas_target_t *ptgt = NULL;
11729 
11730         ASSERT(mutex_owned(&mpt->m_mutex));
11731 
11732         /*
11733          * Set a flag telling I/O path that we're processing a reset.  This is
11734          * needed because after the reset is complete, the hash table still
11735          * needs to be rebuilt.  If I/Os are started before the hash table is
11736          * rebuilt, I/O errors will occur.  This flag allows I/Os to be marked
11737          * so that they can be retried.
11738          */
11739         mpt->m_in_reset = TRUE;
11740 
11741         /*
11742          * Set all throttles to HOLD
11743          */
11744         for (ptgt = refhash_first(mpt->m_targets); ptgt != NULL;
11745             ptgt = refhash_next(mpt->m_targets, ptgt)) {
11746                 mptsas_set_throttle(mpt, ptgt, HOLD_THROTTLE);
11747         }
11748 
11749         /*
11750          * Disable interrupts
11751          */
11752         MPTSAS_DISABLE_INTR(mpt);
11753 
11754         /*
11755          * Abort all commands: outstanding commands, commands in waitq and
11756          * tx_waitq.
11757          */
11758         mptsas_flush_hba(mpt);
11759 
11760         /*
11761          * Reinitialize the chip.
11762          */
11763         if (mptsas_init_chip(mpt, FALSE) == DDI_FAILURE) {
11764                 rval = DDI_FAILURE;
11765         }
11766 
11767         /*
11768          * Enable interrupts again
11769          */
11770         MPTSAS_ENABLE_INTR(mpt);
11771 
11772         /*
11773          * If mptsas_init_chip was successful, update the driver data.
11774          */
11775         if (rval == DDI_SUCCESS) {
11776                 mptsas_update_driver_data(mpt);
11777         }
11778 
11779         /*
11780          * Reset the throttles
11781          */
11782         for (ptgt = refhash_first(mpt->m_targets); ptgt != NULL;
11783             ptgt = refhash_next(mpt->m_targets, ptgt)) {
11784                 mptsas_set_throttle(mpt, ptgt, MAX_THROTTLE);
11785         }
11786 
11787         mptsas_doneq_empty(mpt);
11788         mptsas_restart_hba(mpt);
11789 
11790         if (rval != DDI_SUCCESS) {
11791                 mptsas_fm_ereport(mpt, DDI_FM_DEVICE_NO_RESPONSE);
11792                 ddi_fm_service_impact(mpt->m_dip, DDI_SERVICE_LOST);
11793         }
11794 
11795         /*
11796          * Clear the reset flag so that I/Os can continue.
11797          */
11798         mpt->m_in_reset = FALSE;
11799 
11800         return (rval);
11801 }
11802 
11803 static int
11804 mptsas_init_chip(mptsas_t *mpt, int first_time)
11805 {
11806         ddi_dma_cookie_t        cookie;
11807         uint32_t                i;

11808         int                     rval;
11809 
11810         /*
11811          * Check to see if the firmware image is valid
11812          */
11813         if (ddi_get32(mpt->m_datap, &mpt->m_reg->HostDiagnostic) &
11814             MPI2_DIAG_FLASH_BAD_SIG) {
11815                 mptsas_log(mpt, CE_WARN, "mptsas bad flash signature!");
11816                 goto fail;
11817         }
11818 
11819         /*
11820          * Reset the chip
11821          */
11822         rval = mptsas_ioc_reset(mpt, first_time);
11823         if (rval == MPTSAS_RESET_FAIL) {
11824                 mptsas_log(mpt, CE_WARN, "hard reset failed!");
11825                 goto fail;
11826         }
11827 


11830         }
11831         /*
11832          * Setup configuration space
11833          */
11834         if (mptsas_config_space_init(mpt) == FALSE) {
11835                 mptsas_log(mpt, CE_WARN, "mptsas_config_space_init "
11836                     "failed!");
11837                 goto fail;
11838         }
11839 
11840         /*
11841          * IOC facts can change after a diag reset so all buffers that are
11842          * based on these numbers must be de-allocated and re-allocated.  Get
11843          * new IOC facts each time chip is initialized.
11844          */
11845         if (mptsas_ioc_get_facts(mpt) == DDI_FAILURE) {
11846                 mptsas_log(mpt, CE_WARN, "mptsas_ioc_get_facts failed");
11847                 goto fail;
11848         }
11849 










11850         mpt->m_targets = refhash_create(MPTSAS_TARGET_BUCKET_COUNT,
11851             mptsas_target_addr_hash, mptsas_target_addr_cmp,
11852             mptsas_target_free, sizeof (mptsas_target_t),
11853             offsetof(mptsas_target_t, m_link),
11854             offsetof(mptsas_target_t, m_addr), KM_SLEEP);
11855 
11856         if (mptsas_alloc_active_slots(mpt, KM_SLEEP)) {
11857                 goto fail;
11858         }
11859         /*
11860          * Allocate request message frames, reply free queue, reply descriptor
11861          * post queue, and reply message frames using latest IOC facts.
11862          */
11863         if (mptsas_alloc_request_frames(mpt) == DDI_FAILURE) {
11864                 mptsas_log(mpt, CE_WARN, "mptsas_alloc_request_frames failed");
11865                 goto fail;
11866         }




11867         if (mptsas_alloc_free_queue(mpt) == DDI_FAILURE) {
11868                 mptsas_log(mpt, CE_WARN, "mptsas_alloc_free_queue failed!");
11869                 goto fail;
11870         }
11871         if (mptsas_alloc_post_queue(mpt) == DDI_FAILURE) {
11872                 mptsas_log(mpt, CE_WARN, "mptsas_alloc_post_queue failed!");
11873                 goto fail;
11874         }
11875         if (mptsas_alloc_reply_frames(mpt) == DDI_FAILURE) {
11876                 mptsas_log(mpt, CE_WARN, "mptsas_alloc_reply_frames failed!");
11877                 goto fail;
11878         }
11879 
11880 mur:
11881         /*
11882          * Re-Initialize ioc to operational state
11883          */
11884         if (mptsas_ioc_init(mpt) == DDI_FAILURE) {
11885                 mptsas_log(mpt, CE_WARN, "mptsas_ioc_init failed");
11886                 goto fail;
11887         }
11888 
11889         mptsas_alloc_reply_args(mpt);
11890 
11891         /*
11892          * Initialize reply post index.  Reply free index is initialized after
11893          * the next loop.
11894          */
11895         mpt->m_post_index = 0;
11896 
11897         /*
11898          * Initialize the Reply Free Queue with the physical addresses of our
11899          * reply frames.
11900          */
11901         cookie.dmac_address = mpt->m_reply_frame_dma_addr;
11902         for (i = 0; i < mpt->m_max_replies; i++) {
11903                 ddi_put32(mpt->m_acc_free_queue_hdl,
11904                     &((uint32_t *)(void *)mpt->m_free_queue)[i],
11905                     cookie.dmac_address);
11906                 cookie.dmac_address += mpt->m_reply_frame_size;
11907         }
11908         (void) ddi_dma_sync(mpt->m_dma_free_queue_hdl, 0, 0,
11909             DDI_DMA_SYNC_FORDEV);
11910 
11911         /*
11912          * Initialize the reply free index to one past the last frame on the
11913          * queue.  This will signify that the queue is empty to start with.
11914          */
11915         mpt->m_free_index = i;
11916         ddi_put32(mpt->m_datap, &mpt->m_reg->ReplyFreeHostIndex, i);
11917 
11918         /*
11919          * Initialize the reply post queue to 0xFFFFFFFF,0xFFFFFFFF's.

11920          */


11921         for (i = 0; i < mpt->m_post_queue_depth; i++) {
11922                 ddi_put64(mpt->m_acc_post_queue_hdl,
11923                     &((uint64_t *)(void *)mpt->m_post_queue)[i],
11924                     0xFFFFFFFFFFFFFFFF);
11925         }



11926         (void) ddi_dma_sync(mpt->m_dma_post_queue_hdl, 0, 0,
11927             DDI_DMA_SYNC_FORDEV);
11928 
11929         /*








11930          * Enable ports
11931          */
11932         if (mptsas_ioc_enable_port(mpt) == DDI_FAILURE) {
11933                 mptsas_log(mpt, CE_WARN, "mptsas_ioc_enable_port failed");
11934                 goto fail;
11935         }
11936 
11937         /*
11938          * enable events
11939          */
11940         if (mptsas_ioc_enable_event_notification(mpt)) {


11941                 goto fail;
11942         }
11943 
11944         /*
11945          * We need checks in attach and these.
11946          * chip_init is called in mult. places
11947          */
11948 
11949         if ((mptsas_check_dma_handle(mpt->m_dma_req_frame_hdl) !=
11950             DDI_SUCCESS) ||


11951             (mptsas_check_dma_handle(mpt->m_dma_reply_frame_hdl) !=
11952             DDI_SUCCESS) ||
11953             (mptsas_check_dma_handle(mpt->m_dma_free_queue_hdl) !=
11954             DDI_SUCCESS) ||
11955             (mptsas_check_dma_handle(mpt->m_dma_post_queue_hdl) !=
11956             DDI_SUCCESS) ||
11957             (mptsas_check_dma_handle(mpt->m_hshk_dma_hdl) !=
11958             DDI_SUCCESS)) {
11959                 ddi_fm_service_impact(mpt->m_dip, DDI_SERVICE_UNAFFECTED);
11960                 goto fail;
11961         }
11962 
11963         /* Check all acc handles */
11964         if ((mptsas_check_acc_handle(mpt->m_datap) != DDI_SUCCESS) ||
11965             (mptsas_check_acc_handle(mpt->m_acc_req_frame_hdl) !=
11966             DDI_SUCCESS) ||


11967             (mptsas_check_acc_handle(mpt->m_acc_reply_frame_hdl) !=
11968             DDI_SUCCESS) ||
11969             (mptsas_check_acc_handle(mpt->m_acc_free_queue_hdl) !=
11970             DDI_SUCCESS) ||
11971             (mptsas_check_acc_handle(mpt->m_acc_post_queue_hdl) !=
11972             DDI_SUCCESS) ||
11973             (mptsas_check_acc_handle(mpt->m_hshk_acc_hdl) !=
11974             DDI_SUCCESS) ||
11975             (mptsas_check_acc_handle(mpt->m_config_handle) !=
11976             DDI_SUCCESS)) {
11977                 ddi_fm_service_impact(mpt->m_dip, DDI_SERVICE_UNAFFECTED);
11978                 goto fail;
11979         }
11980 
11981         return (DDI_SUCCESS);
11982 
11983 fail:
11984         return (DDI_FAILURE);
11985 }
11986 


12015                 if (++cap_count > 48) {
12016                         mptsas_log(mpt, CE_WARN,
12017                             "too many device capabilities.\n");
12018                         break;
12019                 }
12020                 if (caps_ptr < 64) {
12021                         mptsas_log(mpt, CE_WARN,
12022                             "capabilities pointer 0x%x out of range.\n",
12023                             caps_ptr);
12024                         break;
12025                 }
12026 
12027                 /*
12028                  * Get next capability and check that it is valid.
12029                  * For now, we only support power management.
12030                  */
12031                 cap = pci_config_get8(mpt->m_config_handle, caps_ptr);
12032                 switch (cap) {
12033                         case PCI_CAP_ID_PM:
12034                                 mptsas_log(mpt, CE_NOTE,
12035                                     "?mptsas%d supports power management.\n",
12036                                     mpt->m_instance);
12037                                 mpt->m_options |= MPTSAS_OPT_PM;
12038 
12039                                 /* Save PMCSR offset */
12040                                 mpt->m_pmcsr_offset = caps_ptr + PCI_PMCSR;
12041                                 break;












12042                         /*
12043                          * The following capabilities are valid.  Any others
12044                          * will cause a message to be logged.
12045                          */
12046                         case PCI_CAP_ID_VPD:
12047                         case PCI_CAP_ID_MSI:
12048                         case PCI_CAP_ID_PCIX:
12049                         case PCI_CAP_ID_PCI_E:
12050                         case PCI_CAP_ID_MSI_X:
12051                                 break;
12052                         default:
12053                                 mptsas_log(mpt, CE_NOTE,
12054                                     "?mptsas%d unrecognized capability "
12055                                     "0x%x.\n", mpt->m_instance, cap);
12056                                 break;
12057                 }
12058 
12059                 /*
12060                  * Get next capabilities pointer and clear bits 0,1.
12061                  */
12062                 caps_ptr = P2ALIGN(pci_config_get8(mpt->m_config_handle,
12063                     (caps_ptr + PCI_CAP_NEXT_PTR)), 4);
12064         }
12065         return (TRUE);
12066 }
12067 
12068 static int
12069 mptsas_init_pm(mptsas_t *mpt)
12070 {
12071         char            pmc_name[16];
12072         char            *pmc[] = {
12073                                 NULL,
12074                                 "0=Off (PCI D3 State)",
12075                                 "3=On (PCI D0 State)",
12076                                 NULL
12077                         };
12078         uint16_t        pmcsr_stat;
12079 
12080         if (mptsas_get_pci_cap(mpt) == FALSE) {
12081                 return (DDI_FAILURE);
12082         }
12083         /*
12084          * If PCI's capability does not support PM, then don't need
12085          * to registe the pm-components
12086          */
12087         if (!(mpt->m_options & MPTSAS_OPT_PM))
12088                 return (DDI_SUCCESS);
12089         /*
12090          * If power management is supported by this chip, create
12091          * pm-components property for the power management framework
12092          */
12093         (void) sprintf(pmc_name, "NAME=mptsas%d", mpt->m_instance);
12094         pmc[0] = pmc_name;
12095         if (ddi_prop_update_string_array(DDI_DEV_T_NONE, mpt->m_dip,
12096             "pm-components", pmc, 3) != DDI_PROP_SUCCESS) {
12097                 mpt->m_options &= ~MPTSAS_OPT_PM;
12098                 mptsas_log(mpt, CE_WARN,
12099                     "mptsas%d: pm-component property creation failed.",
12100                     mpt->m_instance);
12101                 return (DDI_FAILURE);
12102         }
12103 
12104         /*
12105          * Power on device.
12106          */
12107         (void) pm_busy_component(mpt->m_dip, 0);
12108         pmcsr_stat = pci_config_get16(mpt->m_config_handle,
12109             mpt->m_pmcsr_offset);
12110         if ((pmcsr_stat & PCI_PMCSR_STATE_MASK) != PCI_PMCSR_D0) {
12111                 mptsas_log(mpt, CE_WARN, "mptsas%d: Power up the device",
12112                     mpt->m_instance);
12113                 pci_config_put16(mpt->m_config_handle, mpt->m_pmcsr_offset,
12114                     PCI_PMCSR_D0);
12115         }
12116         if (pm_power_has_changed(mpt->m_dip, 0, PM_LEVEL_D0) != DDI_SUCCESS) {
12117                 mptsas_log(mpt, CE_WARN, "pm_power_has_changed failed");
12118                 return (DDI_FAILURE);
12119         }
12120         mpt->m_power_level = PM_LEVEL_D0;
12121         /*
12122          * Set pm idle delay.
12123          */
12124         mpt->m_pm_idle_delay = ddi_prop_get_int(DDI_DEV_T_ANY,
12125             mpt->m_dip, 0, "mptsas-pm-idle-delay", MPTSAS_PM_IDLE_TIMEOUT);
12126 
12127         return (DDI_SUCCESS);
12128 }
12129 
12130 static int
12131 mptsas_register_intrs(mptsas_t *mpt)
12132 {
12133         dev_info_t *dip;
12134         int intr_types;
12135 
12136         dip = mpt->m_dip;
12137 
12138         /* Get supported interrupt types */
12139         if (ddi_intr_get_supported_types(dip, &intr_types) != DDI_SUCCESS) {
12140                 mptsas_log(mpt, CE_WARN, "ddi_intr_get_supported_types "
12141                     "failed\n");
12142                 return (FALSE);
12143         }
12144 
12145         NDBG6(("ddi_intr_get_supported_types() returned: 0x%x", intr_types));
12146 
12147         /*











12148          * Try MSI, but fall back to FIXED
12149          */
12150         if (mptsas_enable_msi && (intr_types & DDI_INTR_TYPE_MSI)) {
12151                 if (mptsas_add_intrs(mpt, DDI_INTR_TYPE_MSI) == DDI_SUCCESS) {
12152                         NDBG0(("Using MSI interrupt type"));
12153                         mpt->m_intr_type = DDI_INTR_TYPE_MSI;
12154                         return (TRUE);
12155                 }
12156         }
12157         if (intr_types & DDI_INTR_TYPE_FIXED) {
12158                 if (mptsas_add_intrs(mpt, DDI_INTR_TYPE_FIXED) == DDI_SUCCESS) {
12159                         NDBG0(("Using FIXED interrupt type"));
12160                         mpt->m_intr_type = DDI_INTR_TYPE_FIXED;
12161                         return (TRUE);
12162                 } else {
12163                         NDBG0(("FIXED interrupt registration failed"));
12164                         return (FALSE);
12165                 }
12166         }
12167 
12168         return (FALSE);
12169 }
12170 
12171 static void
12172 mptsas_unregister_intrs(mptsas_t *mpt)
12173 {
12174         mptsas_rem_intrs(mpt);
12175 }
12176 
12177 /*
12178  * mptsas_add_intrs:
12179  *
12180  * Register FIXED or MSI interrupts.
12181  */
12182 static int
12183 mptsas_add_intrs(mptsas_t *mpt, int intr_type)
12184 {
12185         dev_info_t      *dip = mpt->m_dip;
12186         int             avail, actual, count = 0;
12187         int             i, flag, ret;
12188 
12189         NDBG6(("mptsas_add_intrs:interrupt type 0x%x", intr_type));
12190 
12191         /* Get number of interrupts */
12192         ret = ddi_intr_get_nintrs(dip, intr_type, &count);
12193         if ((ret != DDI_SUCCESS) || (count <= 0)) {
12194                 mptsas_log(mpt, CE_WARN, "ddi_intr_get_nintrs() failed, "
12195                     "ret %d count %d\n", ret, count);
12196 
12197                 return (DDI_FAILURE);
12198         }
12199 
12200         /* Get number of available interrupts */
12201         ret = ddi_intr_get_navail(dip, intr_type, &avail);
12202         if ((ret != DDI_SUCCESS) || (avail == 0)) {
12203                 mptsas_log(mpt, CE_WARN, "ddi_intr_get_navail() failed, "
12204                     "ret %d avail %d\n", ret, avail);
12205 
12206                 return (DDI_FAILURE);
12207         }
12208 
12209         if (avail < count) {
12210                 mptsas_log(mpt, CE_NOTE, "ddi_intr_get_nvail returned %d, "
12211                     "navail() returned %d", count, avail);
12212         }
12213 
12214         /* Mpt only have one interrupt routine */
12215         if ((intr_type == DDI_INTR_TYPE_MSI) && (count > 1)) {
12216                 count = 1;






















12217         }
12218 
12219         /* Allocate an array of interrupt handles */
12220         mpt->m_intr_size = count * sizeof (ddi_intr_handle_t);
12221         mpt->m_htable = kmem_alloc(mpt->m_intr_size, KM_SLEEP);
12222 
12223         flag = DDI_INTR_ALLOC_NORMAL;
12224 
12225         /* call ddi_intr_alloc() */
12226         ret = ddi_intr_alloc(dip, mpt->m_htable, intr_type, 0,
12227             count, &actual, flag);
12228 
12229         if ((ret != DDI_SUCCESS) || (actual == 0)) {
12230                 mptsas_log(mpt, CE_WARN, "ddi_intr_alloc() failed, ret %d\n",
12231                     ret);
12232                 kmem_free(mpt->m_htable, mpt->m_intr_size);
12233                 return (DDI_FAILURE);
12234         }
12235 

12236         /* use interrupt count returned or abort? */
12237         if (actual < count) {
12238                 mptsas_log(mpt, CE_NOTE, "Requested: %d, Received: %d\n",
12239                     count, actual);

12240         }
12241 
12242         mpt->m_intr_cnt = actual;
12243 
12244         /*
12245          * Get priority for first msi, assume remaining are all the same
12246          */
12247         if ((ret = ddi_intr_get_pri(mpt->m_htable[0],
12248             &mpt->m_intr_pri)) != DDI_SUCCESS) {
12249                 mptsas_log(mpt, CE_WARN, "ddi_intr_get_pri() failed %d\n", ret);
12250 
12251                 /* Free already allocated intr */
12252                 for (i = 0; i < actual; i++) {
12253                         (void) ddi_intr_free(mpt->m_htable[i]);
12254                 }
12255 
12256                 kmem_free(mpt->m_htable, mpt->m_intr_size);
12257                 return (DDI_FAILURE);
12258         }
12259 
12260         /* Test for high level mutex */
12261         if (mpt->m_intr_pri >= ddi_intr_get_hilevel_pri()) {
12262                 mptsas_log(mpt, CE_WARN, "mptsas_add_intrs: "
12263                     "Hi level interrupt not supported\n");


12284                         }
12285 
12286                         kmem_free(mpt->m_htable, mpt->m_intr_size);
12287                         return (DDI_FAILURE);
12288                 }
12289         }
12290 
12291         if ((ret = ddi_intr_get_cap(mpt->m_htable[0], &mpt->m_intr_cap))
12292             != DDI_SUCCESS) {
12293                 mptsas_log(mpt, CE_WARN, "ddi_intr_get_cap() failed %d\n", ret);
12294 
12295                 /* Free already allocated intr */
12296                 for (i = 0; i < actual; i++) {
12297                         (void) ddi_intr_free(mpt->m_htable[i]);
12298                 }
12299 
12300                 kmem_free(mpt->m_htable, mpt->m_intr_size);
12301                 return (DDI_FAILURE);
12302         }
12303 


12304         /*
12305          * Enable interrupts
12306          */
12307         if (mpt->m_intr_cap & DDI_INTR_FLAG_BLOCK) {
12308                 /* Call ddi_intr_block_enable() for MSI interrupts */
12309                 (void) ddi_intr_block_enable(mpt->m_htable, mpt->m_intr_cnt);
12310         } else {
12311                 /* Call ddi_intr_enable for MSI or FIXED interrupts */
12312                 for (i = 0; i < mpt->m_intr_cnt; i++) {
12313                         (void) ddi_intr_enable(mpt->m_htable[i]);
12314                 }
12315         }
















12316         return (DDI_SUCCESS);
12317 }
12318 
12319 /*
12320  * mptsas_rem_intrs:
12321  *
12322  * Unregister FIXED or MSI interrupts
12323  */
12324 static void
12325 mptsas_rem_intrs(mptsas_t *mpt)
12326 {
12327         int     i;
12328 
12329         NDBG6(("mptsas_rem_intrs"));
12330 
12331         /* Disable all interrupts */
12332         if (mpt->m_intr_cap & DDI_INTR_FLAG_BLOCK) {
12333                 /* Call ddi_intr_block_disable() */
12334                 (void) ddi_intr_block_disable(mpt->m_htable, mpt->m_intr_cnt);
12335         } else {
12336                 for (i = 0; i < mpt->m_intr_cnt; i++) {
12337                         (void) ddi_intr_disable(mpt->m_htable[i]);
12338                 }
12339         }
12340 
12341         /* Call ddi_intr_remove_handler() */
12342         for (i = 0; i < mpt->m_intr_cnt; i++) {
12343                 (void) ddi_intr_remove_handler(mpt->m_htable[i]);
12344                 (void) ddi_intr_free(mpt->m_htable[i]);
12345         }
12346 
12347         kmem_free(mpt->m_htable, mpt->m_intr_size);

12348 }
12349 
12350 /*
12351  * The IO fault service error handling callback function
12352  */
12353 /*ARGSUSED*/
12354 static int
12355 mptsas_fm_error_cb(dev_info_t *dip, ddi_fm_error_t *err, const void *impl_data)
12356 {
12357         /*
12358          * as the driver can always deal with an error in any dma or
12359          * access handle, we can just return the fme_status value.
12360          */
12361         pci_ereport_post(dip, err, NULL);
12362         return (err->fme_status);
12363 }
12364 
12365 /*
12366  * mptsas_fm_init - initialize fma capabilities and register with IO
12367  *               fault services.


12477         (void) snprintf(buf, FM_MAX_CLASS, "%s.%s", DDI_FM_DEVICE, detail);
12478         ena = fm_ena_generate(0, FM_ENA_FMT1);
12479         if (DDI_FM_EREPORT_CAP(mpt->m_fm_capabilities)) {
12480                 ddi_fm_ereport_post(mpt->m_dip, buf, ena, DDI_NOSLEEP,
12481                     FM_VERSION, DATA_TYPE_UINT8, FM_EREPORT_VERS0, NULL);
12482         }
12483 }
12484 
12485 static int
12486 mptsas_get_target_device_info(mptsas_t *mpt, uint32_t page_address,
12487     uint16_t *dev_handle, mptsas_target_t **pptgt)
12488 {
12489         int             rval;
12490         uint32_t        dev_info;
12491         uint64_t        sas_wwn;
12492         mptsas_phymask_t phymask;
12493         uint8_t         physport, phynum, config, disk;
12494         uint64_t        devicename;
12495         uint16_t        pdev_hdl;
12496         mptsas_target_t *tmp_tgt = NULL;
12497         uint16_t        bay_num, enclosure;
12498 
12499         ASSERT(*pptgt == NULL);
12500 
12501         rval = mptsas_get_sas_device_page0(mpt, page_address, dev_handle,
12502             &sas_wwn, &dev_info, &physport, &phynum, &pdev_hdl,
12503             &bay_num, &enclosure);
12504         if (rval != DDI_SUCCESS) {
12505                 rval = DEV_INFO_FAIL_PAGE0;
12506                 return (rval);
12507         }
12508 
12509         if ((dev_info & (MPI2_SAS_DEVICE_INFO_SSP_TARGET |
12510             MPI2_SAS_DEVICE_INFO_SATA_DEVICE |
12511             MPI2_SAS_DEVICE_INFO_ATAPI_DEVICE)) == NULL) {
12512                 rval = DEV_INFO_WRONG_DEVICE_TYPE;
12513                 return (rval);
12514         }
12515 
12516         /*
12517          * Check if the dev handle is for a Phys Disk. If so, set return value
12518          * and exit.  Don't add Phys Disks to hash.
12519          */
12520         for (config = 0; config < mpt->m_num_raid_configs; config++) {
12521                 for (disk = 0; disk < MPTSAS_MAX_DISKS_IN_CONFIG; disk++) {
12522                         if (*dev_handle == mpt->m_raidconfig[config].
12523                             m_physdisk_devhdl[disk]) {


12528         }
12529 
12530         /*
12531          * Get SATA Device Name from SAS device page0 for
12532          * sata device, if device name doesn't exist, set mta_wwn to
12533          * 0 for direct attached SATA. For the device behind the expander
12534          * we still can use STP address assigned by expander.
12535          */
12536         if (dev_info & (MPI2_SAS_DEVICE_INFO_SATA_DEVICE |
12537             MPI2_SAS_DEVICE_INFO_ATAPI_DEVICE)) {
12538                 mutex_exit(&mpt->m_mutex);
12539                 /* alloc a tmp_tgt to send the cmd */
12540                 tmp_tgt = kmem_zalloc(sizeof (struct mptsas_target),
12541                     KM_SLEEP);
12542                 tmp_tgt->m_devhdl = *dev_handle;
12543                 tmp_tgt->m_deviceinfo = dev_info;
12544                 tmp_tgt->m_qfull_retries = QFULL_RETRIES;
12545                 tmp_tgt->m_qfull_retry_interval =
12546                     drv_usectohz(QFULL_RETRY_INTERVAL * 1000);
12547                 tmp_tgt->m_t_throttle = MAX_THROTTLE;

12548                 devicename = mptsas_get_sata_guid(mpt, tmp_tgt, 0);

12549                 kmem_free(tmp_tgt, sizeof (struct mptsas_target));
12550                 mutex_enter(&mpt->m_mutex);
12551                 if (devicename != 0 && (((devicename >> 56) & 0xf0) == 0x50)) {
12552                         sas_wwn = devicename;
12553                 } else if (dev_info & MPI2_SAS_DEVICE_INFO_DIRECT_ATTACH) {
12554                         sas_wwn = 0;
12555                 }
12556         }
12557 
12558         phymask = mptsas_physport_to_phymask(mpt, physport);
12559         *pptgt = mptsas_tgt_alloc(mpt, *dev_handle, sas_wwn,
12560             dev_info, phymask, phynum);
12561         if (*pptgt == NULL) {
12562                 mptsas_log(mpt, CE_WARN, "Failed to allocated target"
12563                     "structure!");
12564                 rval = DEV_INFO_FAIL_ALLOC;
12565                 return (rval);
12566         }

12567         (*pptgt)->m_enclosure = enclosure;
12568         (*pptgt)->m_slot_num = bay_num;
12569         return (DEV_INFO_SUCCESS);
12570 }
12571 
12572 uint64_t
12573 mptsas_get_sata_guid(mptsas_t *mpt, mptsas_target_t *ptgt, int lun)
12574 {
12575         uint64_t        sata_guid = 0, *pwwn = NULL;
12576         int             target = ptgt->m_devhdl;
12577         uchar_t         *inq83 = NULL;
12578         int             inq83_len = 0xFF;
12579         uchar_t         *dblk = NULL;
12580         int             inq83_retry = 3;
12581         int             rval = DDI_FAILURE;
12582 
12583         inq83   = kmem_zalloc(inq83_len, KM_SLEEP);
12584 
12585 inq83_retry:
12586         rval = mptsas_inquiry(mpt, ptgt, lun, 0x83, inq83,


12684         bcopy((caddr_t)mpt->m_tran,
12685             (caddr_t)tran_clone, sizeof (scsi_hba_tran_t));
12686         tgt_private = kmem_alloc(
12687             sizeof (mptsas_tgt_private_t), KM_SLEEP);
12688         if (tgt_private == NULL) {
12689                 goto out;
12690         }
12691         tgt_private->t_lun = ap->a_lun;
12692         tgt_private->t_private = ptgt;
12693         tran_clone->tran_tgt_private = tgt_private;
12694         ap->a_hba_tran = tran_clone;
12695 
12696         pktp = scsi_init_pkt(ap, (struct scsi_pkt *)NULL,
12697             data_bp, cdblen, sizeof (struct scsi_arq_status),
12698             0, PKT_CONSISTENT, NULL, NULL);
12699         if (pktp == NULL) {
12700                 goto out;
12701         }
12702         bcopy(cdb, pktp->pkt_cdbp, cdblen);
12703         pktp->pkt_flags = FLAG_NOPARITY;

12704         if (scsi_poll(pktp) < 0) {
12705                 goto out;
12706         }
12707         if (((struct scsi_status *)pktp->pkt_scbp)->sts_chk) {
12708                 goto out;
12709         }
12710         if (resid != NULL) {
12711                 *resid = pktp->pkt_resid;
12712         }
12713 
12714         ret = DDI_SUCCESS;
12715 out:
12716         if (pktp) {
12717                 scsi_destroy_pkt(pktp);
12718         }
12719         if (tran_clone) {
12720                 kmem_free(tran_clone, sizeof (scsi_hba_tran_t));
12721         }
12722         if (tgt_private) {
12723                 kmem_free(tgt_private, sizeof (mptsas_tgt_private_t));


13532         dev_info_t      *tdip;
13533 
13534         rval = mptsas_config_luns(pdip, ptgt);
13535         if (rval != DDI_SUCCESS) {
13536                 /*
13537                  * The return value means the SCMD_REPORT_LUNS
13538                  * did not execute successfully. The target maybe
13539                  * doesn't support such command.
13540                  */
13541                 rval = mptsas_probe_lun(pdip, 0, &tdip, ptgt);
13542         }
13543         return (rval);
13544 }
13545 
13546 /*
13547  * Return fail if not all the childs/paths are freed.
13548  * if there is any path under the HBA, the return value will be always fail
13549  * because we didn't call mdi_pi_free for path
13550  */
13551 static int
13552 mptsas_offline_target(dev_info_t *pdip, char *name)
13553 {
13554         dev_info_t              *child = NULL, *prechild = NULL;
13555         mdi_pathinfo_t          *pip = NULL, *savepip = NULL;
13556         int                     tmp_rval, rval = DDI_SUCCESS;
13557         char                    *addr, *cp;
13558         size_t                  s;
13559         mptsas_t                *mpt = DIP2MPT(pdip);
13560 
13561         child = ddi_get_child(pdip);
13562         while (child) {
13563                 addr = ddi_get_name_addr(child);
13564                 prechild = child;
13565                 child = ddi_get_next_sibling(child);
13566 
13567                 if (addr == NULL) {
13568                         continue;
13569                 }
13570                 if ((cp = strchr(addr, ',')) == NULL) {
13571                         continue;
13572                 }
13573 
13574                 s = (uintptr_t)cp - (uintptr_t)addr;
13575 
13576                 if (strncmp(addr, name, s) != 0) {
13577                         continue;
13578                 }
13579 
13580                 tmp_rval = mptsas_offline_lun(pdip, prechild, NULL,
13581                     NDI_DEVI_REMOVE);
13582                 if (tmp_rval != DDI_SUCCESS) {
13583                         rval = DDI_FAILURE;
13584                         if (ndi_prop_create_boolean(DDI_DEV_T_NONE,
13585                             prechild, MPTSAS_DEV_GONE) !=
13586                             DDI_PROP_SUCCESS) {
13587                                 mptsas_log(mpt, CE_WARN, "mptsas driver "
13588                                     "unable to create property for "
13589                                     "SAS %s (MPTSAS_DEV_GONE)", addr);
13590                         }
13591                 }
13592         }
13593 
13594         pip = mdi_get_next_client_path(pdip, NULL);
13595         while (pip) {
13596                 addr = MDI_PI(pip)->pi_addr;
13597                 savepip = pip;
13598                 pip = mdi_get_next_client_path(pdip, pip);
13599                 if (addr == NULL) {
13600                         continue;
13601                 }
13602 
13603                 if ((cp = strchr(addr, ',')) == NULL) {
13604                         continue;
13605                 }
13606 
13607                 s = (uintptr_t)cp - (uintptr_t)addr;


13944                 ddi_devid_free_guid(guid);
13945         }
13946         if (inq83 != NULL)
13947                 kmem_free(inq83, inq83_len1);
13948         return (rval);
13949 }
13950 
13951 static int
13952 mptsas_create_virt_lun(dev_info_t *pdip, struct scsi_inquiry *inq, char *guid,
13953     dev_info_t **lun_dip, mdi_pathinfo_t **pip, mptsas_target_t *ptgt, int lun)
13954 {
13955         int                     target;
13956         char                    *nodename = NULL;
13957         char                    **compatible = NULL;
13958         int                     ncompatible     = 0;
13959         int                     mdi_rtn = MDI_FAILURE;
13960         int                     rval = DDI_FAILURE;
13961         char                    *old_guid = NULL;
13962         mptsas_t                *mpt = DIP2MPT(pdip);
13963         char                    *lun_addr = NULL;
13964         char                    *wwn_str = NULL;
13965         char                    *attached_wwn_str = NULL;
13966         char                    *component = NULL;
13967         uint8_t                 phy = 0xFF;
13968         uint64_t                sas_wwn;
13969         int64_t                 lun64 = 0;
13970         uint32_t                devinfo;
13971         uint16_t                dev_hdl;
13972         uint16_t                pdev_hdl;
13973         uint64_t                dev_sas_wwn;
13974         uint64_t                pdev_sas_wwn;
13975         uint32_t                pdev_info;
13976         uint8_t                 physport;
13977         uint8_t                 phy_id;
13978         uint32_t                page_address;
13979         uint16_t                bay_num, enclosure;
13980         char                    pdev_wwn_str[MPTSAS_WWN_STRLEN];
13981         uint32_t                dev_info;
13982 
13983         mutex_enter(&mpt->m_mutex);
13984         target = ptgt->m_devhdl;
13985         sas_wwn = ptgt->m_addr.mta_wwn;
13986         devinfo = ptgt->m_deviceinfo;
13987         phy = ptgt->m_phynum;
13988         mutex_exit(&mpt->m_mutex);
13989 
13990         if (sas_wwn) {
13991                 *pip = mptsas_find_path_addr(pdip, sas_wwn, lun);
13992         } else {
13993                 *pip = mptsas_find_path_phy(pdip, phy);
13994         }
13995 
13996         if (*pip != NULL) {
13997                 *lun_dip = MDI_PI(*pip)->pi_client->ct_dip;
13998                 ASSERT(*lun_dip != NULL);
13999                 if (ddi_prop_lookup_string(DDI_DEV_T_ANY, *lun_dip,


14053                                         *pip = NULL;
14054                                         *lun_dip = NULL;
14055                                         return (DDI_FAILURE);
14056                                 }
14057                         }
14058                 } else {
14059                         mptsas_log(mpt, CE_WARN, "Can't get client-guid "
14060                             "property for path:target:%x, lun:%x", target, lun);
14061                         *pip = NULL;
14062                         *lun_dip = NULL;
14063                         return (DDI_FAILURE);
14064                 }
14065         }
14066         scsi_hba_nodename_compatible_get(inq, NULL,
14067             inq->inq_dtype, NULL, &nodename, &compatible, &ncompatible);
14068 
14069         /*
14070          * if nodename can't be determined then print a message and skip it
14071          */
14072         if (nodename == NULL) {
14073                 mptsas_log(mpt, CE_WARN, "mptsas driver found no compatible "
14074                     "driver for target%d lun %d dtype:0x%02x", target, lun,
14075                     inq->inq_dtype);
14076                 return (DDI_FAILURE);
14077         }
14078 
14079         wwn_str = kmem_zalloc(MPTSAS_WWN_STRLEN, KM_SLEEP);
14080         /* The property is needed by MPAPI */
14081         (void) sprintf(wwn_str, "%016"PRIx64, sas_wwn);
14082 
14083         lun_addr = kmem_zalloc(SCSI_MAXNAMELEN, KM_SLEEP);
14084         if (guid) {
14085                 (void) sprintf(lun_addr, "w%s,%x", wwn_str, lun);
14086                 (void) sprintf(wwn_str, "w%016"PRIx64, sas_wwn);
14087         } else {
14088                 (void) sprintf(lun_addr, "p%x,%x", phy, lun);
14089                 (void) sprintf(wwn_str, "p%x", phy);
14090         }
14091 
14092         mdi_rtn = mdi_pi_alloc_compatible(pdip, nodename,
14093             guid, lun_addr, compatible, ncompatible,
14094             0, pip);
14095         if (mdi_rtn == MDI_SUCCESS) {
14096 
14097                 if (mdi_prop_update_string(*pip, MDI_GUID,
14098                     guid) != DDI_SUCCESS) {
14099                         mptsas_log(mpt, CE_WARN, "mptsas driver unable to "
14100                             "create prop for target %d lun %d (MDI_GUID)",
14101                             target, lun);
14102                         mdi_rtn = MDI_FAILURE;
14103                         goto virt_create_done;
14104                 }
14105 
14106                 if (mdi_prop_update_int(*pip, LUN_PROP,
14107                     lun) != DDI_SUCCESS) {
14108                         mptsas_log(mpt, CE_WARN, "mptsas driver unable to "
14109                             "create prop for target %d lun %d (LUN_PROP)",
14110                             target, lun);
14111                         mdi_rtn = MDI_FAILURE;
14112                         goto virt_create_done;
14113                 }
14114                 lun64 = (int64_t)lun;
14115                 if (mdi_prop_update_int64(*pip, LUN64_PROP,
14116                     lun64) != DDI_SUCCESS) {
14117                         mptsas_log(mpt, CE_WARN, "mptsas driver unable to "
14118                             "create prop for target %d (LUN64_PROP)",
14119                             target);
14120                         mdi_rtn = MDI_FAILURE;
14121                         goto virt_create_done;
14122                 }
14123                 if (mdi_prop_update_string_array(*pip, "compatible",
14124                     compatible, ncompatible) !=
14125                     DDI_PROP_SUCCESS) {
14126                         mptsas_log(mpt, CE_WARN, "mptsas driver unable to "
14127                             "create prop for target %d lun %d (COMPATIBLE)",
14128                             target, lun);
14129                         mdi_rtn = MDI_FAILURE;
14130                         goto virt_create_done;
14131                 }
14132                 if (sas_wwn && (mdi_prop_update_string(*pip,
14133                     SCSI_ADDR_PROP_TARGET_PORT, wwn_str) != DDI_PROP_SUCCESS)) {
14134                         mptsas_log(mpt, CE_WARN, "mptsas driver unable to "
14135                             "create prop for target %d lun %d "
14136                             "(target-port)", target, lun);
14137                         mdi_rtn = MDI_FAILURE;
14138                         goto virt_create_done;
14139                 } else if ((sas_wwn == 0) && (mdi_prop_update_int(*pip,
14140                     "sata-phy", phy) != DDI_PROP_SUCCESS)) {
14141                         /*
14142                          * Direct attached SATA device without DeviceName
14143                          */
14144                         mptsas_log(mpt, CE_WARN, "mptsas driver unable to "
14145                             "create prop for SAS target %d lun %d "
14146                             "(sata-phy)", target, lun);
14147                         mdi_rtn = MDI_FAILURE;
14148                         goto virt_create_done;
14149                 }
14150                 mutex_enter(&mpt->m_mutex);
14151 
14152                 page_address = (MPI2_SAS_DEVICE_PGAD_FORM_HANDLE &
14153                     MPI2_SAS_DEVICE_PGAD_FORM_MASK) |
14154                     (uint32_t)ptgt->m_devhdl;
14155                 rval = mptsas_get_sas_device_page0(mpt, page_address,
14156                     &dev_hdl, &dev_sas_wwn, &dev_info, &physport,
14157                     &phy_id, &pdev_hdl, &bay_num, &enclosure);
14158                 if (rval != DDI_SUCCESS) {
14159                         mutex_exit(&mpt->m_mutex);
14160                         mptsas_log(mpt, CE_WARN, "mptsas unable to get "
14161                             "parent device for handle %d", page_address);
14162                         mdi_rtn = MDI_FAILURE;
14163                         goto virt_create_done;
14164                 }
14165 
14166                 page_address = (MPI2_SAS_DEVICE_PGAD_FORM_HANDLE &
14167                     MPI2_SAS_DEVICE_PGAD_FORM_MASK) | (uint32_t)pdev_hdl;
14168                 rval = mptsas_get_sas_device_page0(mpt, page_address,
14169                     &dev_hdl, &pdev_sas_wwn, &pdev_info, &physport,
14170                     &phy_id, &pdev_hdl, &bay_num, &enclosure);
14171                 if (rval != DDI_SUCCESS) {
14172                         mutex_exit(&mpt->m_mutex);
14173                         mptsas_log(mpt, CE_WARN, "mptsas unable to get"
14174                             "device info for handle %d", page_address);
14175                         mdi_rtn = MDI_FAILURE;
14176                         goto virt_create_done;
14177                 }
14178 
14179                 mutex_exit(&mpt->m_mutex);
14180 
14181                 /*
14182                  * If this device direct attached to the controller
14183                  * set the attached-port to the base wwid
14184                  */
14185                 if ((ptgt->m_deviceinfo & DEVINFO_DIRECT_ATTACHED)
14186                     != DEVINFO_DIRECT_ATTACHED) {
14187                         (void) sprintf(pdev_wwn_str, "w%016"PRIx64,
14188                             pdev_sas_wwn);
14189                 } else {
14190                         /*


14197                         }
14198                         if (ddi_prop_update_string(DDI_DEV_T_NONE,
14199                             pdip, SCSI_ADDR_PROP_ATTACHED_PORT, wwn_str) !=
14200                             DDI_PROP_SUCCESS) {
14201                                 mptsas_log(mpt, CE_WARN,
14202                                     "mptsas unable to create "
14203                                     "property for iport target-port"
14204                                     " %s (sas_wwn)",
14205                                     wwn_str);
14206                                 mdi_rtn = MDI_FAILURE;
14207                                 goto virt_create_done;
14208                         }
14209 
14210                         (void) sprintf(pdev_wwn_str, "w%016"PRIx64,
14211                             mpt->un.m_base_wwid);
14212                 }
14213 
14214                 if (mdi_prop_update_string(*pip,
14215                     SCSI_ADDR_PROP_ATTACHED_PORT, pdev_wwn_str) !=
14216                     DDI_PROP_SUCCESS) {
14217                         mptsas_log(mpt, CE_WARN, "mptsas unable to create "
14218                             "property for iport attached-port %s (sas_wwn)",
14219                             attached_wwn_str);
14220                         mdi_rtn = MDI_FAILURE;
14221                         goto virt_create_done;
14222                 }
14223 
14224 
14225                 if (inq->inq_dtype == 0) {
14226                         component = kmem_zalloc(MAXPATHLEN, KM_SLEEP);
14227                         /*
14228                          * set obp path for pathinfo
14229                          */
14230                         (void) snprintf(component, MAXPATHLEN,
14231                             "disk@%s", lun_addr);
14232 
14233                         if (mdi_pi_pathname_obp_set(*pip, component) !=
14234                             DDI_SUCCESS) {
14235                                 mptsas_log(mpt, CE_WARN, "mpt_sas driver "
14236                                     "unable to set obp-path for object %s",
14237                                     component);
14238                                 mdi_rtn = MDI_FAILURE;
14239                                 goto virt_create_done;
14240                         }
14241                 }
14242 
14243                 *lun_dip = MDI_PI(*pip)->pi_client->ct_dip;
14244                 if (devinfo & (MPI2_SAS_DEVICE_INFO_SATA_DEVICE |
14245                     MPI2_SAS_DEVICE_INFO_ATAPI_DEVICE)) {
14246                         if ((ndi_prop_update_int(DDI_DEV_T_NONE, *lun_dip,
14247                             "pm-capable", 1)) !=
14248                             DDI_PROP_SUCCESS) {
14249                                 mptsas_log(mpt, CE_WARN, "mptsas driver"
14250                                     "failed to create pm-capable "
14251                                     "property, target %d", target);
14252                                 mdi_rtn = MDI_FAILURE;
14253                                 goto virt_create_done;
14254                         }
14255                 }
14256                 /*
14257                  * Create the phy-num property
14258                  */
14259                 if (mdi_prop_update_int(*pip, "phy-num",
14260                     ptgt->m_phynum) != DDI_SUCCESS) {
14261                         mptsas_log(mpt, CE_WARN, "mptsas driver unable to "
14262                             "create phy-num property for target %d lun %d",
14263                             target, lun);
14264                         mdi_rtn = MDI_FAILURE;
14265                         goto virt_create_done;
14266                 }
14267                 NDBG20(("new path:%s onlining,", MDI_PI(*pip)->pi_addr));
14268                 mdi_rtn = mdi_pi_online(*pip, 0);
14269                 if (mdi_rtn == MDI_SUCCESS) {
14270                         mutex_enter(&mpt->m_mutex);
14271                         ptgt->m_led_status = 0;
14272                         (void) mptsas_flush_led_status(mpt, ptgt);
14273                         mutex_exit(&mpt->m_mutex);
14274                 }
14275                 if (mdi_rtn == MDI_NOT_SUPPORTED) {
14276                         mdi_rtn = MDI_FAILURE;
14277                 }
14278 virt_create_done:
14279                 if (*pip && mdi_rtn != MDI_SUCCESS) {
14280                         (void) mdi_pi_free(*pip, 0);
14281                         *pip = NULL;
14282                         *lun_dip = NULL;
14283                 }
14284         }
14285 
14286         scsi_hba_nodename_compatible_free(nodename, compatible);
14287         if (lun_addr != NULL) {
14288                 kmem_free(lun_addr, SCSI_MAXNAMELEN);
14289         }
14290         if (wwn_str != NULL) {
14291                 kmem_free(wwn_str, MPTSAS_WWN_STRLEN);
14292         }
14293         if (component != NULL) {
14294                 kmem_free(component, MAXPATHLEN);
14295         }
14296 
14297         return ((mdi_rtn == MDI_SUCCESS) ? DDI_SUCCESS : DDI_FAILURE);
14298 }
14299 
14300 static int
14301 mptsas_create_phys_lun(dev_info_t *pdip, struct scsi_inquiry *inq,
14302     char *guid, dev_info_t **lun_dip, mptsas_target_t *ptgt, int lun)
14303 {
14304         int                     target;
14305         int                     rval;
14306         int                     ndi_rtn = NDI_FAILURE;
14307         uint64_t                be_sas_wwn;
14308         char                    *nodename = NULL;
14309         char                    **compatible = NULL;
14310         int                     ncompatible = 0;
14311         int                     instance = 0;
14312         mptsas_t                *mpt = DIP2MPT(pdip);
14313         char                    *wwn_str = NULL;
14314         char                    *component = NULL;
14315         char                    *attached_wwn_str = NULL;
14316         uint8_t                 phy = 0xFF;
14317         uint64_t                sas_wwn;
14318         uint32_t                devinfo;
14319         uint16_t                dev_hdl;
14320         uint16_t                pdev_hdl;
14321         uint64_t                pdev_sas_wwn;
14322         uint64_t                dev_sas_wwn;
14323         uint32_t                pdev_info;
14324         uint8_t                 physport;
14325         uint8_t                 phy_id;
14326         uint32_t                page_address;
14327         uint16_t                bay_num, enclosure;
14328         char                    pdev_wwn_str[MPTSAS_WWN_STRLEN];
14329         uint32_t                dev_info;
14330         int64_t                 lun64 = 0;
14331 
14332         mutex_enter(&mpt->m_mutex);
14333         target = ptgt->m_devhdl;
14334         sas_wwn = ptgt->m_addr.mta_wwn;
14335         devinfo = ptgt->m_deviceinfo;
14336         phy = ptgt->m_phynum;
14337         mutex_exit(&mpt->m_mutex);
14338 
14339         /*
14340          * generate compatible property with binding-set "mpt"
14341          */
14342         scsi_hba_nodename_compatible_get(inq, NULL, inq->inq_dtype, NULL,
14343             &nodename, &compatible, &ncompatible);
14344 
14345         /*
14346          * if nodename can't be determined then print a message and skip it
14347          */


14378                             target, lun);
14379                         ndi_rtn = NDI_FAILURE;
14380                         goto phys_create_done;
14381                 }
14382                 if (ndi_prop_update_string_array(DDI_DEV_T_NONE,
14383                     *lun_dip, "compatible", compatible, ncompatible)
14384                     != DDI_PROP_SUCCESS) {
14385                         mptsas_log(mpt, CE_WARN, "mptsas unable to create "
14386                             "property for target %d lun %d (COMPATIBLE)",
14387                             target, lun);
14388                         ndi_rtn = NDI_FAILURE;
14389                         goto phys_create_done;
14390                 }
14391 
14392                 /*
14393                  * We need the SAS WWN for non-multipath devices, so
14394                  * we'll use the same property as that multipathing
14395                  * devices need to present for MPAPI. If we don't have
14396                  * a WWN (e.g. parallel SCSI), don't create the prop.
14397                  */
14398                 wwn_str = kmem_zalloc(MPTSAS_WWN_STRLEN, KM_SLEEP);
14399                 (void) sprintf(wwn_str, "w%016"PRIx64, sas_wwn);
14400                 if (sas_wwn && ndi_prop_update_string(DDI_DEV_T_NONE,
14401                     *lun_dip, SCSI_ADDR_PROP_TARGET_PORT, wwn_str)
14402                     != DDI_PROP_SUCCESS) {
14403                         mptsas_log(mpt, CE_WARN, "mptsas unable to "
14404                             "create property for SAS target %d lun %d "
14405                             "(target-port)", target, lun);
14406                         ndi_rtn = NDI_FAILURE;
14407                         goto phys_create_done;
14408                 }
14409 
14410                 be_sas_wwn = BE_64(sas_wwn);
14411                 if (sas_wwn && ndi_prop_update_byte_array(
14412                     DDI_DEV_T_NONE, *lun_dip, "port-wwn",
14413                     (uchar_t *)&be_sas_wwn, 8) != DDI_PROP_SUCCESS) {
14414                         mptsas_log(mpt, CE_WARN, "mptsas unable to "
14415                             "create property for SAS target %d lun %d "
14416                             "(port-wwn)", target, lun);
14417                         ndi_rtn = NDI_FAILURE;
14418                         goto phys_create_done;


14444                             "lun %d", target, lun);
14445                         ndi_rtn = NDI_FAILURE;
14446                         goto phys_create_done;
14447                 }
14448 
14449                 /*
14450                  * The following code is to set properties for SM-HBA support,
14451                  * it doesn't apply to RAID volumes
14452                  */
14453                 if (ptgt->m_addr.mta_phymask == 0)
14454                         goto phys_raid_lun;
14455 
14456                 mutex_enter(&mpt->m_mutex);
14457 
14458                 page_address = (MPI2_SAS_DEVICE_PGAD_FORM_HANDLE &
14459                     MPI2_SAS_DEVICE_PGAD_FORM_MASK) |
14460                     (uint32_t)ptgt->m_devhdl;
14461                 rval = mptsas_get_sas_device_page0(mpt, page_address,
14462                     &dev_hdl, &dev_sas_wwn, &dev_info,
14463                     &physport, &phy_id, &pdev_hdl,
14464                     &bay_num, &enclosure);
14465                 if (rval != DDI_SUCCESS) {
14466                         mutex_exit(&mpt->m_mutex);
14467                         mptsas_log(mpt, CE_WARN, "mptsas unable to get"
14468                             "parent device for handle %d.", page_address);
14469                         ndi_rtn = NDI_FAILURE;
14470                         goto phys_create_done;
14471                 }
14472 
14473                 page_address = (MPI2_SAS_DEVICE_PGAD_FORM_HANDLE &
14474                     MPI2_SAS_DEVICE_PGAD_FORM_MASK) | (uint32_t)pdev_hdl;
14475                 rval = mptsas_get_sas_device_page0(mpt, page_address,
14476                     &dev_hdl, &pdev_sas_wwn, &pdev_info,
14477                     &physport, &phy_id, &pdev_hdl, &bay_num, &enclosure);
14478                 if (rval != DDI_SUCCESS) {
14479                         mutex_exit(&mpt->m_mutex);
14480                         mptsas_log(mpt, CE_WARN, "mptsas unable to create "
14481                             "device for handle %d.", page_address);
14482                         ndi_rtn = NDI_FAILURE;
14483                         goto phys_create_done;
14484                 }
14485 
14486                 mutex_exit(&mpt->m_mutex);
14487 
14488                 /*
14489                  * If this device direct attached to the controller
14490                  * set the attached-port to the base wwid
14491                  */
14492                 if ((ptgt->m_deviceinfo & DEVINFO_DIRECT_ATTACHED)
14493                     != DEVINFO_DIRECT_ATTACHED) {
14494                         (void) sprintf(pdev_wwn_str, "w%016"PRIx64,
14495                             pdev_sas_wwn);
14496                 } else {
14497                         /*


14507                             DDI_PROP_SUCCESS) {
14508                                 mptsas_log(mpt, CE_WARN,
14509                                     "mptsas unable to create "
14510                                     "property for iport target-port"
14511                                     " %s (sas_wwn)",
14512                                     wwn_str);
14513                                 ndi_rtn = NDI_FAILURE;
14514                                 goto phys_create_done;
14515                         }
14516 
14517                         (void) sprintf(pdev_wwn_str, "w%016"PRIx64,
14518                             mpt->un.m_base_wwid);
14519                 }
14520 
14521                 if (ndi_prop_update_string(DDI_DEV_T_NONE,
14522                     *lun_dip, SCSI_ADDR_PROP_ATTACHED_PORT, pdev_wwn_str) !=
14523                     DDI_PROP_SUCCESS) {
14524                         mptsas_log(mpt, CE_WARN,
14525                             "mptsas unable to create "
14526                             "property for iport attached-port %s (sas_wwn)",
14527                             attached_wwn_str);
14528                         ndi_rtn = NDI_FAILURE;
14529                         goto phys_create_done;
14530                 }
14531 
14532                 if (IS_SATA_DEVICE(dev_info)) {
14533                         if (ndi_prop_update_string(DDI_DEV_T_NONE,
14534                             *lun_dip, MPTSAS_VARIANT, "sata") !=
14535                             DDI_PROP_SUCCESS) {
14536                                 mptsas_log(mpt, CE_WARN,
14537                                     "mptsas unable to create "
14538                                     "property for device variant ");
14539                                 ndi_rtn = NDI_FAILURE;
14540                                 goto phys_create_done;
14541                         }
14542                 }
14543 
14544                 if (IS_ATAPI_DEVICE(dev_info)) {
14545                         if (ndi_prop_update_string(DDI_DEV_T_NONE,
14546                             *lun_dip, MPTSAS_VARIANT, "atapi") !=
14547                             DDI_PROP_SUCCESS) {
14548                                 mptsas_log(mpt, CE_WARN,
14549                                     "mptsas unable to create "
14550                                     "property for device variant ");
14551                                 ndi_rtn = NDI_FAILURE;
14552                                 goto phys_create_done;
14553                         }
14554                 }
14555 
14556 phys_raid_lun:
14557                 /*
14558                  * if this is a SAS controller, and the target is a SATA
14559                  * drive, set the 'pm-capable' property for sd and if on
14560                  * an OPL platform, also check if this is an ATAPI
14561                  * device.
14562                  */
14563                 instance = ddi_get_instance(mpt->m_dip);
14564                 if (devinfo & (MPI2_SAS_DEVICE_INFO_SATA_DEVICE |
14565                     MPI2_SAS_DEVICE_INFO_ATAPI_DEVICE)) {
14566                         NDBG2(("mptsas%d: creating pm-capable property, "
14567                             "target %d", instance, target));
14568 
14569                         if ((ndi_prop_update_int(DDI_DEV_T_NONE,
14570                             *lun_dip, "pm-capable", 1)) !=
14571                             DDI_PROP_SUCCESS) {
14572                                 mptsas_log(mpt, CE_WARN, "mptsas "
14573                                     "failed to create pm-capable "
14574                                     "property, target %d", target);
14575                                 ndi_rtn = NDI_FAILURE;
14576                                 goto phys_create_done;
14577                         }
14578 
14579                 }
14580 
14581                 if ((inq->inq_dtype == 0) || (inq->inq_dtype == 5)) {
14582                         /*
14583                          * add 'obp-path' properties for devinfo
14584                          */
14585                         bzero(wwn_str, sizeof (wwn_str));
14586                         (void) sprintf(wwn_str, "%016"PRIx64, sas_wwn);
14587                         component = kmem_zalloc(MAXPATHLEN, KM_SLEEP);
14588                         if (guid) {
14589                                 (void) snprintf(component, MAXPATHLEN,
14590                                     "disk@w%s,%x", wwn_str, lun);
14591                         } else {
14592                                 (void) snprintf(component, MAXPATHLEN,
14593                                     "disk@p%x,%x", phy, lun);
14594                         }
14595                         if (ddi_pathname_obp_set(*lun_dip, component)
14596                             != DDI_SUCCESS) {
14597                                 mptsas_log(mpt, CE_WARN, "mpt_sas driver "
14598                                     "unable to set obp-path for SAS "
14599                                     "object %s", component);
14600                                 ndi_rtn = NDI_FAILURE;
14601                                 goto phys_create_done;
14602                         }
14603                 }
14604                 /*
14605                  * Create the phy-num property for non-raid disk
14606                  */
14607                 if (ptgt->m_addr.mta_phymask != 0) {
14608                         if (ndi_prop_update_int(DDI_DEV_T_NONE,
14609                             *lun_dip, "phy-num", ptgt->m_phynum) !=
14610                             DDI_PROP_SUCCESS) {
14611                                 mptsas_log(mpt, CE_WARN, "mptsas driver "
14612                                     "failed to create phy-num property for "
14613                                     "target %d", target);
14614                                 ndi_rtn = NDI_FAILURE;
14615                                 goto phys_create_done;
14616                         }
14617                 }
14618 phys_create_done:
14619                 /*
14620                  * If props were setup ok, online the lun
14621                  */
14622                 if (ndi_rtn == NDI_SUCCESS) {
14623                         /*
14624                          * Try to online the new node
14625                          */
14626                         ndi_rtn = ndi_devi_online(*lun_dip, NDI_ONLINE_ATTACH);
14627                 }
14628                 if (ndi_rtn == NDI_SUCCESS) {
14629                         mutex_enter(&mpt->m_mutex);
14630                         ptgt->m_led_status = 0;
14631                         (void) mptsas_flush_led_status(mpt, ptgt);
14632                         mutex_exit(&mpt->m_mutex);
14633                 }
14634 
14635                 /*
14636                  * If success set rtn flag, else unwire alloc'd lun
14637                  */
14638                 if (ndi_rtn != NDI_SUCCESS) {
14639                         NDBG12(("mptsas driver unable to online "
14640                             "target %d lun %d", target, lun));
14641                         ndi_prop_remove_all(*lun_dip);
14642                         (void) ndi_devi_free(*lun_dip);
14643                         *lun_dip = NULL;
14644                 }
14645         }
14646 
14647         scsi_hba_nodename_compatible_free(nodename, compatible);
14648 
14649         if (wwn_str != NULL) {
14650                 kmem_free(wwn_str, MPTSAS_WWN_STRLEN);
14651         }
14652         if (component != NULL) {
14653                 kmem_free(component, MAXPATHLEN);
14654         }
14655 
14656 
14657         return ((ndi_rtn == NDI_SUCCESS) ? DDI_SUCCESS : DDI_FAILURE);
14658 }
14659 
14660 static int
14661 mptsas_probe_smp(dev_info_t *pdip, uint64_t wwn)
14662 {
14663         mptsas_t        *mpt = DIP2MPT(pdip);
14664         struct smp_device smp_sd;
14665 
14666         /* XXX An HBA driver should not be allocating an smp_device. */
14667         bzero(&smp_sd, sizeof (struct smp_device));
14668         smp_sd.smp_sd_address.smp_a_hba_tran = mpt->m_smptran;
14669         bcopy(&wwn, smp_sd.smp_sd_address.smp_a_wwn, SAS_WWN_BYTE_SIZE);
14670 
14671         if (smp_probe(&smp_sd) != DDI_PROBE_SUCCESS)
14672                 return (NDI_FAILURE);
14673         return (NDI_SUCCESS);
14674 }
14675 
14676 static int


14707 {
14708         char            wwn_str[MPTSAS_WWN_STRLEN];
14709         char            attached_wwn_str[MPTSAS_WWN_STRLEN];
14710         int             ndi_rtn = NDI_FAILURE;
14711         int             rval = 0;
14712         mptsas_smp_t    dev_info;
14713         uint32_t        page_address;
14714         mptsas_t        *mpt = DIP2MPT(pdip);
14715         uint16_t        dev_hdl;
14716         uint64_t        sas_wwn;
14717         uint64_t        smp_sas_wwn;
14718         uint8_t         physport;
14719         uint8_t         phy_id;
14720         uint16_t        pdev_hdl;
14721         uint8_t         numphys = 0;
14722         uint16_t        i = 0;
14723         char            phymask[MPTSAS_MAX_PHYS];
14724         char            *iport = NULL;
14725         mptsas_phymask_t        phy_mask = 0;
14726         uint16_t        attached_devhdl;
14727         uint16_t        bay_num, enclosure;
14728 
14729         (void) sprintf(wwn_str, "%"PRIx64, smp_node->m_addr.mta_wwn);
14730 
14731         /*
14732          * Probe smp device, prevent the node of removed device from being
14733          * configured succesfully
14734          */
14735         if (mptsas_probe_smp(pdip, smp_node->m_addr.mta_wwn) != NDI_SUCCESS) {
14736                 return (DDI_FAILURE);
14737         }
14738 
14739         if ((*smp_dip = mptsas_find_smp_child(pdip, wwn_str)) != NULL) {
14740                 return (DDI_SUCCESS);
14741         }
14742 
14743         ndi_rtn = ndi_devi_alloc(pdip, "smp", DEVI_SID_NODEID, smp_dip);
14744 
14745         /*
14746          * if lun alloc success, set props
14747          */


14774                 mutex_enter(&mpt->m_mutex);
14775 
14776                 page_address = (MPI2_SAS_EXPAND_PGAD_FORM_HNDL &
14777                     MPI2_SAS_EXPAND_PGAD_FORM_MASK) | smp_node->m_devhdl;
14778                 rval = mptsas_get_sas_expander_page0(mpt, page_address,
14779                     &dev_info);
14780                 if (rval != DDI_SUCCESS) {
14781                         mutex_exit(&mpt->m_mutex);
14782                         mptsas_log(mpt, CE_WARN,
14783                             "mptsas unable to get expander "
14784                             "parent device info for %x", page_address);
14785                         ndi_rtn = NDI_FAILURE;
14786                         goto smp_create_done;
14787                 }
14788 
14789                 smp_node->m_pdevhdl = dev_info.m_pdevhdl;
14790                 page_address = (MPI2_SAS_DEVICE_PGAD_FORM_HANDLE &
14791                     MPI2_SAS_DEVICE_PGAD_FORM_MASK) |
14792                     (uint32_t)dev_info.m_pdevhdl;
14793                 rval = mptsas_get_sas_device_page0(mpt, page_address,
14794                     &dev_hdl, &sas_wwn, &smp_node->m_pdevinfo,
14795                     &physport, &phy_id, &pdev_hdl, &bay_num, &enclosure);
14796                 if (rval != DDI_SUCCESS) {
14797                         mutex_exit(&mpt->m_mutex);
14798                         mptsas_log(mpt, CE_WARN, "mptsas unable to get "
14799                             "device info for %x", page_address);
14800                         ndi_rtn = NDI_FAILURE;
14801                         goto smp_create_done;
14802                 }
14803 
14804                 page_address = (MPI2_SAS_DEVICE_PGAD_FORM_HANDLE &
14805                     MPI2_SAS_DEVICE_PGAD_FORM_MASK) |
14806                     (uint32_t)dev_info.m_devhdl;
14807                 rval = mptsas_get_sas_device_page0(mpt, page_address,
14808                     &dev_hdl, &smp_sas_wwn, &smp_node->m_deviceinfo,
14809                     &physport, &phy_id, &pdev_hdl, &bay_num, &enclosure);

14810                 if (rval != DDI_SUCCESS) {
14811                         mutex_exit(&mpt->m_mutex);
14812                         mptsas_log(mpt, CE_WARN, "mptsas unable to get "
14813                             "device info for %x", page_address);
14814                         ndi_rtn = NDI_FAILURE;
14815                         goto smp_create_done;
14816                 }
14817                 mutex_exit(&mpt->m_mutex);
14818 
14819                 /*
14820                  * If this smp direct attached to the controller
14821                  * set the attached-port to the base wwid
14822                  */
14823                 if ((smp_node->m_deviceinfo & DEVINFO_DIRECT_ATTACHED)
14824                     != DEVINFO_DIRECT_ATTACHED) {
14825                         (void) sprintf(attached_wwn_str, "w%016"PRIx64,
14826                             sas_wwn);
14827                 } else {
14828                         (void) sprintf(attached_wwn_str, "w%016"PRIx64,
14829                             mpt->un.m_base_wwid);


14943                 /*
14944                  * If success set rtn flag, else unwire alloc'd lun
14945                  */
14946                 if (ndi_rtn != NDI_SUCCESS) {
14947                         NDBG12(("mptsas unable to online "
14948                             "SMP target %s", wwn_str));
14949                         ndi_prop_remove_all(*smp_dip);
14950                         (void) ndi_devi_free(*smp_dip);
14951                 }
14952         }
14953 
14954         return ((ndi_rtn == NDI_SUCCESS) ? DDI_SUCCESS : DDI_FAILURE);
14955 }
14956 
14957 /* smp transport routine */
14958 static int mptsas_smp_start(struct smp_pkt *smp_pkt)
14959 {
14960         uint64_t                        wwn;
14961         Mpi2SmpPassthroughRequest_t     req;
14962         Mpi2SmpPassthroughReply_t       rep;
14963         uint32_t                        direction = 0;
14964         mptsas_t                        *mpt;
14965         int                             ret;
14966         uint64_t                        tmp64;
14967 
14968         mpt = (mptsas_t *)smp_pkt->smp_pkt_address->
14969             smp_a_hba_tran->smp_tran_hba_private;
14970 
14971         bcopy(smp_pkt->smp_pkt_address->smp_a_wwn, &wwn, SAS_WWN_BYTE_SIZE);
14972         /*
14973          * Need to compose a SMP request message
14974          * and call mptsas_do_passthru() function
14975          */
14976         bzero(&req, sizeof (req));
14977         bzero(&rep, sizeof (rep));
14978         req.PassthroughFlags = 0;
14979         req.PhysicalPort = 0xff;
14980         req.ChainOffset = 0;
14981         req.Function = MPI2_FUNCTION_SMP_PASSTHROUGH;
14982 
14983         if ((smp_pkt->smp_pkt_reqsize & 0xffff0000ul) != 0) {


15247                 NDBG20(("Hash item already exist"));
15248                 tmp_tgt->m_deviceinfo = devinfo;
15249                 tmp_tgt->m_devhdl = devhdl;  /* XXX - duplicate? */
15250                 return (tmp_tgt);
15251         }
15252         tmp_tgt = kmem_zalloc(sizeof (struct mptsas_target), KM_SLEEP);
15253         if (tmp_tgt == NULL) {
15254                 cmn_err(CE_WARN, "Fatal, allocated tgt failed");
15255                 return (NULL);
15256         }
15257         tmp_tgt->m_devhdl = devhdl;
15258         tmp_tgt->m_addr.mta_wwn = wwid;
15259         tmp_tgt->m_deviceinfo = devinfo;
15260         tmp_tgt->m_addr.mta_phymask = phymask;
15261         tmp_tgt->m_phynum = phynum;
15262         /* Initialized the tgt structure */
15263         tmp_tgt->m_qfull_retries = QFULL_RETRIES;
15264         tmp_tgt->m_qfull_retry_interval =
15265             drv_usectohz(QFULL_RETRY_INTERVAL * 1000);
15266         tmp_tgt->m_t_throttle = MAX_THROTTLE;


15267 
15268         refhash_insert(mpt->m_targets, tmp_tgt);
15269 
15270         return (tmp_tgt);
15271 }
15272 









15273 static mptsas_smp_t *
15274 mptsas_smp_alloc(mptsas_t *mpt, mptsas_smp_t *data)
15275 {
15276         mptsas_target_addr_t addr;
15277         mptsas_smp_t *ret_data;
15278 
15279         addr.mta_wwn = data->m_addr.mta_wwn;
15280         addr.mta_phymask = data->m_addr.mta_phymask;
15281         ret_data = refhash_lookup(mpt->m_smp_targets, &addr);






15282         if (ret_data != NULL) {
15283                 bcopy(data, ret_data, sizeof (mptsas_smp_t)); /* XXX - dupl */
15284                 return (ret_data);
15285         }
15286 
15287         ret_data = kmem_alloc(sizeof (mptsas_smp_t), KM_SLEEP);
15288         bcopy(data, ret_data, sizeof (mptsas_smp_t));
15289         refhash_insert(mpt->m_smp_targets, ret_data);
15290         return (ret_data);
15291 }
15292 
15293 /*
15294  * Functions for SGPIO LED support
15295  */
15296 static dev_info_t *
15297 mptsas_get_dip_from_dev(dev_t dev, mptsas_phymask_t *phymask)
15298 {
15299         dev_info_t      *dip;
15300         int             prop;
15301         dip = e_ddi_hold_devi_by_dev(dev, 0);
15302         if (dip == NULL)
15303                 return (dip);


15427                 *status = LE_32(rep.SlotStatus);
15428         }
15429 
15430         return (0);
15431 }
15432 
15433 int
15434 mptsas_dma_addr_create(mptsas_t *mpt, ddi_dma_attr_t dma_attr,
15435     ddi_dma_handle_t *dma_hdp, ddi_acc_handle_t *acc_hdp, caddr_t *dma_memp,
15436     uint32_t alloc_size, ddi_dma_cookie_t *cookiep)
15437 {
15438         ddi_dma_cookie_t        new_cookie;
15439         size_t                  alloc_len;
15440         uint_t                  ncookie;
15441 
15442         if (cookiep == NULL)
15443                 cookiep = &new_cookie;
15444 
15445         if (ddi_dma_alloc_handle(mpt->m_dip, &dma_attr, DDI_DMA_SLEEP,
15446             NULL, dma_hdp) != DDI_SUCCESS) {
15447                 dma_hdp = NULL;
15448                 return (FALSE);
15449         }
15450 
15451         if (ddi_dma_mem_alloc(*dma_hdp, alloc_size, &mpt->m_dev_acc_attr,
15452             DDI_DMA_CONSISTENT, DDI_DMA_SLEEP, NULL, dma_memp, &alloc_len,
15453             acc_hdp) != DDI_SUCCESS) {
15454                 ddi_dma_free_handle(dma_hdp);
15455                 dma_hdp = NULL;
15456                 return (FALSE);
15457         }
15458 
15459         if (ddi_dma_addr_bind_handle(*dma_hdp, NULL, *dma_memp, alloc_len,
15460             (DDI_DMA_RDWR | DDI_DMA_CONSISTENT), DDI_DMA_SLEEP, NULL,
15461             cookiep, &ncookie) != DDI_DMA_MAPPED) {
15462                 (void) ddi_dma_mem_free(acc_hdp);
15463                 ddi_dma_free_handle(dma_hdp);
15464                 dma_hdp = NULL;
15465                 return (FALSE);
15466         }
15467 
15468         return (TRUE);
15469 }
15470 
15471 void
15472 mptsas_dma_addr_destroy(ddi_dma_handle_t *dma_hdp, ddi_acc_handle_t *acc_hdp)
15473 {
15474         if (*dma_hdp == NULL)
15475                 return;
15476 
15477         (void) ddi_dma_unbind_handle(*dma_hdp);
15478         (void) ddi_dma_mem_free(acc_hdp);
15479         ddi_dma_free_handle(dma_hdp);
15480         dma_hdp = NULL;
15481 }


   4  * The contents of this file are subject to the terms of the
   5  * Common Development and Distribution License (the "License").
   6  * You may not use this file except in compliance with the License.
   7  *
   8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
   9  * or http://www.opensolaris.org/os/licensing.
  10  * See the License for the specific language governing permissions
  11  * and limitations under the License.
  12  *
  13  * When distributing Covered Code, include this CDDL HEADER in each
  14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
  15  * If applicable, add the following below this CDDL HEADER, with the
  16  * fields enclosed by brackets "[]" replaced with your own identifying
  17  * information: Portions Copyright [yyyy] [name of copyright owner]
  18  *
  19  * CDDL HEADER END
  20  */
  21 
  22 /*
  23  * Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
  24  * Copyright 2014 Nexenta Systems, Inc. All rights reserved.
  25  * Copyright (c) 2014, Joyent, Inc. All rights reserved.
  26  * Copyright (c) 2014, Tegile Systems Inc. All rights reserved.
  27  * Copyright 2014 OmniTI Computer Consulting, Inc. All rights reserved.
  28  */
  29 
  30 /*
  31  * Copyright (c) 2000 to 2010, LSI Corporation.
  32  * All rights reserved.
  33  *
  34  * Redistribution and use in source and binary forms of all code within
  35  * this file that is exclusively owned by LSI, with or without
  36  * modification, is permitted provided that, in addition to the CDDL 1.0
  37  * License requirements, the following conditions are met:
  38  *
  39  *    Neither the name of the author nor the names of its contributors may be
  40  *    used to endorse or promote products derived from this software without
  41  *    specific prior written permission.
  42  *
  43  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  44  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  45  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  46  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  47  * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  48  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  49  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
  50  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
  51  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  52  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  53  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
  54  * DAMAGE.
  55  */
  56 
  57 /*
  58  * mptsas3 - This is a driver based on LSI Logic's MPT2.0/2.5 interface.
  59  *
  60  */
  61 
  62 #if defined(lint) || defined(DEBUG)
  63 #define MPTSAS_DEBUG
  64 #endif
  65 
  66 /*
  67  * standard header files.
  68  */
  69 #include <sys/note.h>
  70 #include <sys/scsi/scsi.h>
  71 #include <sys/pci.h>
  72 #include <sys/file.h>
  73 #include <sys/policy.h>
  74 #include <sys/model.h>
  75 #include <sys/sysevent.h>
  76 #include <sys/sysevent/eventdefs.h>
  77 #include <sys/sysevent/dr.h>
  78 #include <sys/sata/sata_defs.h>
  79 #include <sys/scsi/generic/sas.h>
  80 #include <sys/scsi/impl/scsi_sas.h>
  81 
  82 #pragma pack(1)
  83 #include <sys/scsi/adapters/mpt_sas3/mpi/mpi2_type.h>
  84 #include <sys/scsi/adapters/mpt_sas3/mpi/mpi2.h>
  85 #include <sys/scsi/adapters/mpt_sas3/mpi/mpi2_cnfg.h>
  86 #include <sys/scsi/adapters/mpt_sas3/mpi/mpi2_init.h>
  87 #include <sys/scsi/adapters/mpt_sas3/mpi/mpi2_ioc.h>
  88 #include <sys/scsi/adapters/mpt_sas3/mpi/mpi2_sas.h>
  89 #include <sys/scsi/adapters/mpt_sas3/mpi/mpi2_tool.h>
  90 #include <sys/scsi/adapters/mpt_sas3/mpi/mpi2_raid.h>
  91 #pragma pack()
  92 
  93 /*
  94  * private header files.
  95  *
  96  */
  97 #include <sys/scsi/impl/scsi_reset_notify.h>
  98 #include <sys/scsi/adapters/mpt_sas3/mptsas3_var.h>
  99 #include <sys/scsi/adapters/mpt_sas3/mptsas3_ioctl.h>
 100 #include <sys/scsi/adapters/mpt_sas3/mptsas3_smhba.h>
 101 #include <sys/scsi/adapters/mpt_sas3/mptsas3_hash.h>
 102 #include <sys/raidioctl.h>
 103 
 104 #include <sys/fs/dv_node.h>       /* devfs_clean */
 105 
 106 /*
 107  * FMA header files
 108  */
 109 #include <sys/ddifm.h>
 110 #include <sys/fm/protocol.h>
 111 #include <sys/fm/util.h>
 112 #include <sys/fm/io/ddi.h>
 113 
 114 /*
 115  * autoconfiguration data and routines.
 116  */
 117 static int mptsas_attach(dev_info_t *dip, ddi_attach_cmd_t cmd);
 118 static int mptsas_detach(dev_info_t *devi, ddi_detach_cmd_t cmd);
 119 static int mptsas_power(dev_info_t *dip, int component, int level);
 120 
 121 /*


 129 static int mptsas_quiesce(dev_info_t *devi);
 130 #endif  /* __sparc */
 131 
 132 /*
 133  * Resource initilaization for hardware
 134  */
 135 static void mptsas_setup_cmd_reg(mptsas_t *mpt);
 136 static void mptsas_disable_bus_master(mptsas_t *mpt);
 137 static void mptsas_hba_fini(mptsas_t *mpt);
 138 static void mptsas_cfg_fini(mptsas_t *mptsas_blkp);
 139 static int mptsas_hba_setup(mptsas_t *mpt);
 140 static void mptsas_hba_teardown(mptsas_t *mpt);
 141 static int mptsas_config_space_init(mptsas_t *mpt);
 142 static void mptsas_config_space_fini(mptsas_t *mpt);
 143 static void mptsas_iport_register(mptsas_t *mpt);
 144 static int mptsas_smp_setup(mptsas_t *mpt);
 145 static void mptsas_smp_teardown(mptsas_t *mpt);
 146 static int mptsas_cache_create(mptsas_t *mpt);
 147 static void mptsas_cache_destroy(mptsas_t *mpt);
 148 static int mptsas_alloc_request_frames(mptsas_t *mpt);
 149 static int mptsas_alloc_sense_bufs(mptsas_t *mpt);
 150 static int mptsas_alloc_reply_frames(mptsas_t *mpt);
 151 static int mptsas_alloc_free_queue(mptsas_t *mpt);
 152 static int mptsas_alloc_post_queue(mptsas_t *mpt);
 153 static void mptsas_free_post_queue(mptsas_t *mpt);
 154 static void mptsas_alloc_reply_args(mptsas_t *mpt);
 155 static int mptsas_alloc_extra_sgl_frame(mptsas_t *mpt, mptsas_cmd_t *cmd);
 156 static void mptsas_free_extra_sgl_frame(mptsas_t *mpt, mptsas_cmd_t *cmd);
 157 static int mptsas_init_chip(mptsas_t *mpt, int first_time);
 158 
 159 /*
 160  * SCSA function prototypes
 161  */
 162 static int mptsas_scsi_start(struct scsi_address *ap, struct scsi_pkt *pkt);
 163 static int mptsas_scsi_reset(struct scsi_address *ap, int level);
 164 static int mptsas_scsi_abort(struct scsi_address *ap, struct scsi_pkt *pkt);
 165 static int mptsas_scsi_getcap(struct scsi_address *ap, char *cap, int tgtonly);
 166 static int mptsas_scsi_setcap(struct scsi_address *ap, char *cap, int value,
 167     int tgtonly);
 168 static void mptsas_scsi_dmafree(struct scsi_address *ap, struct scsi_pkt *pkt);
 169 static struct scsi_pkt *mptsas_scsi_init_pkt(struct scsi_address *ap,
 170     struct scsi_pkt *pkt, struct buf *bp, int cmdlen, int statuslen,
 171         int tgtlen, int flags, int (*callback)(), caddr_t arg);
 172 static void mptsas_scsi_sync_pkt(struct scsi_address *ap, struct scsi_pkt *pkt);
 173 static void mptsas_scsi_destroy_pkt(struct scsi_address *ap,


 188 /*
 189  * SMP functions
 190  */
 191 static int mptsas_smp_start(struct smp_pkt *smp_pkt);
 192 
 193 /*
 194  * internal function prototypes.
 195  */
 196 static void mptsas_list_add(mptsas_t *mpt);
 197 static void mptsas_list_del(mptsas_t *mpt);
 198 
 199 static int mptsas_quiesce_bus(mptsas_t *mpt);
 200 static int mptsas_unquiesce_bus(mptsas_t *mpt);
 201 
 202 static int mptsas_alloc_handshake_msg(mptsas_t *mpt, size_t alloc_size);
 203 static void mptsas_free_handshake_msg(mptsas_t *mpt);
 204 
 205 static void mptsas_ncmds_checkdrain(void *arg);
 206 
 207 static int mptsas_prepare_pkt(mptsas_cmd_t *cmd);
 208 static void mptsas_retry_pkt(mptsas_t *mpt, mptsas_cmd_t *sp);
 209 static int mptsas_save_cmd_to_slot(mptsas_t *mpt, mptsas_cmd_t *cmd);
 210 static int mptsas_accept_pkt(mptsas_t *mpt, mptsas_cmd_t *sp,
 211     int *tran_rval);
 212 static void mptsas_accept_tx_waitqs(mptsas_t *mpt);
 213 static void mptsas_unblock_tx_waitqs(mptsas_t *mpt);
 214 static void mptsas_drain_tx_waitq(mptsas_t *mpt, mptsas_tx_waitqueue_t *txwq);
 215 static int mptsas_check_targ_intxtion(mptsas_target_t *ptgt, int cmd_pkt_flags);
 216 
 217 static int mptsas_do_detach(dev_info_t *dev);
 218 static int mptsas_do_scsi_reset(mptsas_t *mpt, uint16_t devhdl);
 219 static int mptsas_do_scsi_abort(mptsas_t *mpt, int target, int lun,
 220     struct scsi_pkt *pkt);
 221 static int mptsas_scsi_capchk(char *cap, int tgtonly, int *cidxp);
 222 
 223 static void mptsas_handle_qfull(mptsas_t *mpt, mptsas_cmd_t *cmd);
 224 static void mptsas_handle_event(void *args);
 225 static int mptsas_handle_event_sync(void *args);
 226 static void mptsas_handle_dr(void *args);
 227 static void mptsas_handle_topo_change(mptsas_topo_change_list_t *topo_node,
 228     dev_info_t *pdip);
 229 
 230 static void mptsas_restart_cmd(void *);
 231 
 232 static void mptsas_flush_hba(mptsas_t *mpt);
 233 static void mptsas_flush_target(mptsas_t *mpt, ushort_t target, int lun,
 234         uint8_t tasktype);
 235 static void mptsas_set_pkt_reason(mptsas_t *mpt, mptsas_cmd_t *cmd,
 236     uchar_t reason, uint_t stat);
 237 
 238 static uint_t mptsas_intr(caddr_t arg1, caddr_t arg2);
 239 static void mptsas_process_intr(mptsas_t *mpt, mptsas_reply_pqueue_t *rpqp,
 240     pMpi2ReplyDescriptorsUnion_t reply_desc_union);
 241 static void mptsas_handle_scsi_io_success(mptsas_t *mpt,
 242     mptsas_reply_pqueue_t *rpqp, pMpi2ReplyDescriptorsUnion_t reply_desc);
 243 static void mptsas_handle_address_reply(mptsas_t *mpt,
 244     pMpi2ReplyDescriptorsUnion_t reply_desc);
 245 static int mptsas_wait_intr(mptsas_t *mpt, int polltime);
 246 static void mptsas_sge_setup(mptsas_t *mpt, mptsas_cmd_t *cmd,
 247     uint32_t *control, pMpi2SCSIIORequest_t frame, ddi_acc_handle_t acc_hdl);
 248 
 249 static void mptsas_watch(void *arg);
 250 static void mptsas_watchsubr(mptsas_t *mpt);
 251 static void mptsas_cmd_timeout(mptsas_t *mpt, mptsas_target_t *ptgt);
 252 
 253 static void mptsas_start_passthru(mptsas_t *mpt, mptsas_cmd_t *cmd);
 254 static int mptsas_do_passthru(mptsas_t *mpt, uint8_t *request, uint8_t *reply,
 255     uint8_t *data, uint32_t request_size, uint32_t reply_size,
 256     uint32_t data_size, uint8_t direction, uint8_t *dataout,
 257     uint32_t dataout_size, short timeout, int mode);
 258 static int mptsas_free_devhdl(mptsas_t *mpt, uint16_t devhdl);
 259 
 260 static uint8_t mptsas_get_fw_diag_buffer_number(mptsas_t *mpt,
 261     uint32_t unique_id);
 262 static void mptsas_start_diag(mptsas_t *mpt, mptsas_cmd_t *cmd);
 263 static int mptsas_post_fw_diag_buffer(mptsas_t *mpt,
 264     mptsas_fw_diagnostic_buffer_t *pBuffer, uint32_t *return_code);
 265 static int mptsas_release_fw_diag_buffer(mptsas_t *mpt,
 266     mptsas_fw_diagnostic_buffer_t *pBuffer, uint32_t *return_code,
 267     uint32_t diag_type);
 268 static int mptsas_diag_register(mptsas_t *mpt,
 269     mptsas_fw_diag_register_t *diag_register, uint32_t *return_code);
 270 static int mptsas_diag_unregister(mptsas_t *mpt,
 271     mptsas_fw_diag_unregister_t *diag_unregister, uint32_t *return_code);
 272 static int mptsas_diag_query(mptsas_t *mpt, mptsas_fw_diag_query_t *diag_query,
 273     uint32_t *return_code);
 274 static int mptsas_diag_read_buffer(mptsas_t *mpt,
 275     mptsas_diag_read_buffer_t *diag_read_buffer, uint8_t *ioctl_buf,
 276     uint32_t *return_code, int ioctl_mode);


 291 
 292 static int mptsas_cache_frames_constructor(void *buf, void *cdrarg,
 293     int kmflags);
 294 static void mptsas_cache_frames_destructor(void *buf, void *cdrarg);
 295 
 296 static void mptsas_check_scsi_io_error(mptsas_t *mpt, pMpi2SCSIIOReply_t reply,
 297     mptsas_cmd_t *cmd);
 298 static void mptsas_check_task_mgt(mptsas_t *mpt,
 299     pMpi2SCSIManagementReply_t reply, mptsas_cmd_t *cmd);
 300 static int mptsas_send_scsi_cmd(mptsas_t *mpt, struct scsi_address *ap,
 301     mptsas_target_t *ptgt, uchar_t *cdb, int cdblen, struct buf *data_bp,
 302     int *resid);
 303 
 304 static int mptsas_alloc_active_slots(mptsas_t *mpt, int flag);
 305 static void mptsas_free_active_slots(mptsas_t *mpt);
 306 static int mptsas_start_cmd(mptsas_t *mpt, mptsas_cmd_t *cmd);
 307 
 308 static void mptsas_restart_hba(mptsas_t *mpt);
 309 static void mptsas_restart_waitq(mptsas_t *mpt);
 310 
 311 static void mptsas_deliver_doneq_thread(mptsas_t *mpt,
 312     mptsas_done_list_t *dlist);
 313 static void mptsas_doneq_add(mptsas_t *mpt, mptsas_cmd_t *cmd);
 314 static void mptsas_rpdoneq_add(mptsas_t *mpt, mptsas_reply_pqueue_t *rpqp,
 315     mptsas_cmd_t *cmd);
 316 static void mptsas_doneq_mv(mptsas_done_list_t *from,
 317     mptsas_doneq_thread_list_t *item);
 318 
 319 static mptsas_cmd_t *mptsas_doneq_thread_rm(mptsas_t *mpt, uint64_t t);
 320 static void mptsas_doneq_empty(mptsas_t *mpt);
 321 static void mptsas_rpdoneq_empty(mptsas_reply_pqueue_t *rpqp);
 322 static void mptsas_doneq_thread(mptsas_thread_arg_t *arg);
 323 static void mptsas_tx_waitq_thread(mptsas_thread_arg_t *arg);
 324 
 325 static mptsas_cmd_t *mptsas_waitq_rm(mptsas_t *mpt);
 326 static void mptsas_waitq_delete(mptsas_t *mpt, mptsas_cmd_t *cmd);



 327 
 328 static void mptsas_start_watch_reset_delay();
 329 static void mptsas_setup_bus_reset_delay(mptsas_t *mpt);
 330 static void mptsas_watch_reset_delay(void *arg);
 331 static int mptsas_watch_reset_delay_subr(mptsas_t *mpt);
 332 static void mptsas_set_throttle(struct mptsas *mpt, mptsas_target_t *ptgt,
 333     int what);
 334 static void mptsas_set_throttle_mtx(struct mptsas *mpt, mptsas_target_t *ptgt,
 335     int what);
 336 static void mptsas_remove_cmd_nomtx(mptsas_t *mpt, mptsas_cmd_t *cmd);
 337 
 338 /*
 339  * helper functions
 340  */
 341 static void mptsas_dump_cmd(mptsas_t *mpt, mptsas_cmd_t *cmd);
 342 
 343 static dev_info_t *mptsas_find_child(dev_info_t *pdip, char *name);
 344 static dev_info_t *mptsas_find_child_phy(dev_info_t *pdip, uint8_t phy);
 345 static dev_info_t *mptsas_find_child_addr(dev_info_t *pdip, uint64_t sasaddr,
 346     int lun);
 347 static mdi_pathinfo_t *mptsas_find_path_addr(dev_info_t *pdip, uint64_t sasaddr,
 348     int lun);
 349 static mdi_pathinfo_t *mptsas_find_path_phy(dev_info_t *pdip, uint8_t phy);
 350 static dev_info_t *mptsas_find_smp_child(dev_info_t *pdip, char *str_wwn);
 351 
 352 static int mptsas_parse_address(char *name, uint64_t *wwid, uint8_t *phy,
 353     int *lun);
 354 static int mptsas_parse_smp_name(char *name, uint64_t *wwn);
 355 
 356 static mptsas_target_t *mptsas_phy_to_tgt(mptsas_t *mpt,


 369 
 370 static int mptsas_send_sep(mptsas_t *mpt, mptsas_target_t *ptgt,
 371     uint32_t *status, uint8_t cmd);
 372 static dev_info_t *mptsas_get_dip_from_dev(dev_t dev,
 373     mptsas_phymask_t *phymask);
 374 static mptsas_target_t *mptsas_addr_to_ptgt(mptsas_t *mpt, char *addr,
 375     mptsas_phymask_t phymask);
 376 static int mptsas_flush_led_status(mptsas_t *mpt, mptsas_target_t *ptgt);
 377 
 378 
 379 /*
 380  * Enumeration / DR functions
 381  */
 382 static void mptsas_config_all(dev_info_t *pdip);
 383 static int mptsas_config_one_addr(dev_info_t *pdip, uint64_t sasaddr, int lun,
 384     dev_info_t **lundip);
 385 static int mptsas_config_one_phy(dev_info_t *pdip, uint8_t phy, int lun,
 386     dev_info_t **lundip);
 387 
 388 static int mptsas_config_target(dev_info_t *pdip, mptsas_target_t *ptgt);
 389 static int mptsas_offline_targetdev(dev_info_t *pdip, char *name);
 390 static void mptsas_offline_target(mptsas_t *mpt, mptsas_target_t *ptgt,
 391     uint8_t topo_flags, dev_info_t *parent);
 392 
 393 static int mptsas_config_raid(dev_info_t *pdip, uint16_t target,
 394     dev_info_t **dip);
 395 
 396 static int mptsas_config_luns(dev_info_t *pdip, mptsas_target_t *ptgt);
 397 static int mptsas_probe_lun(dev_info_t *pdip, int lun,
 398     dev_info_t **dip, mptsas_target_t *ptgt);
 399 
 400 static int mptsas_create_lun(dev_info_t *pdip, struct scsi_inquiry *sd_inq,
 401     dev_info_t **dip, mptsas_target_t *ptgt, int lun);
 402 
 403 static int mptsas_create_phys_lun(dev_info_t *pdip, struct scsi_inquiry *sd,
 404     char *guid, dev_info_t **dip, mptsas_target_t *ptgt, int lun);
 405 static int mptsas_create_virt_lun(dev_info_t *pdip, struct scsi_inquiry *sd,
 406     char *guid, dev_info_t **dip, mdi_pathinfo_t **pip, mptsas_target_t *ptgt,
 407     int lun);
 408 
 409 static void mptsas_offline_missed_luns(dev_info_t *pdip,
 410     uint16_t *repluns, int lun_cnt, mptsas_target_t *ptgt);
 411 static int mptsas_offline_lun(dev_info_t *pdip, dev_info_t *rdip,


 427     int mode);
 428 
 429 mptsas_target_t *mptsas_tgt_alloc(mptsas_t *, uint16_t, uint64_t,
 430     uint32_t, mptsas_phymask_t, uint8_t);
 431 static mptsas_smp_t *mptsas_smp_alloc(mptsas_t *, mptsas_smp_t *);
 432 static int mptsas_online_smp(dev_info_t *pdip, mptsas_smp_t *smp_node,
 433     dev_info_t **smp_dip);
 434 
 435 /*
 436  * Power management functions
 437  */
 438 static int mptsas_get_pci_cap(mptsas_t *mpt);
 439 static int mptsas_init_pm(mptsas_t *mpt);
 440 
 441 /*
 442  * MPT MSI tunable:
 443  *
 444  * By default MSI is enabled on all supported platforms.
 445  */
 446 boolean_t mptsas_enable_msi = B_TRUE;
 447 boolean_t mptsas_enable_msix = B_TRUE;
 448 boolean_t mptsas_physical_bind_failed_page_83 = B_FALSE;
 449 
 450 /*
 451  * Global switch for use of MPI2.5 FAST PATH.
 452  */
 453 boolean_t mptsas3_use_fastpath = B_TRUE;
 454 
 455 static int mptsas_register_intrs(mptsas_t *);
 456 static void mptsas_unregister_intrs(mptsas_t *);
 457 static int mptsas_add_intrs(mptsas_t *, int);
 458 static void mptsas_rem_intrs(mptsas_t *);
 459 
 460 /*
 461  * FMA Prototypes
 462  */
 463 static void mptsas_fm_init(mptsas_t *mpt);
 464 static void mptsas_fm_fini(mptsas_t *mpt);
 465 static int mptsas_fm_error_cb(dev_info_t *, ddi_fm_error_t *, const void *);
 466 
 467 extern pri_t minclsyspri, maxclsyspri;
 468 /*
 469  * NCPUS is used to determine some optimal configurations for number
 470  * of threads created to perform specific jobs. If we are invoked because
 471  * a disk is part of the root file system ncpus may still be 1 so check
 472  * boot_ncpus as well.
 473  */
 474 extern int ncpus, boot_ncpus;
 475 #define NCPUS   max(ncpus, boot_ncpus)
 476 
 477 /*
 478  * This device is created by the SCSI pseudo nexus driver (SCSI vHCI).  It is
 479  * under this device that the paths to a physical device are created when
 480  * MPxIO is used.
 481  */
 482 extern dev_info_t       *scsi_vhci_dip;
 483 
 484 /*
 485  * Tunable timeout value for Inquiry VPD page 0x83
 486  * By default the value is 30 seconds.
 487  */
 488 int mptsas_inq83_retry_timeout = 30;
 489 
 490 /*
 491  * Tunable for default SCSI pkt timeout. Defaults to 5 seconds, which should
 492  * be plenty for INQUIRY and REPORT_LUNS, which are the only commands currently
 493  * issued by mptsas directly.
 494  */
 495 int mptsas_scsi_pkt_time = 5;
 496 
 497 /*
 498  * This is used to allocate memory for message frame storage, not for
 499  * data I/O DMA. All message frames must be stored in the first 4G of
 500  * physical memory.
 501  */
 502 ddi_dma_attr_t mptsas_dma_attrs = {
 503         DMA_ATTR_V0,    /* attribute layout version             */
 504         0x0ull,         /* address low - should be 0 (longlong) */
 505         0xffffffffull,  /* address high - 32-bit max range      */
 506         0x00ffffffull,  /* count max - max DMA object size      */
 507         4,              /* allocation alignment requirements    */
 508         0x78,           /* burstsizes - binary encoded values   */
 509         1,              /* minxfer - gran. of DMA engine        */
 510         0x00ffffffull,  /* maxxfer - gran. of DMA engine        */
 511         0xffffffffull,  /* max segment size (DMA boundary)      */
 512         MPTSAS_MAX_DMA_SEGS, /* scatter/gather list length      */
 513         512,            /* granularity - device transfer size   */
 514         0               /* flags, set to 0                      */
 515 };
 516 
 517 /*
 518  * This is used for data I/O DMA memory allocation. (full 64-bit DMA
 519  * physical addresses are supported.)
 520  */
 521 ddi_dma_attr_t mptsas_dma_attrs64 = {
 522         DMA_ATTR_V0,    /* attribute layout version             */
 523         0x0ull,         /* address low - should be 0 (longlong) */
 524         0xffffffffffffffffull,  /* address high - 64-bit max    */
 525         0x00ffffffull,  /* count max - max DMA object size      */
 526         4,              /* allocation alignment requirements    */
 527         0x78,           /* burstsizes - binary encoded values   */
 528         1,              /* minxfer - gran. of DMA engine        */
 529         0x00ffffffull,  /* maxxfer - gran. of DMA engine        */
 530         0xffffffffull,  /* max segment size (DMA boundary)      */
 531         MPTSAS_MAX_DMA_SEGS, /* scatter/gather list length      */
 532         512,            /* granularity - device transfer size   */
 533         0               /* flags, set to 0 */
 534 };
 535 
 536 ddi_device_acc_attr_t mptsas_dev_attr = {
 537         DDI_DEVICE_ATTR_V1,
 538         DDI_STRUCTURE_LE_ACC,
 539         DDI_STRICTORDER_ACC,
 540         DDI_DEFAULT_ACC
 541 };
 542 
 543 static struct cb_ops mptsas_cb_ops = {
 544         scsi_hba_open,          /* open */
 545         scsi_hba_close,         /* close */
 546         nodev,                  /* strategy */
 547         nodev,                  /* print */
 548         nodev,                  /* dump */
 549         nodev,                  /* read */
 550         nodev,                  /* write */
 551         mptsas_ioctl,           /* ioctl */
 552         nodev,                  /* devmap */
 553         nodev,                  /* mmap */


 568         nulldev,                /* identify */
 569         nulldev,                /* probe */
 570         mptsas_attach,          /* attach */
 571         mptsas_detach,          /* detach */
 572 #ifdef  __sparc
 573         mptsas_reset,
 574 #else
 575         nodev,                  /* reset */
 576 #endif  /* __sparc */
 577         &mptsas_cb_ops,             /* driver operations */
 578         NULL,                   /* bus operations */
 579         mptsas_power,           /* power management */
 580 #ifdef  __sparc
 581         ddi_quiesce_not_needed
 582 #else
 583         mptsas_quiesce          /* quiesce */
 584 #endif  /* __sparc */
 585 };
 586 
 587 
 588 #define MPTSAS_MOD_STRING "MPTSAS3 HBA Driver 00.00.01"
 589 
 590 static struct modldrv modldrv = {
 591         &mod_driverops,     /* Type of module. This one is a driver */
 592         MPTSAS_MOD_STRING, /* Name of the module. */
 593         &mptsas_ops,        /* driver ops */
 594 };
 595 
 596 static struct modlinkage modlinkage = {
 597         MODREV_1, &modldrv, NULL
 598 };
 599 #define TARGET_PROP     "target"
 600 #define LUN_PROP        "lun"
 601 #define LUN64_PROP      "lun64"
 602 #define SAS_PROP        "sas-mpt"
 603 #define MDI_GUID        "wwn"
 604 #define NDI_GUID        "guid"
 605 #define MPTSAS_DEV_GONE "mptsas_dev_gone"
 606 
 607 /*
 608  * Local static data
 609  */
 610 #if defined(MPTSAS_DEBUG)
 611 uint32_t mptsas_debug_flags = 0x0;
 612 /*
 613  * Flags to ignore these messages in local debug ring buffer.
 614  * Default is to ignore the watchsubr() output which normally happens
 615  * every second.
 616  */
 617 uint32_t mptsas_dbglog_imask = 0x40000000;
 618 uint32_t mptsas_test_timeout = 0;
 619 #endif  /* defined(MPTSAS_DEBUG) */
 620 uint32_t mptsas_debug_resets = 0;
 621 
 622 static kmutex_t         mptsas_global_mutex;
 623 static void             *mptsas3_state;         /* soft state ptr */
 624 static krwlock_t        mptsas_global_rwlock;
 625 
 626 static kmutex_t         mptsas_log_mutex;
 627 static char             mptsas_log_buf[256];
 628 _NOTE(MUTEX_PROTECTS_DATA(mptsas_log_mutex, mptsas_log_buf))
 629 
 630 static mptsas_t *mptsas_head, *mptsas_tail;
 631 static clock_t mptsas_scsi_watchdog_tick;
 632 static clock_t mptsas_tick;
 633 static timeout_id_t mptsas_reset_watch;
 634 static timeout_id_t mptsas_timeout_id;
 635 static int mptsas_timeouts_enabled = 0;
 636 
 637 /*
 638  * Maximum number of MSI-X interrupts any instance of mptsas3 can use.
 639  * Note that if you want to increase this you may have to also bump the
 640  * value of ddi_msix_alloc_limit which defaults to 8.
 641  * Set to zero to fall back to other interrupt types.
 642  */
 643 int mptsas3_max_msix_intrs = 8;
 644 
 645 /*
 646  * Default length for extended auto request sense buffers.
 647  * All sense buffers need to be under the same alloc because there
 648  * is only one common top 32bits (of 64bits) address register.
 649  * Most requests only require 32 bytes, but some request >256.
 650  * We use rmalloc()/rmfree() on this additional memory to manage the
 651  * "extended" requests.
 652  */
 653 int mptsas_extreq_sense_bufsize = 256*64;
 654 
 655 /*
 656  * Believe that all software resrictions of having to run with DMA
 657  * attributes to limit allocation to the first 4G are removed.
 658  * However, this flag remains to enable quick switchback should suspicious
 659  * problems emerge.
 660  * Note that scsi_alloc_consistent_buf() does still adhering to allocating
 661  * 32 bit addressable memory, but we can cope if that is changed now.
 662  */
 663 int mptsas_use_64bit_msgaddr = 1;
 664 
 665 /*
 666  * warlock directives
 667  */
 668 _NOTE(SCHEME_PROTECTS_DATA("unique per pkt", scsi_pkt \
 669         mptsas_cmd NcrTableIndirect buf scsi_cdb scsi_status))
 670 _NOTE(SCHEME_PROTECTS_DATA("unique per pkt", smp_pkt))
 671 _NOTE(SCHEME_PROTECTS_DATA("stable data", scsi_device scsi_address))
 672 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", mptsas_tgt_private))
 673 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", scsi_hba_tran::tran_tgt_private))
 674 
 675 /*
 676  * SM - HBA statics
 677  */
 678 char    *mptsas_driver_rev = MPTSAS_MOD_STRING;
 679 
 680 #ifdef MPTSAS_DEBUG
 681 void debug_enter(char *);
 682 #endif
 683 
 684 /*
 685  * Notes:
 686  *      - scsi_hba_init(9F) initializes SCSI HBA modules
 687  *      - must call scsi_hba_fini(9F) if modload() fails
 688  */
 689 int
 690 _init(void)
 691 {
 692         int status;
 693         /* CONSTCOND */
 694         ASSERT(NO_COMPETING_THREADS);
 695 
 696         NDBG0(("_init"));
 697 
 698         status = ddi_soft_state_init(&mptsas3_state, MPTSAS_SIZE,
 699             MPTSAS_INITIAL_SOFT_SPACE);
 700         if (status != 0) {
 701                 return (status);
 702         }
 703 
 704         if ((status = scsi_hba_init(&modlinkage)) != 0) {
 705                 ddi_soft_state_fini(&mptsas3_state);
 706                 return (status);
 707         }
 708 
 709         mutex_init(&mptsas_global_mutex, NULL, MUTEX_DRIVER, NULL);
 710         rw_init(&mptsas_global_rwlock, NULL, RW_DRIVER, NULL);
 711         mutex_init(&mptsas_log_mutex, NULL, MUTEX_DRIVER, NULL);
 712 
 713         if ((status = mod_install(&modlinkage)) != 0) {
 714                 mutex_destroy(&mptsas_log_mutex);
 715                 rw_destroy(&mptsas_global_rwlock);
 716                 mutex_destroy(&mptsas_global_mutex);
 717                 ddi_soft_state_fini(&mptsas3_state);
 718                 scsi_hba_fini(&modlinkage);
 719         }
 720 
 721         return (status);
 722 }
 723 
 724 /*
 725  * Notes:
 726  *      - scsi_hba_fini(9F) uninitializes SCSI HBA modules
 727  */
 728 int
 729 _fini(void)
 730 {
 731         int     status;
 732         /* CONSTCOND */
 733         ASSERT(NO_COMPETING_THREADS);
 734 
 735         NDBG0(("_fini"));
 736 
 737         if ((status = mod_remove(&modlinkage)) == 0) {
 738                 ddi_soft_state_fini(&mptsas3_state);
 739                 scsi_hba_fini(&modlinkage);
 740                 mutex_destroy(&mptsas_global_mutex);
 741                 rw_destroy(&mptsas_global_rwlock);
 742                 mutex_destroy(&mptsas_log_mutex);
 743         }
 744         return (status);
 745 }
 746 
 747 /*
 748  * The loadable-module _info(9E) entry point
 749  */
 750 int
 751 _info(struct modinfo *modinfop)
 752 {
 753         /* CONSTCOND */
 754         ASSERT(NO_COMPETING_THREADS);
 755         NDBG0(("mptsas _info"));
 756 
 757         return (mod_info(&modlinkage, modinfop));
 758 }


 824 static void
 825 mptsas_target_free(void *op)
 826 {
 827         kmem_free(op, sizeof (mptsas_target_t));
 828 }
 829 
 830 static void
 831 mptsas_smp_free(void *op)
 832 {
 833         kmem_free(op, sizeof (mptsas_smp_t));
 834 }
 835 
 836 static void
 837 mptsas_destroy_hashes(mptsas_t *mpt)
 838 {
 839         mptsas_target_t *tp;
 840         mptsas_smp_t *sp;
 841 
 842         for (tp = refhash_first(mpt->m_targets); tp != NULL;
 843             tp = refhash_next(mpt->m_targets, tp)) {
 844                 mutex_destroy(&tp->m_t_mutex);
 845                 refhash_remove(mpt->m_targets, tp);
 846         }
 847         for (sp = refhash_first(mpt->m_smp_targets); sp != NULL;
 848             sp = refhash_next(mpt->m_smp_targets, sp)) {
 849                 refhash_remove(mpt->m_smp_targets, sp);
 850         }
 851         refhash_destroy(mpt->m_targets);
 852         refhash_destroy(mpt->m_smp_targets);
 853         mpt->m_targets = NULL;
 854         mpt->m_smp_targets = NULL;
 855 }
 856 
 857 static int
 858 mptsas_iport_attach(dev_info_t *dip, ddi_attach_cmd_t cmd)
 859 {
 860         dev_info_t              *pdip;
 861         mptsas_t                *mpt;
 862         scsi_hba_tran_t         *hba_tran;
 863         char                    *iport = NULL;
 864         char                    phymask[MPTSAS_MAX_PHYS];
 865         mptsas_phymask_t        phy_mask = 0;
 866         int                     dynamic_port = 0;
 867         uint32_t                page_address;
 868         char                    initiator_wwnstr[MPTSAS_WWN_STRLEN];
 869         int                     rval = DDI_FAILURE;
 870         int                     i = 0;
 871         uint8_t                 numphys = 0;
 872         uint8_t                 phy_id;
 873         uint8_t                 phy_port = 0;
 874         uint16_t                attached_devhdl = 0;
 875         uint32_t                dev_info;
 876         uint64_t                attached_sas_wwn;
 877         uint16_t                dev_hdl;
 878         uint16_t                pdev_hdl;
 879         uint16_t                bay_num, enclosure, io_flags;
 880         char                    attached_wwnstr[MPTSAS_WWN_STRLEN];
 881 
 882         /* CONSTCOND */
 883         ASSERT(NO_COMPETING_THREADS);
 884 
 885         switch (cmd) {
 886         case DDI_ATTACH:
 887                 break;
 888 
 889         case DDI_RESUME:
 890                 /*
 891                  * If this a scsi-iport node, nothing to do here.
 892                  */
 893                 return (DDI_SUCCESS);
 894 
 895         default:
 896                 return (DDI_FAILURE);
 897         }
 898 
 899         pdip = ddi_get_parent(dip);


1021                     "prop update failed");
1022                 return (DDI_FAILURE);
1023         }
1024         if (ddi_prop_update_int(DDI_DEV_T_NONE, dip,
1025             MPTSAS_VIRTUAL_PORT, 0) !=
1026             DDI_PROP_SUCCESS) {
1027                 (void) ddi_prop_remove(DDI_DEV_T_NONE, dip,
1028                     MPTSAS_VIRTUAL_PORT);
1029                 mptsas_log(mpt, CE_WARN, "mptsas virtual port "
1030                     "prop update failed");
1031                 return (DDI_FAILURE);
1032         }
1033         mptsas_smhba_set_all_phy_props(mpt, dip, numphys, phy_mask,
1034             &attached_devhdl);
1035 
1036         mutex_enter(&mpt->m_mutex);
1037         page_address = (MPI2_SAS_DEVICE_PGAD_FORM_HANDLE &
1038             MPI2_SAS_DEVICE_PGAD_FORM_MASK) | (uint32_t)attached_devhdl;
1039         rval = mptsas_get_sas_device_page0(mpt, page_address, &dev_hdl,
1040             &attached_sas_wwn, &dev_info, &phy_port, &phy_id,
1041             &pdev_hdl, &bay_num, &enclosure, &io_flags);
1042         if (rval != DDI_SUCCESS) {
1043                 mptsas_log(mpt, CE_WARN,
1044                     "Failed to get device page0 for handle:%d",
1045                     attached_devhdl);
1046                 mutex_exit(&mpt->m_mutex);
1047                 return (DDI_FAILURE);
1048         }
1049 
1050         for (i = 0; i < MPTSAS_MAX_PHYS; i++) {
1051                 bzero(phymask, sizeof (phymask));
1052                 (void) sprintf(phymask, "%x", mpt->m_phy_info[i].phy_mask);
1053                 if (strcmp(phymask, iport) == 0) {
1054                         (void) sprintf(&mpt->m_phy_info[i].smhba_info.path[0],
1055                             "%x",
1056                             mpt->m_phy_info[i].phy_mask);
1057                 }
1058         }
1059         mutex_exit(&mpt->m_mutex);
1060 
1061         bzero(attached_wwnstr, sizeof (attached_wwnstr));


1078          */
1079         if (mdi_phci_register(MDI_HCI_CLASS_SCSI,
1080             dip, 0) == MDI_SUCCESS) {
1081                 mpt->m_mpxio_enable = TRUE;
1082         }
1083         return (DDI_SUCCESS);
1084 }
1085 
1086 /*
1087  * Notes:
1088  *      Set up all device state and allocate data structures,
1089  *      mutexes, condition variables, etc. for device operation.
1090  *      Add interrupts needed.
1091  *      Return DDI_SUCCESS if device is ready, else return DDI_FAILURE.
1092  */
1093 static int
1094 mptsas_attach(dev_info_t *dip, ddi_attach_cmd_t cmd)
1095 {
1096         mptsas_t                *mpt = NULL;
1097         int                     instance, i, j;
1098         int                     q_thread_num;

1099         char                    map_setup = 0;
1100         char                    config_setup = 0;
1101         char                    hba_attach_setup = 0;
1102         char                    smp_attach_setup = 0;
1103         char                    mutex_init_done = 0;
1104         char                    event_taskq_create = 0;
1105         char                    dr_taskq_create = 0;
1106         char                    doneq_thread_create = 0;
1107         char                    txwq_thread_create = 0;
1108         char                    added_watchdog = 0;
1109         scsi_hba_tran_t         *hba_tran;
1110         uint_t                  mem_bar = MEM_SPACE;
1111         int                     rval = DDI_FAILURE;
1112 
1113         /* CONSTCOND */
1114         ASSERT(NO_COMPETING_THREADS);
1115 
1116         if (scsi_hba_iport_unit_address(dip)) {
1117                 return (mptsas_iport_attach(dip, cmd));
1118         }
1119 
1120         switch (cmd) {
1121         case DDI_ATTACH:
1122                 break;
1123 
1124         case DDI_RESUME:
1125                 if ((hba_tran = ddi_get_driver_private(dip)) == NULL)
1126                         return (DDI_FAILURE);
1127 
1128                 mpt = TRAN2MPT(hba_tran);


1203                 }
1204                 mutex_exit(&mptsas_global_mutex);
1205 
1206                 /* report idle status to pm framework */
1207                 if (mpt->m_options & MPTSAS_OPT_PM) {
1208                         (void) pm_idle_component(dip, 0);
1209                 }
1210 
1211                 return (DDI_SUCCESS);
1212 
1213         default:
1214                 return (DDI_FAILURE);
1215 
1216         }
1217 
1218         instance = ddi_get_instance(dip);
1219 
1220         /*
1221          * Allocate softc information.
1222          */
1223         if (ddi_soft_state_zalloc(mptsas3_state, instance) != DDI_SUCCESS) {
1224                 mptsas_log(NULL, CE_WARN,
1225                     "mptsas%d: cannot allocate soft state", instance);
1226                 goto fail;
1227         }
1228 
1229         mpt = ddi_get_soft_state(mptsas3_state, instance);
1230 
1231         if (mpt == NULL) {
1232                 mptsas_log(NULL, CE_WARN,
1233                     "mptsas%d: cannot get soft state", instance);
1234                 goto fail;
1235         }
1236 
1237         /* Indicate that we are 'sizeof (scsi_*(9S))' clean. */
1238         scsi_size_clean(dip);
1239 
1240         mpt->m_dip = dip;
1241         mpt->m_instance = instance;
1242 
1243         /* Make a per-instance copy of the structures */
1244         mpt->m_io_dma_attr = mptsas_dma_attrs64;
1245         if (mptsas_use_64bit_msgaddr) {
1246                 mpt->m_msg_dma_attr = mptsas_dma_attrs64;
1247         } else {
1248                 mpt->m_msg_dma_attr = mptsas_dma_attrs;
1249         }
1250         mpt->m_reg_acc_attr = mptsas_dev_attr;
1251         mpt->m_dev_acc_attr = mptsas_dev_attr;
1252 
1253         /*
1254          * Round down the arq sense buffer size to nearest 16 bytes.
1255          */
1256         mpt->m_req_sense_size = EXTCMDS_STATUS_SIZE;
1257 
1258         /*
1259          * Initialize FMA
1260          */
1261         mpt->m_fm_capabilities = ddi_getprop(DDI_DEV_T_ANY, mpt->m_dip,
1262             DDI_PROP_CANSLEEP | DDI_PROP_DONTPASS, "fm-capable",
1263             DDI_FM_EREPORT_CAPABLE | DDI_FM_ACCCHK_CAPABLE |
1264             DDI_FM_DMACHK_CAPABLE | DDI_FM_ERRCB_CAPABLE);
1265 
1266         mptsas_fm_init(mpt);
1267 
1268         if (mptsas_alloc_handshake_msg(mpt,
1269             sizeof (Mpi2SCSITaskManagementRequest_t)) == DDI_FAILURE) {
1270                 mptsas_log(mpt, CE_WARN, "cannot initialize handshake msg.");
1271                 goto fail;
1272         }
1273 
1274         /*
1275          * Setup configuration space
1276          */
1277         if (mptsas_config_space_init(mpt) == FALSE) {
1278                 mptsas_log(mpt, CE_WARN, "mptsas_config_space_init failed");


1292          */
1293         if ((mpt->m_event_taskq = ddi_taskq_create(dip, "mptsas_event_taskq",
1294             1, TASKQ_DEFAULTPRI, 0)) == NULL) {
1295                 mptsas_log(mpt, CE_NOTE, "ddi_taskq_create failed");
1296                 goto fail;
1297         }
1298         event_taskq_create++;
1299 
1300         /*
1301          * A taskq is created for dealing with dr events
1302          */
1303         if ((mpt->m_dr_taskq = ddi_taskq_create(dip,
1304             "mptsas_dr_taskq",
1305             1, TASKQ_DEFAULTPRI, 0)) == NULL) {
1306                 mptsas_log(mpt, CE_NOTE, "ddi_taskq_create for discovery "
1307                     "failed");
1308                 goto fail;
1309         }
1310         dr_taskq_create++;
1311 
1312         cv_init(&mpt->m_qthread_cv, NULL, CV_DRIVER, NULL);
1313         mutex_init(&mpt->m_qthread_mutex, NULL, MUTEX_DRIVER, NULL);
1314 
1315         i = ddi_prop_get_int(DDI_DEV_T_ANY, dip,
1316             0, "mptsas_enable_txwq_prop", NCPUS > 1);
1317         if (i) {
1318                 mpt->m_txwq_thread_n = NUM_TX_WAITQ;
1319                 mpt->m_txwq_enabled = FALSE;
1320                 if (ddi_prop_get_int(DDI_DEV_T_ANY, dip,
1321                     0, "mptsas_allow_txwq_jumping", 0)) {
1322                         mpt->m_txwq_allow_q_jumping = TRUE;
1323                 }
1324                 i = ddi_prop_get_int(DDI_DEV_T_ANY, dip,
1325                     0, "mptsas_txwq_threashold_prop", 80000);
1326                 mpt->m_txwq_thread_threshold = (uint16_t)i;
1327         } else {
1328                 mpt->m_txwq_thread_n = 0;
1329                 mpt->m_txwq_enabled = FALSE;
1330         }
1331 
1332         if (mpt->m_txwq_thread_n) {
1333                 mutex_enter(&mpt->m_qthread_mutex);
1334                 for (j = 0; j < NUM_TX_WAITQ; j++) {
1335                         mutex_init(&mpt->m_tx_waitq[j].txwq_mutex, NULL,
1336                             MUTEX_DRIVER,
1337                             NULL);
1338                         cv_init(&mpt->m_tx_waitq[j].txwq_cv, NULL, CV_DRIVER,
1339                             NULL);
1340                         cv_init(&mpt->m_tx_waitq[j].txwq_drain_cv, NULL,
1341                             CV_DRIVER, NULL);
1342                         mpt->m_tx_waitq[j].txwq_active = TRUE;
1343                         mpt->m_tx_waitq[j].txwq_draining = FALSE;
1344                         mpt->m_tx_waitq[j].txwq_cmdq = NULL;
1345                         mpt->m_tx_waitq[j].txwq_qtail =
1346                             &mpt->m_tx_waitq[j].txwq_cmdq;
1347                         mutex_enter(&mpt->m_tx_waitq[j].txwq_mutex);
1348                         mpt->m_tx_waitq[j].arg.mpt = mpt;
1349                         mpt->m_tx_waitq[j].arg.t = j;
1350                         mpt->m_tx_waitq[j].txwq_threadp =
1351                             thread_create(NULL, 0, mptsas_tx_waitq_thread,
1352                             &mpt->m_tx_waitq[j].arg,
1353                             0, &p0, TS_RUN, maxclsyspri - 10);
1354                         mutex_exit(&mpt->m_tx_waitq[j].txwq_mutex);
1355                 }
1356                 mutex_exit(&mpt->m_qthread_mutex);
1357                 txwq_thread_create++;
1358         }
1359 
1360         mpt->m_doneq_thread_threshold = ddi_prop_get_int(DDI_DEV_T_ANY, dip,
1361             0, "mptsas_doneq_thread_threshold_prop", 10);
1362         mpt->m_doneq_length_threshold = ddi_prop_get_int(DDI_DEV_T_ANY, dip,
1363             0, "mptsas_doneq_length_threshold_prop", 8);
1364         mpt->m_doneq_thread_n = ddi_prop_get_int(DDI_DEV_T_ANY, dip,
1365             0, "mptsas_doneq_thread_n_prop", min(NCPUS, 8));
1366 
1367         if (mpt->m_doneq_thread_n) {
1368                 mutex_enter(&mpt->m_qthread_mutex);



1369                 mpt->m_doneq_thread_id =
1370                     kmem_zalloc(sizeof (mptsas_doneq_thread_list_t)
1371                     * mpt->m_doneq_thread_n, KM_SLEEP);
1372 
1373                 for (j = 0; j < mpt->m_doneq_thread_n; j++) {
1374                         cv_init(&mpt->m_doneq_thread_id[j].cv, NULL,
1375                             CV_DRIVER, NULL);
1376                         mutex_init(&mpt->m_doneq_thread_id[j].mutex, NULL,
1377                             MUTEX_DRIVER, NULL);
1378                         mutex_enter(&mpt->m_doneq_thread_id[j].mutex);
1379                         mpt->m_doneq_thread_id[j].flag |=
1380                             MPTSAS_DONEQ_THREAD_ACTIVE;
1381                         mpt->m_doneq_thread_id[j].arg.mpt = mpt;
1382                         mpt->m_doneq_thread_id[j].arg.t = j;
1383                         mpt->m_doneq_thread_id[j].threadp =
1384                             thread_create(NULL, 0, mptsas_doneq_thread,
1385                             &mpt->m_doneq_thread_id[j].arg,
1386                             0, &p0, TS_RUN, maxclsyspri - 10);
1387                         mpt->m_doneq_thread_id[j].dlist.dl_tail =
1388                             &mpt->m_doneq_thread_id[j].dlist.dl_q;
1389                         mutex_exit(&mpt->m_doneq_thread_id[j].mutex);
1390                 }
1391                 mutex_exit(&mpt->m_qthread_mutex);
1392                 doneq_thread_create++;
1393         }
1394 
1395         /*
1396          * Disable hardware interrupt since we're not ready to
1397          * handle it yet.
1398          */
1399         MPTSAS_DISABLE_INTR(mpt);
1400 
1401         /*
1402          * Initialize mutex used in interrupt handler.
1403          * We don't support hi-level so the mutex's are all adaptive
1404          * and we don't want to register the interrupts until we get
1405          * the chip type information from _init_chip() below.
1406          * Otherwise we would use DDI_INTR_PRI(mpt->m_intr_pri)
1407          * rather than NULL in the mutex_init() calls.
1408          */
1409         mutex_init(&mpt->m_mutex, NULL, MUTEX_DRIVER, NULL);
1410         mutex_init(&mpt->m_passthru_mutex, NULL, MUTEX_DRIVER, NULL);


1411         for (i = 0; i < MPTSAS_MAX_PHYS; i++) {
1412                 mutex_init(&mpt->m_phy_info[i].smhba_info.phy_mutex,
1413                     NULL, MUTEX_DRIVER, NULL);

1414         }
1415 
1416         cv_init(&mpt->m_cv, NULL, CV_DRIVER, NULL);
1417         cv_init(&mpt->m_passthru_cv, NULL, CV_DRIVER, NULL);
1418         cv_init(&mpt->m_fw_cv, NULL, CV_DRIVER, NULL);
1419         cv_init(&mpt->m_config_cv, NULL, CV_DRIVER, NULL);
1420         cv_init(&mpt->m_fw_diag_cv, NULL, CV_DRIVER, NULL);
1421         mutex_init_done++;
1422 









1423         mutex_enter(&mpt->m_mutex);
1424         /*
1425          * Initialize power management component
1426          */
1427         if (mpt->m_options & MPTSAS_OPT_PM) {
1428                 if (mptsas_init_pm(mpt)) {
1429                         mutex_exit(&mpt->m_mutex);
1430                         mptsas_log(mpt, CE_WARN, "mptsas pm initialization "
1431                             "failed");
1432                         goto fail;
1433                 }
1434         }
1435 
1436         /*
1437          * Initialize chip using Message Unit Reset, if allowed
1438          */
1439         mpt->m_softstate |= MPTSAS_SS_MSG_UNIT_RESET;
1440         if (mptsas_init_chip(mpt, TRUE) == DDI_FAILURE) {
1441                 mutex_exit(&mpt->m_mutex);
1442                 mptsas_log(mpt, CE_WARN, "mptsas chip initialization failed");


1447          * Fill in the phy_info structure and get the base WWID
1448          */
1449         if (mptsas_get_manufacture_page5(mpt) == DDI_FAILURE) {
1450                 mptsas_log(mpt, CE_WARN,
1451                     "mptsas_get_manufacture_page5 failed!");
1452                 goto fail;
1453         }
1454 
1455         if (mptsas_get_sas_io_unit_page_hndshk(mpt)) {
1456                 mptsas_log(mpt, CE_WARN,
1457                     "mptsas_get_sas_io_unit_page_hndshk failed!");
1458                 goto fail;
1459         }
1460 
1461         if (mptsas_get_manufacture_page0(mpt) == DDI_FAILURE) {
1462                 mptsas_log(mpt, CE_WARN,
1463                     "mptsas_get_manufacture_page0 failed!");
1464                 goto fail;
1465         }
1466 
1467         /*
1468          * If we only have one interrupt the default for doneq_thread_threshold
1469          * should be 0 so that all completion processing goes to the threads.
1470          * Only change it if it wasn't set from .conf file.
1471          */
1472         if (mpt->m_doneq_thread_n != 0 &&
1473             ddi_prop_exists(DDI_DEV_T_ANY, dip,
1474             0, "mptsas_doneq_length_threshold_prop") == 0 &&
1475             mpt->m_intr_cnt == 1) {
1476                 mpt->m_doneq_length_threshold = 0;
1477         }
1478 
1479 
1480         mutex_exit(&mpt->m_mutex);
1481 
1482         /*
1483          * Register the iport for multiple port HBA
1484          */
1485         mptsas_iport_register(mpt);
1486 
1487         /*
1488          * initialize SCSI HBA transport structure
1489          */
1490         if (mptsas_hba_setup(mpt) == FALSE)
1491                 goto fail;
1492         hba_attach_setup++;
1493 
1494         if (mptsas_smp_setup(mpt) == FALSE)
1495                 goto fail;
1496         smp_attach_setup++;
1497 
1498         if (mptsas_cache_create(mpt) == FALSE)
1499                 goto fail;
1500 
1501         mpt->m_scsi_reset_delay      = ddi_prop_get_int(DDI_DEV_T_ANY,
1502             dip, 0, "scsi-reset-delay", SCSI_DEFAULT_RESET_DELAY);
1503         if (mpt->m_scsi_reset_delay == 0) {
1504                 mptsas_log(mpt, CE_NOTE,
1505                     "scsi_reset_delay of 0 is not recommended,"
1506                     " resetting to SCSI_DEFAULT_RESET_DELAY\n");
1507                 mpt->m_scsi_reset_delay = SCSI_DEFAULT_RESET_DELAY;
1508         }
1509 
1510         /*
1511          * Initialize the wait and done FIFO queue
1512          */
1513         mpt->m_dlist.dl_tail = &mpt->m_dlist.dl_q;
1514         mpt->m_waitqtail = &mpt->m_waitq;


1515 
1516         /*
1517          * ioc cmd queue initialize
1518          */
1519         mpt->m_ioc_event_cmdtail = &mpt->m_ioc_event_cmdq;
1520         mpt->m_dev_handle = 0xFFFF;
1521 
1522         MPTSAS_ENABLE_INTR(mpt);
1523 
1524         /*
1525          * enable event notification
1526          */
1527         mutex_enter(&mpt->m_mutex);
1528         if (mptsas_ioc_enable_event_notification(mpt)) {
1529                 mutex_exit(&mpt->m_mutex);
1530                 goto fail;
1531         }
1532         mutex_exit(&mpt->m_mutex);
1533 
1534         /*
1535          * used for mptsas_watch
1536          */
1537         mptsas_list_add(mpt);
1538 
1539         mutex_enter(&mptsas_global_mutex);
1540         if (mptsas_timeouts_enabled == 0) {
1541                 mptsas_scsi_watchdog_tick = ddi_prop_get_int(DDI_DEV_T_ANY,
1542                     dip, 0, "scsi-watchdog-tick", DEFAULT_WD_TICK);
1543 
1544                 mptsas_tick = mptsas_scsi_watchdog_tick *
1545                     drv_usectohz((clock_t)1000000);
1546 
1547                 mptsas_timeout_id = timeout(mptsas_watch, NULL, mptsas_tick);
1548                 mptsas_timeouts_enabled = 1;
1549         }
1550         mutex_exit(&mptsas_global_mutex);
1551         added_watchdog++;
1552 
1553         /*
1554          * Initialize PHY info for smhba.
1555          * This requires watchdog to be enabled otherwise if interrupts
1556          * don't work the system will hang.
1557          */
1558         if (mptsas_smhba_setup(mpt)) {
1559                 mptsas_log(mpt, CE_WARN, "mptsas phy initialization "
1560                     "failed");
1561                 goto fail;
1562         }
1563 
1564         /* Check all dma handles allocated in attach */
1565         if ((mptsas_check_dma_handle(mpt->m_dma_req_frame_hdl)
1566             != DDI_SUCCESS) ||
1567             (mptsas_check_dma_handle(mpt->m_dma_req_sense_hdl)
1568             != DDI_SUCCESS) ||
1569             (mptsas_check_dma_handle(mpt->m_dma_reply_frame_hdl)
1570             != DDI_SUCCESS) ||
1571             (mptsas_check_dma_handle(mpt->m_dma_free_queue_hdl)
1572             != DDI_SUCCESS) ||
1573             (mptsas_check_dma_handle(mpt->m_dma_post_queue_hdl)
1574             != DDI_SUCCESS) ||
1575             (mptsas_check_dma_handle(mpt->m_hshk_dma_hdl)
1576             != DDI_SUCCESS)) {
1577                 goto fail;
1578         }
1579 
1580         /* Check all acc handles allocated in attach */
1581         if ((mptsas_check_acc_handle(mpt->m_datap) != DDI_SUCCESS) ||
1582             (mptsas_check_acc_handle(mpt->m_acc_req_frame_hdl)
1583             != DDI_SUCCESS) ||
1584             (mptsas_check_acc_handle(mpt->m_acc_req_sense_hdl)
1585             != DDI_SUCCESS) ||
1586             (mptsas_check_acc_handle(mpt->m_acc_reply_frame_hdl)
1587             != DDI_SUCCESS) ||
1588             (mptsas_check_acc_handle(mpt->m_acc_free_queue_hdl)
1589             != DDI_SUCCESS) ||
1590             (mptsas_check_acc_handle(mpt->m_acc_post_queue_hdl)
1591             != DDI_SUCCESS) ||
1592             (mptsas_check_acc_handle(mpt->m_hshk_acc_hdl)
1593             != DDI_SUCCESS) ||
1594             (mptsas_check_acc_handle(mpt->m_config_handle)
1595             != DDI_SUCCESS)) {
1596                 goto fail;
1597         }
1598 
1599         /*
1600          * After this point, we are not going to fail the attach.
1601          */

















1602 
1603         /* Print message of HBA present */
1604         ddi_report_dev(dip);
1605 
1606         /* report idle status to pm framework */
1607         if (mpt->m_options & MPTSAS_OPT_PM) {
1608                 (void) pm_idle_component(dip, 0);
1609         }
1610 
1611         return (DDI_SUCCESS);
1612 
1613 fail:
1614         mptsas_log(mpt, CE_WARN, "attach failed");
1615         mptsas_fm_ereport(mpt, DDI_FM_DEVICE_NO_RESPONSE);
1616         ddi_fm_service_impact(mpt->m_dip, DDI_SERVICE_LOST);
1617         if (mpt) {
1618                 /* deallocate in reverse order */
1619                 if (added_watchdog) {
1620                         mptsas_list_del(mpt);
1621                         mutex_enter(&mptsas_global_mutex);
1622 
1623                         if (mptsas_timeout_id && (mptsas_head == NULL)) {
1624                                 timeout_id_t tid = mptsas_timeout_id;
1625                                 mptsas_timeouts_enabled = 0;
1626                                 mptsas_timeout_id = 0;
1627                                 mutex_exit(&mptsas_global_mutex);
1628                                 (void) untimeout(tid);
1629                                 mutex_enter(&mptsas_global_mutex);
1630                         }
1631                         mutex_exit(&mptsas_global_mutex);
1632                 }
1633 
1634                 mptsas_cache_destroy(mpt);
1635 
1636                 if (smp_attach_setup) {
1637                         mptsas_smp_teardown(mpt);
1638                 }
1639                 if (hba_attach_setup) {
1640                         mptsas_hba_teardown(mpt);
1641                 }
1642 
1643                 if (mpt->m_targets)
1644                         refhash_destroy(mpt->m_targets);
1645                 if (mpt->m_smp_targets)
1646                         refhash_destroy(mpt->m_smp_targets);
1647 
1648                 if (mpt->m_active) {
1649                         mptsas_free_active_slots(mpt);
1650                 }
1651                 if (mpt->m_intr_cnt) {
1652                         mptsas_unregister_intrs(mpt);
1653                 }
1654 
1655                 if (doneq_thread_create) {
1656                         mutex_enter(&mpt->m_qthread_mutex);
1657                         q_thread_num = mpt->m_doneq_thread_n;
1658                         for (j = 0; j < q_thread_num; j++) {
1659                                 mutex_enter(&mpt->m_doneq_thread_id[j].mutex);
1660                                 mpt->m_doneq_thread_id[j].flag &=
1661                                     (~MPTSAS_DONEQ_THREAD_ACTIVE);
1662                                 cv_signal(&mpt->m_doneq_thread_id[j].cv);
1663                                 mutex_exit(&mpt->m_doneq_thread_id[j].mutex);
1664                         }
1665                         while (mpt->m_doneq_thread_n) {
1666                                 cv_wait(&mpt->m_qthread_cv,
1667                                     &mpt->m_qthread_mutex);
1668                         }
1669                         for (j = 0; j < q_thread_num; j++) {
1670                                 cv_destroy(&mpt->m_doneq_thread_id[j].cv);
1671                                 mutex_destroy(&mpt->m_doneq_thread_id[j].mutex);
1672                         }
1673                         kmem_free(mpt->m_doneq_thread_id,
1674                             sizeof (mptsas_doneq_thread_list_t)
1675                             * q_thread_num);
1676                         mutex_exit(&mpt->m_qthread_mutex);
1677                 }
1678                 if (txwq_thread_create) {
1679                         mutex_enter(&mpt->m_qthread_mutex);
1680                         q_thread_num = mpt->m_txwq_thread_n;
1681                         for (j = 0; j < q_thread_num; j++) {
1682                                 mutex_enter(&mpt->m_tx_waitq[j].txwq_mutex);
1683                                 mpt->m_tx_waitq[j].txwq_active = FALSE;
1684                                 cv_signal(&mpt->m_tx_waitq[j].txwq_cv);
1685                                 mutex_exit(&mpt->m_tx_waitq[j].txwq_mutex);
1686                         }
1687                         while (mpt->m_txwq_thread_n) {
1688                                 cv_wait(&mpt->m_qthread_cv,
1689                                     &mpt->m_qthread_mutex);
1690                         }
1691                         for (j = 0; j < q_thread_num; j++) {
1692                                 cv_destroy(&mpt->m_tx_waitq[j].txwq_cv);
1693                                 cv_destroy(&mpt->m_tx_waitq[j].txwq_drain_cv);
1694                                 mutex_destroy(&mpt->m_tx_waitq[j].txwq_mutex);
1695                         }
1696                 }
1697                 if (event_taskq_create) {
1698                         ddi_taskq_destroy(mpt->m_event_taskq);
1699                 }
1700                 if (dr_taskq_create) {
1701                         ddi_taskq_destroy(mpt->m_dr_taskq);
1702                 }
1703                 if (mutex_init_done) {
1704                         mutex_destroy(&mpt->m_qthread_mutex);
1705                         mutex_destroy(&mpt->m_passthru_mutex);
1706                         mutex_destroy(&mpt->m_mutex);
1707                         for (i = 0; i < MPTSAS_MAX_PHYS; i++) {
1708                                 mutex_destroy(
1709                                     &mpt->m_phy_info[i].smhba_info.phy_mutex);
1710                         }
1711                         cv_destroy(&mpt->m_qthread_cv);
1712                         cv_destroy(&mpt->m_cv);
1713                         cv_destroy(&mpt->m_passthru_cv);
1714                         cv_destroy(&mpt->m_fw_cv);
1715                         cv_destroy(&mpt->m_config_cv);
1716                         cv_destroy(&mpt->m_fw_diag_cv);
1717                 }
1718 
1719                 if (map_setup) {
1720                         mptsas_cfg_fini(mpt);
1721                 }
1722                 if (config_setup) {
1723                         mptsas_config_space_fini(mpt);
1724                 }
1725                 mptsas_free_handshake_msg(mpt);
1726                 mptsas_hba_fini(mpt);
1727 
1728                 mptsas_fm_fini(mpt);
1729                 ddi_soft_state_free(mptsas3_state, instance);
1730                 ddi_prop_remove_all(dip);
1731         }
1732         return (DDI_FAILURE);
1733 }
1734 
1735 static int
1736 mptsas_suspend(dev_info_t *devi)
1737 {
1738         mptsas_t        *mpt, *g;
1739         scsi_hba_tran_t *tran;
1740 
1741         if (scsi_hba_iport_unit_address(devi)) {
1742                 return (DDI_SUCCESS);
1743         }
1744 
1745         if ((tran = ddi_get_driver_private(devi)) == NULL)
1746                 return (DDI_SUCCESS);
1747 
1748         mpt = TRAN2MPT(tran);
1749         if (!mpt) {


1923                 return (mptsas_do_detach(devi));
1924 
1925         case DDI_SUSPEND:
1926                 return (mptsas_suspend(devi));
1927 
1928         default:
1929                 return (DDI_FAILURE);
1930         }
1931         /* NOTREACHED */
1932 }
1933 
1934 static int
1935 mptsas_do_detach(dev_info_t *dip)
1936 {
1937         mptsas_t        *mpt;
1938         scsi_hba_tran_t *tran;
1939         int             circ = 0;
1940         int             circ1 = 0;
1941         mdi_pathinfo_t  *pip = NULL;
1942         int             i;
1943         int             q_thread_num = 0;
1944 
1945         NDBG0(("mptsas_do_detach: dip=0x%p", (void *)dip));
1946 
1947         if ((tran = ndi_flavorv_get(dip, SCSA_FLAVOR_SCSI_DEVICE)) == NULL)
1948                 return (DDI_FAILURE);
1949 
1950         mpt = TRAN2MPT(tran);
1951         if (!mpt) {
1952                 return (DDI_FAILURE);
1953         }
1954         /*
1955          * Still have pathinfo child, should not detach mpt driver
1956          */
1957         if (scsi_hba_iport_unit_address(dip)) {
1958                 if (mpt->m_mpxio_enable) {
1959                         /*
1960                          * MPxIO enabled for the iport
1961                          */
1962                         ndi_devi_enter(scsi_vhci_dip, &circ1);
1963                         ndi_devi_enter(dip, &circ);


1971                                     "outstanding path info"));
1972                                 return (DDI_FAILURE);
1973                         }
1974                         ndi_devi_exit(dip, circ);
1975                         ndi_devi_exit(scsi_vhci_dip, circ1);
1976                         (void) mdi_phci_unregister(dip, 0);
1977                 }
1978 
1979                 ddi_prop_remove_all(dip);
1980 
1981                 return (DDI_SUCCESS);
1982         }
1983 
1984         /* Make sure power level is D0 before accessing registers */
1985         if (mpt->m_options & MPTSAS_OPT_PM) {
1986                 (void) pm_busy_component(dip, 0);
1987                 if (mpt->m_power_level != PM_LEVEL_D0) {
1988                         if (pm_raise_power(dip, 0, PM_LEVEL_D0) !=
1989                             DDI_SUCCESS) {
1990                                 mptsas_log(mpt, CE_WARN,
1991                                     "mptsas3%d: Raise power request failed.",
1992                                     mpt->m_instance);
1993                                 (void) pm_idle_component(dip, 0);
1994                                 return (DDI_FAILURE);
1995                         }
1996                 }
1997         }
1998 
1999         /*
2000          * Send RAID action system shutdown to sync IR.  After action, send a
2001          * Message Unit Reset. Since after that DMA resource will be freed,
2002          * set ioc to READY state will avoid HBA initiated DMA operation.
2003          */
2004         mutex_enter(&mpt->m_mutex);
2005         MPTSAS_DISABLE_INTR(mpt);
2006         mptsas_raid_action_system_shutdown(mpt);
2007         mpt->m_softstate |= MPTSAS_SS_MSG_UNIT_RESET;
2008         (void) mptsas_ioc_reset(mpt, FALSE);
2009         mutex_exit(&mpt->m_mutex);
2010         mptsas_rem_intrs(mpt);
2011         ddi_taskq_destroy(mpt->m_event_taskq);
2012         ddi_taskq_destroy(mpt->m_dr_taskq);
2013 
2014         if (mpt->m_doneq_thread_n) {
2015                 mutex_enter(&mpt->m_qthread_mutex);
2016                 q_thread_num = mpt->m_doneq_thread_n;
2017                 for (i = 0; i < mpt->m_doneq_thread_n; i++) {
2018                         mutex_enter(&mpt->m_doneq_thread_id[i].mutex);
2019                         mpt->m_doneq_thread_id[i].flag &=
2020                             (~MPTSAS_DONEQ_THREAD_ACTIVE);
2021                         cv_signal(&mpt->m_doneq_thread_id[i].cv);
2022                         mutex_exit(&mpt->m_doneq_thread_id[i].mutex);
2023                 }
2024                 while (mpt->m_doneq_thread_n) {
2025                         cv_wait(&mpt->m_qthread_cv,
2026                             &mpt->m_qthread_mutex);
2027                 }
2028                 for (i = 0;  i < q_thread_num; i++) {
2029                         cv_destroy(&mpt->m_doneq_thread_id[i].cv);
2030                         mutex_destroy(&mpt->m_doneq_thread_id[i].mutex);
2031                 }
2032                 kmem_free(mpt->m_doneq_thread_id,
2033                     sizeof (mptsas_doneq_thread_list_t)
2034                     * q_thread_num);
2035                 mutex_exit(&mpt->m_qthread_mutex);
2036         }
2037         if (mpt->m_txwq_thread_n) {
2038                 mutex_enter(&mpt->m_qthread_mutex);
2039                 q_thread_num = mpt->m_txwq_thread_n;
2040                 for (i = 0; i < q_thread_num; i++) {
2041                         mutex_enter(&mpt->m_tx_waitq[i].txwq_mutex);
2042                         mpt->m_tx_waitq[i].txwq_active = FALSE;
2043                         cv_signal(&mpt->m_tx_waitq[i].txwq_cv);
2044                         mutex_exit(&mpt->m_tx_waitq[i].txwq_mutex);
2045                 }
2046                 while (mpt->m_txwq_thread_n) {
2047                         cv_wait(&mpt->m_qthread_cv,
2048                             &mpt->m_qthread_mutex);
2049                 }
2050                 for (i = 0; i < q_thread_num; i++) {
2051                         cv_destroy(&mpt->m_tx_waitq[i].txwq_cv);
2052                         cv_destroy(&mpt->m_tx_waitq[i].txwq_drain_cv);
2053                         mutex_destroy(&mpt->m_tx_waitq[i].txwq_mutex);
2054                 }
2055         }
2056 
2057         scsi_hba_reset_notify_tear_down(mpt->m_reset_notify_listf);
2058 
2059         mptsas_list_del(mpt);
2060 
2061         /*
2062          * Cancel timeout threads for this mpt
2063          */
2064         mutex_enter(&mpt->m_mutex);
2065         if (mpt->m_quiesce_timeid) {
2066                 timeout_id_t tid = mpt->m_quiesce_timeid;
2067                 mpt->m_quiesce_timeid = 0;
2068                 mutex_exit(&mpt->m_mutex);
2069                 (void) untimeout(tid);
2070                 mutex_enter(&mpt->m_mutex);
2071         }
2072 
2073         if (mpt->m_restart_cmd_timeid) {
2074                 timeout_id_t tid = mpt->m_restart_cmd_timeid;


2115 
2116         mptsas_destroy_hashes(mpt);
2117 
2118         /*
2119          * Delete nt_active.
2120          */
2121         mutex_enter(&mpt->m_mutex);
2122         mptsas_free_active_slots(mpt);
2123         mutex_exit(&mpt->m_mutex);
2124 
2125         /* deallocate everything that was allocated in mptsas_attach */
2126         mptsas_cache_destroy(mpt);
2127 
2128         mptsas_hba_fini(mpt);
2129         mptsas_cfg_fini(mpt);
2130 
2131         /* Lower the power informing PM Framework */
2132         if (mpt->m_options & MPTSAS_OPT_PM) {
2133                 if (pm_lower_power(dip, 0, PM_LEVEL_D3) != DDI_SUCCESS)
2134                         mptsas_log(mpt, CE_WARN,
2135                             "!mptsas3%d: Lower power request failed "
2136                             "during detach, ignoring.",
2137                             mpt->m_instance);
2138         }
2139 
2140         mutex_destroy(&mpt->m_qthread_mutex);
2141         mutex_destroy(&mpt->m_passthru_mutex);
2142         mutex_destroy(&mpt->m_mutex);
2143         for (i = 0; i < MPTSAS_MAX_PHYS; i++) {
2144                 mutex_destroy(&mpt->m_phy_info[i].smhba_info.phy_mutex);
2145         }
2146         cv_destroy(&mpt->m_qthread_cv);
2147         cv_destroy(&mpt->m_cv);
2148         cv_destroy(&mpt->m_passthru_cv);
2149         cv_destroy(&mpt->m_fw_cv);
2150         cv_destroy(&mpt->m_config_cv);
2151         cv_destroy(&mpt->m_fw_diag_cv);
2152 
2153 
2154         mptsas_smp_teardown(mpt);
2155         mptsas_hba_teardown(mpt);
2156 
2157         mptsas_config_space_fini(mpt);
2158 
2159         mptsas_free_handshake_msg(mpt);
2160 
2161         mptsas_fm_fini(mpt);
2162         ddi_soft_state_free(mptsas3_state, ddi_get_instance(dip));
2163         ddi_prop_remove_all(dip);
2164 
2165         return (DDI_SUCCESS);
2166 }
2167 
2168 static void
2169 mptsas_list_add(mptsas_t *mpt)
2170 {
2171         rw_enter(&mptsas_global_rwlock, RW_WRITER);
2172 
2173         if (mptsas_head == NULL) {
2174                 mptsas_head = mpt;
2175         } else {
2176                 mptsas_tail->m_next = mpt;
2177         }
2178         mptsas_tail = mpt;
2179         rw_exit(&mptsas_global_rwlock);
2180 }
2181 
2182 static void


2195                                 m->m_next = mpt->m_next;
2196                                 break;
2197                         }
2198                 }
2199                 if (m == NULL) {
2200                         mptsas_log(mpt, CE_PANIC, "Not in softc list!");
2201                 }
2202         }
2203 
2204         if (mptsas_tail == mpt) {
2205                 mptsas_tail = m;
2206         }
2207         rw_exit(&mptsas_global_rwlock);
2208 }
2209 
2210 static int
2211 mptsas_alloc_handshake_msg(mptsas_t *mpt, size_t alloc_size)
2212 {
2213         ddi_dma_attr_t  task_dma_attrs;
2214 
2215         mpt->m_hshk_dma_size = 0;
2216         task_dma_attrs = mpt->m_msg_dma_attr;
2217         task_dma_attrs.dma_attr_sgllen = 1;
2218         task_dma_attrs.dma_attr_granular = (uint32_t)(alloc_size);
2219 
2220         /* allocate Task Management ddi_dma resources */
2221         if (mptsas_dma_addr_create(mpt, task_dma_attrs,
2222             &mpt->m_hshk_dma_hdl, &mpt->m_hshk_acc_hdl, &mpt->m_hshk_memp,
2223             alloc_size, NULL) == FALSE) {
2224                 return (DDI_FAILURE);
2225         }
2226         mpt->m_hshk_dma_size = alloc_size;
2227 
2228         return (DDI_SUCCESS);
2229 }
2230 
2231 static void
2232 mptsas_free_handshake_msg(mptsas_t *mpt)
2233 {
2234         if (mpt->m_hshk_dma_size == 0)
2235                 return;
2236         mptsas_dma_addr_destroy(&mpt->m_hshk_dma_hdl, &mpt->m_hshk_acc_hdl);
2237         mpt->m_hshk_dma_size = 0;
2238 }
2239 
2240 static int
2241 mptsas_hba_setup(mptsas_t *mpt)
2242 {
2243         scsi_hba_tran_t         *hba_tran;
2244         int                     tran_flags;
2245 
2246         /* Allocate a transport structure */
2247         hba_tran = mpt->m_tran = scsi_hba_tran_alloc(mpt->m_dip,
2248             SCSI_HBA_CANSLEEP);
2249         ASSERT(mpt->m_tran != NULL);
2250 
2251         hba_tran->tran_hba_private   = mpt;
2252         hba_tran->tran_tgt_private   = NULL;
2253 
2254         hba_tran->tran_tgt_init              = mptsas_scsi_tgt_init;
2255         hba_tran->tran_tgt_free              = mptsas_scsi_tgt_free;


2393 static void
2394 mptsas_smp_teardown(mptsas_t *mpt)
2395 {
2396         (void) smp_hba_detach(mpt->m_dip);
2397         if (mpt->m_smptran != NULL) {
2398                 smp_hba_tran_free(mpt->m_smptran);
2399                 mpt->m_smptran = NULL;
2400         }
2401         mpt->m_smp_devhdl = 0;
2402 }
2403 
2404 static int
2405 mptsas_cache_create(mptsas_t *mpt)
2406 {
2407         int instance = mpt->m_instance;
2408         char buf[64];
2409 
2410         /*
2411          * create kmem cache for packets
2412          */
2413         (void) sprintf(buf, "mptsas3%d_cache", instance);
2414         mpt->m_kmem_cache = kmem_cache_create(buf,
2415             sizeof (struct mptsas_cmd) + scsi_pkt_size(), 16,
2416             mptsas_kmem_cache_constructor, mptsas_kmem_cache_destructor,
2417             NULL, (void *)mpt, NULL, 0);
2418 
2419         if (mpt->m_kmem_cache == NULL) {
2420                 mptsas_log(mpt, CE_WARN, "creating kmem cache failed");
2421                 return (FALSE);
2422         }
2423 
2424         /*
2425          * create kmem cache for extra SGL frames if SGL cannot
2426          * be accomodated into main request frame.
2427          */
2428         (void) sprintf(buf, "mptsas3%d_cache_frames", instance);
2429         mpt->m_cache_frames = kmem_cache_create(buf,
2430             sizeof (mptsas_cache_frames_t), 16,
2431             mptsas_cache_frames_constructor, mptsas_cache_frames_destructor,
2432             NULL, (void *)mpt, NULL, 0);
2433 
2434         if (mpt->m_cache_frames == NULL) {
2435                 mptsas_log(mpt, CE_WARN, "creating cache for frames failed");
2436                 return (FALSE);
2437         }
2438 
2439         return (TRUE);
2440 }
2441 
2442 static void
2443 mptsas_cache_destroy(mptsas_t *mpt)
2444 {
2445         /* deallocate in reverse order */
2446         if (mpt->m_cache_frames) {
2447                 kmem_cache_destroy(mpt->m_cache_frames);
2448                 mpt->m_cache_frames = NULL;
2449         }
2450         if (mpt->m_kmem_cache) {
2451                 kmem_cache_destroy(mpt->m_kmem_cache);
2452                 mpt->m_kmem_cache = NULL;
2453         }
2454 }
2455 
2456 static int
2457 mptsas_power(dev_info_t *dip, int component, int level)
2458 {
2459 #ifndef __lock_lint
2460         _NOTE(ARGUNUSED(component))
2461 #endif
2462         mptsas_t        *mpt;
2463         int             rval = DDI_SUCCESS;
2464         int             polls = 0;
2465         uint32_t        ioc_status;
2466 
2467         if (scsi_hba_iport_unit_address(dip) != 0)
2468                 return (DDI_SUCCESS);
2469 
2470         mpt = ddi_get_soft_state(mptsas3_state, ddi_get_instance(dip));
2471         if (mpt == NULL) {
2472                 return (DDI_FAILURE);
2473         }
2474 
2475         mutex_enter(&mpt->m_mutex);
2476 
2477         /*
2478          * If the device is busy, don't lower its power level
2479          */
2480         if (mpt->m_busy && (mpt->m_power_level > level)) {
2481                 mutex_exit(&mpt->m_mutex);
2482                 return (DDI_FAILURE);
2483         }
2484         switch (level) {
2485         case PM_LEVEL_D0:
2486                 NDBG11(("mptsas3%d: turning power ON.", mpt->m_instance));
2487                 MPTSAS_POWER_ON(mpt);
2488                 /*
2489                  * Wait up to 30 seconds for IOC to come out of reset.
2490                  */
2491                 while (((ioc_status = ddi_get32(mpt->m_datap,
2492                     &mpt->m_reg->Doorbell)) &
2493                     MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_RESET) {
2494                         if (polls++ > 3000) {
2495                                 break;
2496                         }
2497                         delay(drv_usectohz(10000));
2498                 }
2499                 /*
2500                  * If IOC is not in operational state, try to hard reset it.
2501                  */
2502                 if ((ioc_status & MPI2_IOC_STATE_MASK) !=
2503                     MPI2_IOC_STATE_OPERATIONAL) {
2504                         mpt->m_softstate &= ~MPTSAS_SS_MSG_UNIT_RESET;
2505                         if (mptsas_restart_ioc(mpt) == DDI_FAILURE) {
2506                                 mptsas_log(mpt, CE_WARN,
2507                                     "mptsas_power: hard reset failed");
2508                                 mutex_exit(&mpt->m_mutex);
2509                                 return (DDI_FAILURE);
2510                         }
2511                 }
2512                 mpt->m_power_level = PM_LEVEL_D0;
2513                 break;
2514         case PM_LEVEL_D3:
2515                 NDBG11(("mptsas3%d: turning power OFF.", mpt->m_instance));
2516                 MPTSAS_POWER_OFF(mpt);
2517                 break;
2518         default:
2519                 mptsas_log(mpt, CE_WARN, "mptsas3%d: unknown power level <%x>.",
2520                     mpt->m_instance, level);
2521                 rval = DDI_FAILURE;
2522                 break;
2523         }
2524         mutex_exit(&mpt->m_mutex);
2525         return (rval);
2526 }
2527 
2528 /*
2529  * Initialize configuration space and figure out which
2530  * chip and revison of the chip the mpt driver is using.
2531  */
2532 static int
2533 mptsas_config_space_init(mptsas_t *mpt)
2534 {
2535         NDBG0(("mptsas_config_space_init"));
2536 
2537         if (mpt->m_config_handle != NULL)
2538                 return (TRUE);
2539 


2677                 ddi_fm_service_impact(mpt->m_dip, DDI_SERVICE_UNAFFECTED);
2678                 rval = DDI_FAILURE;
2679         }
2680 
2681         mptsas_dma_addr_destroy(&dma_handle, &accessp);
2682         return (rval);
2683 
2684 }
2685 
2686 static int
2687 mptsas_alloc_request_frames(mptsas_t *mpt)
2688 {
2689         ddi_dma_attr_t          frame_dma_attrs;
2690         caddr_t                 memp;
2691         ddi_dma_cookie_t        cookie;
2692         size_t                  mem_size;
2693 
2694         /*
2695          * re-alloc when it has already alloced
2696          */
2697         if (mpt->m_dma_flags & MPTSAS_REQ_FRAME) {
2698                 mptsas_dma_addr_destroy(&mpt->m_dma_req_frame_hdl,
2699                     &mpt->m_acc_req_frame_hdl);
2700                 mpt->m_dma_flags &= ~MPTSAS_REQ_FRAME;
2701         }
2702 
2703         /*
2704          * The size of the request frame pool is:
2705          *   Number of Request Frames * Request Frame Size
2706          */
2707         mem_size = mpt->m_max_requests * mpt->m_req_frame_size;
2708 
2709         /*
2710          * set the DMA attributes.  System Request Message Frames must be
2711          * aligned on a 16-byte boundry.
2712          */
2713         frame_dma_attrs = mpt->m_msg_dma_attr;
2714         frame_dma_attrs.dma_attr_align = 16;
2715         frame_dma_attrs.dma_attr_sgllen = 1;
2716 
2717         /*
2718          * allocate the request frame pool.
2719          */
2720         if (mptsas_dma_addr_create(mpt, frame_dma_attrs,
2721             &mpt->m_dma_req_frame_hdl, &mpt->m_acc_req_frame_hdl, &memp,
2722             mem_size, &cookie) == FALSE) {
2723                 return (DDI_FAILURE);
2724         }
2725 
2726         /*
2727          * Store the request frame memory address.  This chip uses this
2728          * address to dma to and from the driver's frame.  The second
2729          * address is the address mpt uses to fill in the frame.
2730          */
2731         mpt->m_req_frame_dma_addr = cookie.dmac_laddress;
2732         mpt->m_req_frame = memp;
2733 
2734         /*
2735          * Clear the request frame pool.
2736          */
2737         bzero(mpt->m_req_frame, mem_size);
2738 
2739         mpt->m_dma_flags |= MPTSAS_REQ_FRAME;
2740         return (DDI_SUCCESS);
2741 }
2742 
2743 static int
2744 mptsas_alloc_sense_bufs(mptsas_t *mpt)
2745 {
2746         ddi_dma_attr_t          sense_dma_attrs;
2747         caddr_t                 memp;
2748         ddi_dma_cookie_t        cookie;
2749         size_t                  mem_size;
2750         int                     num_extrqsense_bufs;
2751 
2752         /*
2753          * re-alloc when it has already alloced
2754          */
2755         if (mpt->m_dma_flags & MPTSAS_REQ_SENSE) {
2756                 rmfreemap(mpt->m_erqsense_map);
2757                 mptsas_dma_addr_destroy(&mpt->m_dma_req_sense_hdl,
2758                     &mpt->m_acc_req_sense_hdl);
2759                 mpt->m_dma_flags &= ~MPTSAS_REQ_SENSE;
2760         }
2761 
2762         /*
2763          * The size of the request sense pool is:
2764          *   (Number of Request Frames - 2 ) * Request Sense Size +
2765          *   extra memory for extended sense requests.
2766          */
2767         mem_size = ((mpt->m_max_requests - 2) * mpt->m_req_sense_size) +
2768             mptsas_extreq_sense_bufsize;
2769 
2770         /*
2771          * set the DMA attributes.  ARQ buffers
2772          * aligned on a 16-byte boundry.
2773          */
2774         sense_dma_attrs = mpt->m_msg_dma_attr;
2775         sense_dma_attrs.dma_attr_align = 16;
2776         sense_dma_attrs.dma_attr_sgllen = 1;
2777 
2778         /*
2779          * allocate the request sense buffer pool.
2780          */
2781         if (mptsas_dma_addr_create(mpt, sense_dma_attrs,
2782             &mpt->m_dma_req_sense_hdl, &mpt->m_acc_req_sense_hdl, &memp,
2783             mem_size, &cookie) == FALSE) {
2784                 return (DDI_FAILURE);
2785         }
2786 
2787         /*
2788          * Store the request sense base memory address.  This chip uses this
2789          * address to dma the request sense data.  The second
2790          * address is the address mpt uses to access the data.
2791          * The third is the base for the extended rqsense buffers.
2792          */
2793         mpt->m_req_sense_dma_addr = cookie.dmac_laddress;
2794         mpt->m_req_sense = memp;
2795         memp += (mpt->m_max_requests - 2) * mpt->m_req_sense_size;
2796         mpt->m_extreq_sense = memp;
2797 
2798         /*
2799          * The extra memory is divided up into multiples of the base
2800          * buffer size in order to allocate via rmalloc().
2801          * Note that the rmallocmap cannot start at zero!
2802          */
2803         num_extrqsense_bufs = mptsas_extreq_sense_bufsize /
2804             mpt->m_req_sense_size;
2805         mpt->m_erqsense_map = rmallocmap_wait(num_extrqsense_bufs);
2806         rmfree(mpt->m_erqsense_map, num_extrqsense_bufs, 1);
2807 
2808         /*
2809          * Clear the pool.
2810          */
2811         bzero(mpt->m_req_sense, mem_size);
2812 
2813         mpt->m_dma_flags |= MPTSAS_REQ_SENSE;
2814         return (DDI_SUCCESS);
2815 }
2816 
2817 static int
2818 mptsas_alloc_reply_frames(mptsas_t *mpt)
2819 {
2820         ddi_dma_attr_t          frame_dma_attrs;
2821         caddr_t                 memp;
2822         ddi_dma_cookie_t        cookie;
2823         size_t                  mem_size;
2824 
2825         /*
2826          * re-alloc when it has already alloced
2827          */
2828         if (mpt->m_dma_flags & MPTSAS_REPLY_FRAME) {
2829                 mptsas_dma_addr_destroy(&mpt->m_dma_reply_frame_hdl,
2830                     &mpt->m_acc_reply_frame_hdl);
2831                 mpt->m_dma_flags &= ~MPTSAS_REPLY_FRAME;
2832         }
2833 
2834         /*
2835          * The size of the reply frame pool is:
2836          *   Number of Reply Frames * Reply Frame Size
2837          */
2838         mem_size = mpt->m_max_replies * mpt->m_reply_frame_size;
2839 
2840         /*
2841          * set the DMA attributes.   System Reply Message Frames must be
2842          * aligned on a 4-byte boundry.  This is the default.
2843          */
2844         frame_dma_attrs = mpt->m_msg_dma_attr;
2845         frame_dma_attrs.dma_attr_sgllen = 1;
2846 
2847         /*
2848          * allocate the reply frame pool
2849          */
2850         if (mptsas_dma_addr_create(mpt, frame_dma_attrs,
2851             &mpt->m_dma_reply_frame_hdl, &mpt->m_acc_reply_frame_hdl, &memp,
2852             mem_size, &cookie) == FALSE) {
2853                 return (DDI_FAILURE);
2854         }
2855 
2856         /*
2857          * Store the reply frame memory address.  This chip uses this
2858          * address to dma to and from the driver's frame.  The second
2859          * address is the address mpt uses to process the frame.
2860          */
2861         mpt->m_reply_frame_dma_addr = cookie.dmac_laddress;
2862         mpt->m_reply_frame = memp;
2863 
2864         /*
2865          * Clear the reply frame pool.
2866          */
2867         bzero(mpt->m_reply_frame, mem_size);
2868 
2869         mpt->m_dma_flags |= MPTSAS_REPLY_FRAME;
2870         return (DDI_SUCCESS);
2871 }
2872 
2873 static int
2874 mptsas_alloc_free_queue(mptsas_t *mpt)
2875 {
2876         ddi_dma_attr_t          frame_dma_attrs;
2877         caddr_t                 memp;
2878         ddi_dma_cookie_t        cookie;
2879         size_t                  mem_size;
2880 
2881         /*
2882          * re-alloc when it has already alloced
2883          */
2884         if (mpt->m_dma_flags & MPTSAS_FREE_QUEUE) {
2885                 mptsas_dma_addr_destroy(&mpt->m_dma_free_queue_hdl,
2886                     &mpt->m_acc_free_queue_hdl);
2887                 mpt->m_dma_flags &= ~MPTSAS_FREE_QUEUE;
2888         }
2889 
2890         /*
2891          * The reply free queue size is:
2892          *   Reply Free Queue Depth * 4
2893          * The "4" is the size of one 32 bit address (low part of 64-bit
2894          *   address)
2895          */
2896         mem_size = mpt->m_free_queue_depth * 4;
2897 
2898         /*
2899          * set the DMA attributes  The Reply Free Queue must be aligned on a
2900          * 16-byte boundry.
2901          */
2902         frame_dma_attrs = mpt->m_msg_dma_attr;
2903         frame_dma_attrs.dma_attr_align = 16;
2904         frame_dma_attrs.dma_attr_sgllen = 1;
2905 
2906         /*
2907          * allocate the reply free queue
2908          */
2909         if (mptsas_dma_addr_create(mpt, frame_dma_attrs,
2910             &mpt->m_dma_free_queue_hdl, &mpt->m_acc_free_queue_hdl, &memp,
2911             mem_size, &cookie) == FALSE) {
2912                 return (DDI_FAILURE);
2913         }
2914 
2915         /*
2916          * Store the reply free queue memory address.  This chip uses this
2917          * address to read from the reply free queue.  The second address
2918          * is the address mpt uses to manage the queue.
2919          */
2920         mpt->m_free_queue_dma_addr = cookie.dmac_laddress;
2921         mpt->m_free_queue = memp;
2922 
2923         /*
2924          * Clear the reply free queue memory.
2925          */
2926         bzero(mpt->m_free_queue, mem_size);
2927 
2928         mpt->m_dma_flags |= MPTSAS_FREE_QUEUE;
2929         return (DDI_SUCCESS);
2930 }
2931 
2932 static void
2933 mptsas_free_post_queue(mptsas_t *mpt)
2934 {
2935         mptsas_reply_pqueue_t   *rpqp;
2936         int                     i;
2937 
2938         if (mpt->m_dma_flags & MPTSAS_POST_QUEUE) {
2939                 mptsas_dma_addr_destroy(&mpt->m_dma_post_queue_hdl,
2940                     &mpt->m_acc_post_queue_hdl);
2941                 rpqp = mpt->m_rep_post_queues;
2942                 for (i = 0; i < mpt->m_post_reply_qcount; i++) {
2943                         mutex_destroy(&rpqp->rpq_mutex);
2944                         rpqp++;
2945                 }
2946                 kmem_free(mpt->m_rep_post_queues,
2947                     sizeof (mptsas_reply_pqueue_t) *
2948                     mpt->m_post_reply_qcount);
2949                 mpt->m_dma_flags &= ~MPTSAS_POST_QUEUE;
2950         }
2951 }
2952 
2953 static int
2954 mptsas_alloc_post_queue(mptsas_t *mpt)
2955 {
2956         ddi_dma_attr_t          frame_dma_attrs;
2957         caddr_t                 memp;
2958         ddi_dma_cookie_t        cookie;
2959         size_t                  mem_size;
2960         mptsas_reply_pqueue_t   *rpqp;
2961         int                     i;
2962 
2963         /*
2964          * re-alloc when it has already alloced
2965          */
2966         mptsas_free_post_queue(mpt);

2967 
2968         /*
2969          * The reply descriptor post queue size is:
2970          *   Reply Descriptor Post Queue Depth * 8
2971          * The "8" is the size of each descriptor (8 bytes or 64 bits).
2972          */
2973         mpt->m_post_reply_qcount = mpt->m_intr_cnt;
2974         mem_size = mpt->m_post_queue_depth * 8 * mpt->m_post_reply_qcount;
2975 
2976         /*
2977          * set the DMA attributes.  The Reply Descriptor Post Queue must be
2978          * aligned on a 16-byte boundry.
2979          */
2980         frame_dma_attrs = mpt->m_msg_dma_attr;
2981         frame_dma_attrs.dma_attr_align = 16;
2982         frame_dma_attrs.dma_attr_sgllen = 1;
2983 
2984         /*
2985          * Allocate the reply post queue(s).
2986          * MPI2.5 introduces a method to allocate multiple queues
2987          * using a redirect table. For now stick to one contiguous
2988          * chunck. This can get as big as 1Mbyte for 16 queues.
2989          * The spec gives no indication that the queue size can be
2990          * reduced if you have many of them.
2991          */
2992         if (mptsas_dma_addr_create(mpt, frame_dma_attrs,
2993             &mpt->m_dma_post_queue_hdl, &mpt->m_acc_post_queue_hdl, &memp,
2994             mem_size, &cookie) == FALSE) {
2995                 return (DDI_FAILURE);
2996         }
2997 
2998         /*
2999          * Store the reply descriptor post queue memory address.  This chip
3000          * uses this address to write to the reply descriptor post queue.  The
3001          * second address is the address mpt uses to manage the queue.
3002          */
3003         mpt->m_post_queue_dma_addr = cookie.dmac_laddress;
3004         mpt->m_post_queue = memp;
3005 
3006         mpt->m_rep_post_queues = kmem_zalloc(sizeof (mptsas_reply_pqueue_t) *
3007             mpt->m_post_reply_qcount, KM_SLEEP);
3008         rpqp = mpt->m_rep_post_queues;
3009         for (i = 0; i < mpt->m_post_reply_qcount; i++) {
3010                 rpqp->rpq_queue = memp;
3011                 mutex_init(&rpqp->rpq_mutex, NULL, MUTEX_DRIVER, NULL);
3012                 rpqp->rpq_dlist.dl_tail = &rpqp->rpq_dlist.dl_q;
3013                 rpqp->rpq_num = (uint8_t)i;
3014                 memp += (mpt->m_post_queue_depth * 8);
3015                 rpqp++;
3016         }
3017 
3018         /*
3019          * Clear the reply post queue memory.
3020          */
3021         bzero(mpt->m_post_queue, mem_size);
3022 
3023         mpt->m_dma_flags |= MPTSAS_POST_QUEUE;
3024         return (DDI_SUCCESS);
3025 }
3026 
3027 static void
3028 mptsas_alloc_reply_args(mptsas_t *mpt)
3029 {
3030         if (mpt->m_replyh_args == NULL) {
3031                 mpt->m_replyh_args = kmem_zalloc(sizeof (m_replyh_arg_t) *
3032                     mpt->m_max_replies, KM_SLEEP);
3033         } else {
3034                 bzero(mpt->m_replyh_args, sizeof (m_replyh_arg_t) *
3035                     mpt->m_max_replies);
3036         }
3037 }
3038 
3039 static int
3040 mptsas_alloc_extra_sgl_frame(mptsas_t *mpt, mptsas_cmd_t *cmd)
3041 {
3042         mptsas_cache_frames_t   *frames = NULL;
3043         if (cmd->cmd_extra_frames == NULL) {
3044                 frames = kmem_cache_alloc(mpt->m_cache_frames, KM_NOSLEEP);
3045                 if (frames == NULL) {
3046                         return (DDI_FAILURE);
3047                 }
3048                 cmd->cmd_extra_frames = frames;
3049         }
3050         return (DDI_SUCCESS);
3051 }
3052 
3053 static void
3054 mptsas_free_extra_sgl_frame(mptsas_t *mpt, mptsas_cmd_t *cmd)
3055 {


3058                     (void *)cmd->cmd_extra_frames);
3059                 cmd->cmd_extra_frames = NULL;
3060         }
3061 }
3062 
3063 static void
3064 mptsas_cfg_fini(mptsas_t *mpt)
3065 {
3066         NDBG0(("mptsas_cfg_fini"));
3067         ddi_regs_map_free(&mpt->m_datap);
3068 }
3069 
3070 static void
3071 mptsas_hba_fini(mptsas_t *mpt)
3072 {
3073         NDBG0(("mptsas_hba_fini"));
3074 
3075         /*
3076          * Free up any allocated memory
3077          */
3078         if (mpt->m_dma_flags & MPTSAS_REQ_FRAME) {
3079                 mptsas_dma_addr_destroy(&mpt->m_dma_req_frame_hdl,
3080                     &mpt->m_acc_req_frame_hdl);
3081         }
3082 
3083         if (mpt->m_dma_flags & MPTSAS_REQ_SENSE) {
3084                 rmfreemap(mpt->m_erqsense_map);
3085                 mptsas_dma_addr_destroy(&mpt->m_dma_req_sense_hdl,
3086                     &mpt->m_acc_req_sense_hdl);
3087         }
3088 
3089         if (mpt->m_dma_flags & MPTSAS_REPLY_FRAME) {
3090                 mptsas_dma_addr_destroy(&mpt->m_dma_reply_frame_hdl,
3091                     &mpt->m_acc_reply_frame_hdl);
3092         }
3093 
3094         if (mpt->m_dma_flags & MPTSAS_FREE_QUEUE) {
3095                 mptsas_dma_addr_destroy(&mpt->m_dma_free_queue_hdl,
3096                     &mpt->m_acc_free_queue_hdl);
3097         }
3098 
3099         mptsas_free_post_queue(mpt);

3100 
3101         if (mpt->m_replyh_args != NULL) {
3102                 kmem_free(mpt->m_replyh_args, sizeof (m_replyh_arg_t)
3103                     * mpt->m_max_replies);
3104         }
3105 }
3106 
3107 static int
3108 mptsas_name_child(dev_info_t *lun_dip, char *name, int len)
3109 {
3110         int             lun = 0;
3111         char            *sas_wwn = NULL;
3112         int             phynum = -1;
3113         int             reallen = 0;
3114 
3115         /* Get the target num */
3116         lun = ddi_prop_get_int(DDI_DEV_T_ANY, lun_dip, DDI_PROP_DONTPASS,
3117             LUN_PROP, 0);
3118 
3119         if ((phynum = ddi_prop_get_int(DDI_DEV_T_ANY, lun_dip,


3358  * scsi_pkt handling
3359  *
3360  * Visible to the external world via the transport structure.
3361  */
3362 
3363 /*
3364  * Notes:
3365  *      - transport the command to the addressed SCSI target/lun device
3366  *      - normal operation is to schedule the command to be transported,
3367  *        and return TRAN_ACCEPT if this is successful.
3368  *      - if NO_INTR, tran_start must poll device for command completion
3369  */
3370 static int
3371 mptsas_scsi_start(struct scsi_address *ap, struct scsi_pkt *pkt)
3372 {
3373 #ifndef __lock_lint
3374         _NOTE(ARGUNUSED(ap))
3375 #endif
3376         mptsas_t        *mpt = PKT2MPT(pkt);
3377         mptsas_cmd_t    *cmd = PKT2CMD(pkt);
3378         int             rval, start;
3379         uint8_t         pref;
3380         mptsas_target_t *ptgt = cmd->cmd_tgt_addr;
3381         mptsas_tx_waitqueue_t *txwq;
3382 
3383         NDBG1(("mptsas_scsi_start: pkt=0x%p", (void *)pkt));
3384         ASSERT(ptgt);
3385         if (ptgt == NULL)
3386                 return (TRAN_FATAL_ERROR);
3387 
3388         /*
3389          * prepare the pkt before taking mutex.
3390          */
3391         rval = mptsas_prepare_pkt(cmd);
3392         if (rval != TRAN_ACCEPT) {
3393                 return (rval);
3394         }
3395 
3396         /*
3397          * Send the command to target/lun, however your HBA requires it.
3398          * If busy, return TRAN_BUSY; if there's some other formatting error
3399          * in the packet, return TRAN_BADPKT; otherwise, fall through to the
3400          * return of TRAN_ACCEPT.
3401          *


3410          * interrupt handler can refer to the pkt to set completion
3411          * status, call the target driver back through pkt_comp, etc.
3412          *
3413          * If the instance lock is held by other thread, don't spin to wait
3414          * for it. Instead, queue the cmd and next time when the instance lock
3415          * is not held, accept all the queued cmd. A extra tx_waitq is
3416          * introduced to protect the queue.
3417          *
3418          * The polled cmd will not be queud and accepted as usual.
3419          *
3420          * Under the tx_waitq mutex, record whether a thread is draining
3421          * the tx_waitq.  An IO requesting thread that finds the instance
3422          * mutex contended appends to the tx_waitq and while holding the
3423          * tx_wait mutex, if the draining flag is not set, sets it and then
3424          * proceeds to spin for the instance mutex. This scheme ensures that
3425          * the last cmd in a burst be processed.
3426          *
3427          * we enable this feature only when the helper threads are enabled,
3428          * at which we think the loads are heavy.
3429          *
3430          * per instance, per queue mutex m_tx_waitq[i].txwq_mutex is
3431          * introduced to protect the txwq_qtail, txwq_cmdq, txwq_len
3432          */
3433 
3434         if (mpt->m_txwq_enabled == TRUE) {
3435                 int gotmtx = 0;
3436 
3437                 if (mpt->m_txwq_allow_q_jumping) {
3438                         gotmtx = mutex_tryenter(&mpt->m_mutex);
3439                 }
3440                 if (gotmtx == 0) {
3441                         /* We didn't get the mutex or didn't try */
3442                         if (cmd->cmd_pkt_flags & FLAG_NOINTR) {
3443                                 mutex_enter(&mpt->m_mutex);
3444                                 /* Polled commands queue jump */
3445                                 mptsas_accept_tx_waitqs(mpt);
3446                         } else {
3447                                 rval = mptsas_check_targ_intxtion(
3448                                     cmd->cmd_tgt_addr,
3449                                     cmd->cmd_pkt_flags);
3450                                 if (rval != TRAN_ACCEPT) {
3451                                         return (rval);
3452                                 }
3453 
3454                                 cmd->cmd_flags |= CFLAG_TXQ;
3455                                 pref = mpt->m_pref_tx_waitq;
3456                                 txwq = &mpt->m_tx_waitq[pref];
3457 
3458                                 if (mutex_tryenter(&txwq->txwq_mutex) == 0) {
3459                                         txwq = &mpt->m_tx_waitq[pref^1];
3460                                         mutex_enter(&txwq->txwq_mutex);



3461                                 } else {
3462                                         pref ^= 1;
3463                                         mpt->m_pref_tx_waitq = pref;





3464                                 }
3465 
3466                                 *txwq->txwq_qtail = cmd;
3467                                 txwq->txwq_qtail = &cmd->cmd_linkp;
3468                                 txwq->txwq_len++;
3469                                 if (!txwq->txwq_draining) {
3470                                         cv_signal(&txwq->txwq_cv);
3471                                 }
3472                                 mutex_exit(&txwq->txwq_mutex);
3473                                 return (rval);









3474                         }
3475                 }
3476         } else {
3477                 mutex_enter(&mpt->m_mutex);





















3478         }
3479         rval = mptsas_check_targ_intxtion(cmd->cmd_tgt_addr,
3480             cmd->cmd_pkt_flags);
3481         if (rval != TRAN_ACCEPT) {
3482                 mutex_exit(&mpt->m_mutex);
3483                 return (rval);
3484         }
3485 
3486         start = mptsas_accept_pkt(mpt, cmd, &rval);
3487         mutex_exit(&mpt->m_mutex);
3488         if (start) {
3489                 (void) mptsas_start_cmd(mpt, cmd);
3490         }
3491 
3492         return (rval);
3493 }
3494 



3495 static int
3496 mptsas_check_targ_intxtion(mptsas_target_t *ptgt, int cmd_pkt_flags)
3497 {




3498         /*
3499          * ptgt->m_dr_flag is a variable that is only ever changed by
3500          * direct write under the main m_mutex.
3501          * It doesn't need a mutex hold to protect this read.






3502          */
3503 
3504         if (ptgt->m_dr_flag == MPTSAS_DR_INTRANSITION) {
3505                 if (cmd_pkt_flags & FLAG_NOQUEUE) {
3506                         /*
3507                          * The command should be allowed to retry by returning
3508                          * TRAN_BUSY to stall the I/O's which come from
3509                          * scsi_vhci since the device/path is in unstable state
3510                          * now.
3511                          */
3512                         return (TRAN_BUSY);
3513                 } else {
3514                         /*
3515                          * The device is offline, just fail the command by
3516                          * return TRAN_FATAL_ERROR.
3517                          */
3518                         return (TRAN_FATAL_ERROR);
3519                 }
3520         }
3521         return (TRAN_ACCEPT);
3522 }
3523 
3524 /*
3525  * Note that this function has a side effect of releasing the
3526  * per target mutex.
3527  */
3528 static void
3529 mptsas_offline_target_direct(mptsas_t *mpt, mptsas_target_t *ptgt)
3530 {
3531         char                            phy_mask_name[MPTSAS_MAX_PHYS];
3532         mptsas_phymask_t                phymask = ptgt->m_addr.mta_phymask;
3533         dev_info_t                      *parent;
3534 
3535         ASSERT(mutex_owned(&mpt->m_mutex));
3536 
3537         ptgt->m_dr_flag = MPTSAS_DR_INTRANSITION;
3538         bzero(phy_mask_name, MPTSAS_MAX_PHYS);
3539         (void) sprintf(phy_mask_name, "%x", phymask);
3540         parent = scsi_hba_iport_find(mpt->m_dip, phy_mask_name);
3541 
3542         if (parent != NULL) {
3543                 mptsas_offline_target(mpt, ptgt,
3544                     ptgt->m_deviceinfo & DEVINFO_DIRECT_ATTACHED ?
3545                     MPTSAS_TOPO_FLAG_DIRECT_ATTACHED_DEVICE :
3546                     MPTSAS_TOPO_FLAG_EXPANDER_ATTACHED_DEVICE,
3547                     parent);
3548         } else {
3549                 mptsas_log(mpt, CE_WARN, "Failed to find an "
3550                     "iport for \"%s\", should not happen!",
3551                     phy_mask_name);
3552         }
3553 }
3554 
3555 /*
3556  * In order to be efficient with the m_mutex (which can be dropped before
3557  * calling mptsas_start_cmd()) indicate if start_cmd should be called via the
3558  * returned value (FALSE or TRUE). Caller is then responsible for doing the
3559  * right thing with the m_mutex.
3560  */
3561 static int
3562 mptsas_accept_pkt(mptsas_t *mpt, mptsas_cmd_t *cmd, int *tran_rval)
3563 {
3564         int             rval = TRAN_ACCEPT;
3565         mptsas_target_t *ptgt = cmd->cmd_tgt_addr;
3566 
3567         NDBG1(("mptsas_accept_pkt: cmd=0x%p", (void *)cmd));
3568 
3569         ASSERT(mutex_owned(&mpt->m_mutex));
3570 
3571         if ((cmd->cmd_flags & CFLAG_PREPARED) == 0) {
3572                 rval = mptsas_prepare_pkt(cmd);
3573                 if (rval != TRAN_ACCEPT) {
3574                         cmd->cmd_flags &= ~CFLAG_TRANFLAG;
3575                         goto set_tranrval;
3576                 }
3577         }
3578 
3579         /*
3580          * If the command came from the tx wait q it may have slipped
3581          * by the check for dr_flag before being added to the queue.
3582          * Fail here with abort status.
3583          */
3584         if (cmd->cmd_flags & CFLAG_TXQ) {
3585                 rval = mptsas_check_targ_intxtion(cmd->cmd_tgt_addr,
3586                     cmd->cmd_pkt_flags);
3587                 if (rval != TRAN_ACCEPT) {
3588                         mptsas_set_pkt_reason(mpt, cmd, CMD_ABORTED,
3589                             STAT_ABORTED);
3590                         mptsas_doneq_add(mpt, cmd);
3591                         mptsas_doneq_empty(mpt);
3592                         goto set_tranrval;
3593                 }
3594         }

3595         /*
3596          * If HBA is being reset, the DevHandles are being re-initialized,
3597          * which means that they could be invalid even if the target is still
3598          * attached.  Check if being reset and if DevHandle is being
3599          * re-initialized.  If this is the case, return BUSY so the I/O can be
3600          * retried later.
3601          */
3602         if ((ptgt->m_devhdl == MPTSAS_INVALID_DEVHDL) && mpt->m_in_reset) {
3603                 mptsas_set_pkt_reason(mpt, cmd, CMD_RESET, STAT_BUS_RESET);
3604                 if (cmd->cmd_flags & CFLAG_TXQ) {
3605                         mptsas_doneq_add(mpt, cmd);
3606                         mptsas_doneq_empty(mpt);

3607                 } else {
3608                         rval = TRAN_BUSY;
3609                 }
3610                 goto set_tranrval;
3611         }
3612 
3613         mutex_enter(&ptgt->m_t_mutex);
3614         /*
3615          * reset the throttle if we were draining
3616          */
3617         if ((ptgt->m_t_ncmds == 0) &&
3618             (ptgt->m_t_throttle == DRAIN_THROTTLE)) {
3619                 NDBG23(("reset throttle"));
3620                 ASSERT(ptgt->m_reset_delay == 0);
3621                 mptsas_set_throttle(mpt, ptgt, MAX_THROTTLE);
3622         }
3623 
3624         /*
3625          * If device handle has already been invalidated, just
3626          * fail the command. In theory, for a command from scsi_vhci
3627          * client it's impossible to receive a command with an invalid
3628          * devhdl since devhdl is set after path offline, target
3629          * driver is not supposed to select an offlined path.
3630          */
3631         if (ptgt->m_devhdl == MPTSAS_INVALID_DEVHDL) {
3632                 NDBG3(("rejecting command, it might because invalid devhdl "
3633                     "request."));
3634                 mutex_exit(&ptgt->m_t_mutex);
3635                 mptsas_set_pkt_reason(mpt, cmd, CMD_DEV_GONE, STAT_TERMINATED);
3636                 if (cmd->cmd_flags & CFLAG_TXQ) {
3637                         mptsas_doneq_add(mpt, cmd);
3638                         mptsas_doneq_empty(mpt);

3639                 } else {
3640                         rval = TRAN_FATAL_ERROR;
3641                 }
3642                 goto set_tranrval;
3643         }
3644         /*
3645          * The first case is the normal case.  mpt gets a command from the
3646          * target driver and starts it.
3647          * Since SMID 0 is reserved and the TM slot is reserved, the actual max
3648          * commands is m_max_requests - 2.
3649          */
3650         if ((mpt->m_ncmds <= (mpt->m_max_requests - 2)) &&
3651             (ptgt->m_t_throttle > HOLD_THROTTLE) &&
3652             (ptgt->m_t_ncmds < ptgt->m_t_throttle) &&
3653             (ptgt->m_reset_delay == 0) && (mpt->m_polled_intr == 0) &&
3654             (ptgt->m_t_nwait == 0) &&
3655             ((cmd->cmd_pkt_flags & FLAG_NOINTR) == 0)) {
3656                 ASSERT((cmd->cmd_flags & CFLAG_CMDIOC) == 0);
3657                 if (mptsas_save_cmd_to_slot(mpt, cmd) == TRUE) {
3658                         ptgt->m_t_ncmds++;
3659                         mutex_exit(&ptgt->m_t_mutex);
3660                         cmd->cmd_active_expiration = 0;
3661                         *tran_rval = rval;
3662                         return (TRUE);
3663                 } else {
3664                         mutex_exit(&ptgt->m_t_mutex);
3665                         mptsas_waitq_add(mpt, cmd);
3666                 }
3667         } else {
3668                 mutex_exit(&ptgt->m_t_mutex);
3669                 /*
3670                  * Add this pkt to the work queue
3671                  */
3672                 mptsas_waitq_add(mpt, cmd);
3673 
3674                 if (cmd->cmd_pkt_flags & FLAG_NOINTR) {
3675                         (void) mptsas_poll(mpt, cmd, MPTSAS_POLL_TIME);
3676 
3677                         /*
3678                          * Only flush the doneq if this is not a TM
3679                          * cmd.  For TM cmds the flushing of the
3680                          * doneq will be done in those routines.
3681                          */
3682                         if ((cmd->cmd_flags & CFLAG_TM_CMD) == 0) {
3683                                 mptsas_doneq_empty(mpt);
3684                         }
3685                 }
3686         }
3687 set_tranrval:
3688         *tran_rval = rval;
3689         return (FALSE);
3690 }
3691 
3692 static void
3693 mptsas_retry_pkt(mptsas_t *mpt, mptsas_cmd_t *cmd)
3694 {
3695         int             rval;


3696 
3697         cmd->cmd_pkt_flags |= FLAG_HEAD;
3698         cmd->cmd_flags |= CFLAG_RETRY;
3699         cmd->cmd_flags &= ~CFLAG_TXQ;
3700         if (mptsas_accept_pkt(mpt, cmd, &rval)) {
3701                 (void) mptsas_start_cmd(mpt, cmd);
3702         }
3703 
3704         /*
3705          * If there was a problem clear the retry flag so that the
3706          * command will be completed with error rather than get lost!
3707          */
3708         if (rval != TRAN_ACCEPT)
3709                 cmd->cmd_flags &= ~CFLAG_RETRY;
3710 }
3711 
3712 static int
3713 mptsas_save_cmd_to_slot(mptsas_t *mpt, mptsas_cmd_t *cmd)
3714 {
3715         mptsas_slots_t *slots = mpt->m_active;
3716         uint_t slot, start_rotor, rotor, n_normal;
3717 
3718         /*
3719          * Account for reserved TM request slot and reserved SMID of 0.
3720          */
3721         ASSERT(slots->m_n_normal == (mpt->m_max_requests - 2));
3722 
3723         /*
3724          * Find the next available slot, beginning at m_rotor.  If no slot is
3725          * available, we'll return FALSE to indicate that.  This mechanism
3726          * considers only the normal slots, not the reserved slot 0 nor the
3727          * task management slot m_n_normal + 1.  The rotor is left to point to
3728          * the normal slot after the one we select, unless we select the last
3729          * normal slot in which case it returns to slot 1.
3730          */
3731         start_rotor = rotor = slots->m_rotor;
3732         n_normal = slots->m_n_normal;
3733         do {
3734                 slot = rotor++;
3735                 if (rotor > n_normal)
3736                         rotor = 1;
3737 
3738                 if (rotor == start_rotor)
3739                         break;
3740         } while (slots->m_slot[slot] != NULL);
3741         slots->m_rotor = rotor;
3742 
3743         if (slots->m_slot[slot] != NULL)
3744                 return (FALSE);
3745 
3746         ASSERT(slot != 0 && slot <= slots->m_n_normal);
3747 
3748         cmd->cmd_slot = slot;
3749         slots->m_slot[slot] = cmd;
3750         atomic_inc_32(&mpt->m_ncmds);
3751 
3752         /*
3753          * Distribute the commands amongst the reply queues (Interrupt vectors).
3754          * Stick to 0 for polled.
3755          */
3756         if (!(cmd->cmd_pkt_flags & FLAG_NOINTR) &&
3757             !(cmd->cmd_flags & (CFLAG_PASSTHRU|CFLAG_CONFIG|CFLAG_FW_DIAG)) &&
3758             (mpt->m_post_reply_qcount > 1)) {
3759                 cmd->cmd_rpqidx = slot % mpt->m_post_reply_qcount;
3760         }
3761         atomic_inc_32(&mpt->m_rep_post_queues[cmd->cmd_rpqidx].rpq_ncmds);
3762         return (TRUE);
3763 }
3764 
3765 int
3766 mptsas_save_cmd(mptsas_t *mpt, mptsas_cmd_t *cmd)
3767 {
3768         mptsas_target_t *ptgt = cmd->cmd_tgt_addr;
3769 
3770         ASSERT(MUTEX_HELD(&mpt->m_mutex));
3771 
3772         if (!mptsas_save_cmd_to_slot(mpt, cmd)) {
3773                 return (FALSE);
3774         }
3775 
3776         /*
3777          * only increment per target ncmds if this is not a
3778          * command that has no target associated with it (i.e. a
3779          * event acknoledgement)
3780          */
3781         if ((cmd->cmd_flags & CFLAG_CMDIOC) == 0) {
3782                 /*
3783                  * Expiration time is set in mptsas_start_cmd
3784                  */
3785                 mutex_enter(&ptgt->m_t_mutex);
3786                 ptgt->m_t_ncmds++;
3787                 mutex_exit(&ptgt->m_t_mutex);
3788                 cmd->cmd_active_expiration = 0;
3789         } else {
3790                 /*
3791                  * Initialize expiration time for passthrough commands,


3792                  */
3793                 cmd->cmd_active_expiration = gethrtime() +
3794                     (hrtime_t)cmd->cmd_pkt->pkt_time * NANOSEC;
3795         }
3796         return (TRUE);
3797 }
3798 
3799 /*
3800  * prepare the pkt:
3801  * the pkt may have been resubmitted or just reused so
3802  * initialize some fields and do some checks.
3803  */
3804 static int
3805 mptsas_prepare_pkt(mptsas_cmd_t *cmd)
3806 {
3807         struct scsi_pkt *pkt = CMD2PKT(cmd);
3808 
3809         NDBG1(("mptsas_prepare_pkt: cmd=0x%p", (void *)cmd));
3810 
3811         /*
3812          * Reinitialize some fields that need it; the packet may
3813          * have been resubmitted
3814          */


3879         ASSERT(ptgt != NULL);
3880         if (ptgt == NULL)
3881                 return (NULL);
3882         ap->a_target = ptgt->m_devhdl;
3883         ap->a_lun = tgt_private->t_lun;
3884 
3885         ASSERT(callback == NULL_FUNC || callback == SLEEP_FUNC);
3886 #ifdef MPTSAS_TEST_EXTRN_ALLOC
3887         statuslen *= 100; tgtlen *= 4;
3888 #endif
3889         NDBG3(("mptsas_scsi_init_pkt:\n"
3890             "\ttgt=%d in=0x%p bp=0x%p clen=%d slen=%d tlen=%d flags=%x",
3891             ap->a_target, (void *)pkt, (void *)bp,
3892             cmdlen, statuslen, tgtlen, flags));
3893 
3894         /*
3895          * Allocate the new packet.
3896          */
3897         if (pkt == NULL) {
3898                 ddi_dma_handle_t        save_dma_handle;



3899 
3900                 cmd = kmem_cache_alloc(mpt->m_kmem_cache, kf);
3901 
3902                 if (cmd) {
3903                         save_dma_handle = cmd->cmd_dmahandle;



3904                         bzero(cmd, sizeof (*cmd) + scsi_pkt_size());
3905                         cmd->cmd_dmahandle = save_dma_handle;



3906 
3907                         pkt = (void *)((uchar_t *)cmd +
3908                             sizeof (struct mptsas_cmd));
3909                         pkt->pkt_ha_private = (opaque_t)cmd;
3910                         pkt->pkt_address = *ap;
3911                         pkt->pkt_private = (opaque_t)cmd->cmd_pkt_private;
3912                         pkt->pkt_scbp = (opaque_t)&cmd->cmd_scb;
3913                         pkt->pkt_cdbp = (opaque_t)&cmd->cmd_cdb;
3914                         cmd->cmd_pkt = (struct scsi_pkt *)pkt;
3915                         cmd->cmd_cdblen = (uchar_t)cmdlen;
3916                         cmd->cmd_scblen = statuslen;
3917                         cmd->cmd_rqslen = SENSE_LENGTH;
3918                         cmd->cmd_tgt_addr = ptgt;
3919                         failure = 0;
3920                 }
3921 
3922                 if (failure || (cmdlen > sizeof (cmd->cmd_cdb)) ||
3923                     (tgtlen > PKT_PRIV_LEN) ||
3924                     (statuslen > EXTCMDS_STATUS_SIZE)) {
3925                         if (failure == 0) {


4165 
4166                         cmd->cmd_dmacount += cmd->cmd_cookie.dmac_size;
4167                         cmd->cmd_totaldmacount += cmd->cmd_cookie.dmac_size;
4168 
4169                         /*
4170                          * store the segment parms into the S/G list
4171                          */
4172                         dmap->count = cmd->cmd_cookie.dmac_size;
4173                         dmap->addr.address64.Low = (uint32_t)
4174                             (cmd->cmd_cookie.dmac_laddress & 0xffffffffull);
4175                         dmap->addr.address64.High = (uint32_t)
4176                             (cmd->cmd_cookie.dmac_laddress >> 32);
4177                 }
4178 
4179                 /*
4180                  * If this was partially allocated we set the resid
4181                  * the amount of data NOT transferred in this window
4182                  * If there is only one window, the resid will be 0
4183                  */
4184                 pkt->pkt_resid = (bp->b_bcount - cmd->cmd_totaldmacount);
4185                 NDBG3(("mptsas_scsi_init_pkt: cmd_dmacount=%d.",
4186                     cmd->cmd_dmacount));
4187         }
4188         return (pkt);
4189 }
4190 
4191 /*
4192  * tran_destroy_pkt(9E) - scsi_pkt(9s) deallocation
4193  *
4194  * Notes:
4195  *      - also frees DMA resources if allocated
4196  *      - implicit DMA synchonization
4197  */
4198 static void
4199 mptsas_scsi_destroy_pkt(struct scsi_address *ap, struct scsi_pkt *pkt)
4200 {
4201         mptsas_cmd_t    *cmd = PKT2CMD(pkt);
4202         mptsas_t        *mpt = ADDR2MPT(ap);
4203 
4204         NDBG3(("mptsas_scsi_destroy_pkt: target=%d pkt=0x%p",
4205             ap->a_target, (void *)pkt));
4206 


4219         if ((cmd->cmd_flags &
4220             (CFLAG_FREE | CFLAG_CDBEXTERN | CFLAG_PRIVEXTERN |
4221             CFLAG_SCBEXTERN)) == 0) {
4222                 cmd->cmd_flags = CFLAG_FREE;
4223                 kmem_cache_free(mpt->m_kmem_cache, (void *)cmd);
4224         } else {
4225                 mptsas_pkt_destroy_extern(mpt, cmd);
4226         }
4227 }
4228 
4229 /*
4230  * kmem cache constructor and destructor:
4231  * When constructing, we bzero the cmd and allocate the dma handle
4232  * When destructing, just free the dma handle
4233  */
4234 static int
4235 mptsas_kmem_cache_constructor(void *buf, void *cdrarg, int kmflags)
4236 {
4237         mptsas_cmd_t            *cmd = buf;
4238         mptsas_t                *mpt  = cdrarg;



4239         int                     (*callback)(caddr_t);
4240 
4241         callback = (kmflags == KM_SLEEP)? DDI_DMA_SLEEP: DDI_DMA_DONTWAIT;
4242 
4243         NDBG4(("mptsas_kmem_cache_constructor"));
4244 




4245         /*
4246          * allocate a dma handle
4247          */
4248         if ((ddi_dma_alloc_handle(mpt->m_dip, &mpt->m_io_dma_attr, callback,
4249             NULL, &cmd->cmd_dmahandle)) != DDI_SUCCESS) {
4250                 cmd->cmd_dmahandle = NULL;
4251                 return (-1);
4252         }



































4253         return (0);
4254 }
4255 
4256 static void
4257 mptsas_kmem_cache_destructor(void *buf, void *cdrarg)
4258 {
4259 #ifndef __lock_lint
4260         _NOTE(ARGUNUSED(cdrarg))
4261 #endif
4262         mptsas_cmd_t    *cmd = buf;
4263 
4264         NDBG4(("mptsas_kmem_cache_destructor"));
4265 









4266         if (cmd->cmd_dmahandle) {
4267                 ddi_dma_free_handle(&cmd->cmd_dmahandle);
4268                 cmd->cmd_dmahandle = NULL;
4269         }
4270 }
4271 
4272 static int
4273 mptsas_cache_frames_constructor(void *buf, void *cdrarg, int kmflags)
4274 {
4275         mptsas_cache_frames_t   *p = buf;
4276         mptsas_t                *mpt = cdrarg;
4277         ddi_dma_attr_t          frame_dma_attr;
4278         size_t                  mem_size, alloc_len;
4279         ddi_dma_cookie_t        cookie;
4280         uint_t                  ncookie;
4281         int (*callback)(caddr_t) = (kmflags == KM_SLEEP)
4282             ? DDI_DMA_SLEEP: DDI_DMA_DONTWAIT;
4283 
4284         frame_dma_attr = mpt->m_msg_dma_attr;
4285         frame_dma_attr.dma_attr_align = 0x10;


4303                     " extra SGL.");
4304                 return (DDI_FAILURE);
4305         }
4306 
4307         if (ddi_dma_addr_bind_handle(p->m_dma_hdl, NULL, p->m_frames_addr,
4308             alloc_len, DDI_DMA_RDWR | DDI_DMA_CONSISTENT, callback, NULL,
4309             &cookie, &ncookie) != DDI_DMA_MAPPED) {
4310                 (void) ddi_dma_mem_free(&p->m_acc_hdl);
4311                 ddi_dma_free_handle(&p->m_dma_hdl);
4312                 p->m_dma_hdl = NULL;
4313                 mptsas_log(mpt, CE_WARN, "Unable to bind DMA resources for"
4314                     " extra SGL");
4315                 return (DDI_FAILURE);
4316         }
4317 
4318         /*
4319          * Store the SGL memory address.  This chip uses this
4320          * address to dma to and from the driver.  The second
4321          * address is the address mpt uses to fill in the SGL.
4322          */
4323         p->m_phys_addr = cookie.dmac_laddress;
4324 
4325         return (DDI_SUCCESS);
4326 }
4327 
4328 static void
4329 mptsas_cache_frames_destructor(void *buf, void *cdrarg)
4330 {
4331 #ifndef __lock_lint
4332         _NOTE(ARGUNUSED(cdrarg))
4333 #endif
4334         mptsas_cache_frames_t   *p = buf;
4335         if (p->m_dma_hdl != NULL) {
4336                 (void) ddi_dma_unbind_handle(p->m_dma_hdl);
4337                 (void) ddi_dma_mem_free(&p->m_acc_hdl);
4338                 ddi_dma_free_handle(&p->m_dma_hdl);
4339                 p->m_phys_addr = NULL;
4340                 p->m_frames_addr = NULL;
4341                 p->m_dma_hdl = NULL;
4342                 p->m_acc_hdl = NULL;
4343         }
4344 
4345 }
4346 
4347 /*
4348  * allocate and deallocate external pkt space (ie. not part of mptsas_cmd)
4349  * for non-standard length cdb, pkt_private, status areas
4350  * if allocation fails, then deallocate all external space and the pkt
4351  */
4352 /* ARGSUSED */
4353 static int
4354 mptsas_pkt_alloc_extern(mptsas_t *mpt, mptsas_cmd_t *cmd,
4355     int cmdlen, int tgtlen, int statuslen, int kf)
4356 {
4357         caddr_t                 cdbp, scbp, tgt;



4358         size_t                  senselength;


4359 
4360         NDBG3(("mptsas_pkt_alloc_extern: "
4361             "cmd=0x%p cmdlen=%d tgtlen=%d statuslen=%d kf=%x",
4362             (void *)cmd, cmdlen, tgtlen, statuslen, kf));
4363 
4364         tgt = cdbp = scbp = NULL;
4365         cmd->cmd_scblen              = statuslen;
4366         cmd->cmd_privlen     = (uchar_t)tgtlen;
4367 
4368         if (cmdlen > sizeof (cmd->cmd_cdb)) {
4369                 if ((cdbp = kmem_zalloc((size_t)cmdlen, kf)) == NULL) {
4370                         goto fail;
4371                 }
4372                 cmd->cmd_pkt->pkt_cdbp = (opaque_t)cdbp;
4373                 cmd->cmd_flags |= CFLAG_CDBEXTERN;
4374         }
4375         if (tgtlen > PKT_PRIV_LEN) {
4376                 if ((tgt = kmem_zalloc((size_t)tgtlen, kf)) == NULL) {
4377                         goto fail;
4378                 }
4379                 cmd->cmd_flags |= CFLAG_PRIVEXTERN;
4380                 cmd->cmd_pkt->pkt_private = tgt;
4381         }
4382         if (statuslen > EXTCMDS_STATUS_SIZE) {
4383                 if ((scbp = kmem_zalloc((size_t)statuslen, kf)) == NULL) {
4384                         goto fail;
4385                 }
4386                 cmd->cmd_flags |= CFLAG_SCBEXTERN;
4387                 cmd->cmd_pkt->pkt_scbp = (opaque_t)scbp;
4388 
4389                 /* allocate sense data buf for DMA */
4390 
4391                 senselength = statuslen - MPTSAS_GET_ITEM_OFF(
4392                     struct scsi_arq_status, sts_sensedata);
4393                 if (senselength > mpt->m_req_sense_size) {
4394                         unsigned long i;
4395                         cmd->cmd_extrqslen = (uint16_t)senselength;
4396                         cmd->cmd_extrqschunks = (senselength +
4397                             (mpt->m_req_sense_size - 1))/mpt->m_req_sense_size;
4398                         i = rmalloc_wait(mpt->m_erqsense_map,
4399                             cmd->cmd_extrqschunks);
4400                         ASSERT(i != 0);
4401                         cmd->cmd_extrqsidx = i - 1;
4402                         cmd->cmd_arq_buf = mpt->m_extreq_sense +
4403                             (cmd->cmd_extrqsidx * mpt->m_req_sense_size);
4404                 } else {
4405                         cmd->cmd_rqslen = (uchar_t)senselength;





























4406                 }

4407         }
4408         return (0);
4409 fail:
4410         mptsas_pkt_destroy_extern(mpt, cmd);
4411         return (1);
4412 }
4413 
4414 /*
4415  * deallocate external pkt space and deallocate the pkt
4416  */
4417 static void
4418 mptsas_pkt_destroy_extern(mptsas_t *mpt, mptsas_cmd_t *cmd)
4419 {
4420         NDBG3(("mptsas_pkt_destroy_extern: cmd=0x%p", (void *)cmd));
4421 
4422         if (cmd->cmd_flags & CFLAG_FREE) {
4423                 mptsas_log(mpt, CE_PANIC,
4424                     "mptsas_pkt_destroy_extern: freeing free packet");
4425                 _NOTE(NOT_REACHED)
4426                 /* NOTREACHED */
4427         }
4428         if (cmd->cmd_extrqslen != 0) {
4429                 rmfree(mpt->m_erqsense_map, cmd->cmd_extrqschunks,
4430                     cmd->cmd_extrqsidx + 1);
4431         }
4432         if (cmd->cmd_flags & CFLAG_CDBEXTERN) {
4433                 kmem_free(cmd->cmd_pkt->pkt_cdbp, (size_t)cmd->cmd_cdblen);
4434         }
4435         if (cmd->cmd_flags & CFLAG_SCBEXTERN) {
4436                 kmem_free(cmd->cmd_pkt->pkt_scbp, (size_t)cmd->cmd_scblen);









4437         }
4438         if (cmd->cmd_flags & CFLAG_PRIVEXTERN) {
4439                 kmem_free(cmd->cmd_pkt->pkt_private, (size_t)cmd->cmd_privlen);
4440         }
4441         cmd->cmd_flags = CFLAG_FREE;
4442         kmem_cache_free(mpt->m_kmem_cache, (void *)cmd);
4443 }
4444 
4445 /*
4446  * tran_sync_pkt(9E) - explicit DMA synchronization
4447  */
4448 /*ARGSUSED*/
4449 static void
4450 mptsas_scsi_sync_pkt(struct scsi_address *ap, struct scsi_pkt *pkt)
4451 {
4452         mptsas_cmd_t    *cmd = PKT2CMD(pkt);
4453 
4454         NDBG3(("mptsas_scsi_sync_pkt: target=%d, pkt=0x%p",
4455             ap->a_target, (void *)pkt));
4456 


4462 }
4463 
4464 /*
4465  * tran_dmafree(9E) - deallocate DMA resources allocated for command
4466  */
4467 /*ARGSUSED*/
4468 static void
4469 mptsas_scsi_dmafree(struct scsi_address *ap, struct scsi_pkt *pkt)
4470 {
4471         mptsas_cmd_t    *cmd = PKT2CMD(pkt);
4472         mptsas_t        *mpt = ADDR2MPT(ap);
4473 
4474         NDBG3(("mptsas_scsi_dmafree: target=%d pkt=0x%p",
4475             ap->a_target, (void *)pkt));
4476 
4477         if (cmd->cmd_flags & CFLAG_DMAVALID) {
4478                 (void) ddi_dma_unbind_handle(cmd->cmd_dmahandle);
4479                 cmd->cmd_flags &= ~CFLAG_DMAVALID;
4480         }
4481 





4482         mptsas_free_extra_sgl_frame(mpt, cmd);
4483 }
4484 
4485 static void
4486 mptsas_pkt_comp(struct scsi_pkt *pkt, mptsas_cmd_t *cmd)
4487 {
4488         if ((cmd->cmd_flags & CFLAG_CMDIOPB) &&
4489             (!(cmd->cmd_flags & CFLAG_DMASEND))) {
4490                 (void) ddi_dma_sync(cmd->cmd_dmahandle, 0, 0,
4491                     DDI_DMA_SYNC_FORCPU);
4492         }
4493         (*pkt->pkt_comp)(pkt);
4494 }
4495 
4496 static void
4497 mptsas_sge_mainframe(mptsas_cmd_t *cmd, pMpi2SCSIIORequest_t frame,
4498                 ddi_acc_handle_t acc_hdl, uint_t cookiec,
4499                 uint32_t end_flags)
4500 {
4501         pMpi2SGESimple64_t      sge;
4502         mptti_t                 *dmap;
4503         uint32_t                flags;






















4504 










4505         dmap = cmd->cmd_sg;
4506 
4507         sge = (pMpi2SGESimple64_t)(&frame->SGL);
4508         while (cookiec--) {
4509                 ddi_put32(acc_hdl, &sge->Address.Low,
4510                     dmap->addr.address64.Low);
4511                 ddi_put32(acc_hdl, &sge->Address.High,
4512                     dmap->addr.address64.High);
4513                 ddi_put32(acc_hdl, &sge->FlagsLength, dmap->count);

4514                 flags = ddi_get32(acc_hdl, &sge->FlagsLength);
4515                 flags |= ((uint32_t)
4516                     (MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
4517                     MPI2_SGE_FLAGS_SYSTEM_ADDRESS |
4518                     MPI2_SGE_FLAGS_64_BIT_ADDRESSING) <<
4519                     MPI2_SGE_FLAGS_SHIFT);
4520 
4521                 /*
4522                  * If this is the last cookie, we set the flags
4523                  * to indicate so
4524                  */
4525                 if (cookiec == 0) {
4526                         flags |= end_flags;




4527                 }
4528                 if (cmd->cmd_flags & CFLAG_DMASEND) {
4529                         flags |= (MPI2_SGE_FLAGS_HOST_TO_IOC <<
4530                             MPI2_SGE_FLAGS_SHIFT);
4531                 } else {
4532                         flags |= (MPI2_SGE_FLAGS_IOC_TO_HOST <<
4533                             MPI2_SGE_FLAGS_SHIFT);
4534                 }
4535                 ddi_put32(acc_hdl, &sge->FlagsLength, flags);
4536                 dmap++;
4537                 sge++;
4538         }
4539 }
4540 
4541 static void
4542 mptsas_sge_chain(mptsas_t *mpt, mptsas_cmd_t *cmd,
4543     pMpi2SCSIIORequest_t frame, ddi_acc_handle_t acc_hdl)
4544 {
4545         pMpi2SGESimple64_t      sge;
4546         pMpi2SGEChain64_t       sgechain;
4547         uint64_t                nframe_phys_addr;
4548         uint_t                  cookiec;
4549         mptti_t                 *dmap;
4550         uint32_t                flags;
4551         int                     i, j, k, l, frames, sgemax;
4552         int                     temp, maxframe_sges;
4553         uint8_t                 chainflags;
4554         uint16_t                chainlength;
4555         mptsas_cache_frames_t   *p;
4556 
4557         cookiec = cmd->cmd_cookiec;
4558 
4559         /*
4560          * Hereby we start to deal with multiple frames.
4561          * The process is as follows:
4562          * 1. Determine how many frames are needed for SGL element
4563          *    storage; Note that all frames are stored in contiguous
4564          *    memory space and in 64-bit DMA mode each element is
4565          *    3 double-words (12 bytes) long.
4566          * 2. Fill up the main frame. We need to do this separately
4567          *    since it contains the SCSI IO request header and needs
4568          *    dedicated processing. Note that the last 4 double-words
4569          *    of the SCSI IO header is for SGL element storage
4570          *    (MPI2_SGE_IO_UNION).
4571          * 3. Fill the chain element in the main frame, so the DMA
4572          *    engine can use the following frames.
4573          * 4. Enter a loop to fill the remaining frames. Note that the
4574          *    last frame contains no chain element.  The remaining
4575          *    frames go into the mpt SGL buffer allocated on the fly,
4576          *    not immediately following the main message frame, as in
4577          *    Gen1.
4578          * Some restrictions:
4579          * 1. For 64-bit DMA, the simple element and chain element
4580          *    are both of 3 double-words (12 bytes) in size, even
4581          *    though all frames are stored in the first 4G of mem
4582          *    range and the higher 32-bits of the address are always 0.
4583          * 2. On some controllers (like the 1064/1068), a frame can
4584          *    hold SGL elements with the last 1 or 2 double-words
4585          *    (4 or 8 bytes) un-used. On these controllers, we should
4586          *    recognize that there's not enough room for another SGL
4587          *    element and move the sge pointer to the next frame.
4588          */





4589 
4590         /*
4591          * Sgemax is the number of SGE's that will fit
4592          * each extra frame and frames is total
4593          * number of frames we'll need.  1 sge entry per
4594          * frame is reseverd for the chain element thus the -1 below.
4595          */
4596         sgemax = ((mpt->m_req_frame_size / sizeof (MPI2_SGE_SIMPLE64)) - 1);
4597         maxframe_sges = MPTSAS_MAX_FRAME_SGES64(mpt);
4598         temp = (cookiec - (maxframe_sges - 1)) / sgemax;
4599 
4600         /*
4601          * A little check to see if we need to round up the number
4602          * of frames we need
4603          */
4604         if ((cookiec - (maxframe_sges - 1)) - (temp * sgemax) > 1) {

4605                 frames = (temp + 1);
4606         } else {
4607                 frames = temp;
4608         }
4609         dmap = cmd->cmd_sg;
4610         sge = (pMpi2SGESimple64_t)(&frame->SGL);
4611 
4612         /*
4613          * First fill in the main frame
4614          */
4615         j = maxframe_sges - 1;
4616         mptsas_sge_mainframe(cmd, frame, acc_hdl, j,
4617             ((uint32_t)(MPI2_SGE_FLAGS_LAST_ELEMENT) <<
4618             MPI2_SGE_FLAGS_SHIFT));
4619         dmap += j;
4620         sge += j;
4621         j++;



























4622 
4623         /*
4624          * Fill in the chain element in the main frame.
4625          * About calculation on ChainOffset:
4626          * 1. Struct msg_scsi_io_request has 4 double-words (16 bytes)
4627          *    in the end reserved for SGL element storage
4628          *    (MPI2_SGE_IO_UNION); we should count it in our
4629          *    calculation.  See its definition in the header file.
4630          * 2. Constant j is the counter of the current SGL element
4631          *    that will be processed, and (j - 1) is the number of
4632          *    SGL elements that have been processed (stored in the
4633          *    main frame).
4634          * 3. ChainOffset value should be in units of double-words (4
4635          *    bytes) so the last value should be divided by 4.
4636          */
4637         ddi_put8(acc_hdl, &frame->ChainOffset,
4638             (sizeof (MPI2_SCSI_IO_REQUEST) -
4639             sizeof (MPI2_SGE_IO_UNION) +
4640             (j - 1) * sizeof (MPI2_SGE_SIMPLE64)) >> 2);
4641         sgechain = (pMpi2SGEChain64_t)sge;


4646 
4647         /*
4648          * The size of the next frame is the accurate size of space
4649          * (in bytes) used to store the SGL elements. j is the counter
4650          * of SGL elements. (j - 1) is the number of SGL elements that
4651          * have been processed (stored in frames).
4652          */
4653         if (frames >= 2) {
4654                 chainlength = mpt->m_req_frame_size /
4655                     sizeof (MPI2_SGE_SIMPLE64) *
4656                     sizeof (MPI2_SGE_SIMPLE64);
4657         } else {
4658                 chainlength = ((cookiec - (j - 1)) *
4659                     sizeof (MPI2_SGE_SIMPLE64));
4660         }
4661 
4662         p = cmd->cmd_extra_frames;
4663 
4664         ddi_put16(acc_hdl, &sgechain->Length, chainlength);
4665         ddi_put32(acc_hdl, &sgechain->Address.Low,
4666             (p->m_phys_addr&0xffffffffull));
4667         ddi_put32(acc_hdl, &sgechain->Address.High, p->m_phys_addr>>32);

4668 
4669         /*
4670          * If there are more than 2 frames left we have to
4671          * fill in the next chain offset to the location of
4672          * the chain element in the next frame.
4673          * sgemax is the number of simple elements in an extra
4674          * frame. Note that the value NextChainOffset should be
4675          * in double-words (4 bytes).
4676          */
4677         if (frames >= 2) {
4678                 ddi_put8(acc_hdl, &sgechain->NextChainOffset,
4679                     (sgemax * sizeof (MPI2_SGE_SIMPLE64)) >> 2);
4680         } else {
4681                 ddi_put8(acc_hdl, &sgechain->NextChainOffset, 0);
4682         }
4683 
4684         /*
4685          * Jump to next frame;
4686          * Starting here, chain buffers go into the per command SGL.
4687          * This buffer is allocated when chain buffers are needed.


4705                          * and we have more SGE's to fill in
4706                          * we have to fill the final entry
4707                          * with a chain element and then
4708                          * continue to the next frame
4709                          */
4710                         if ((l == (sgemax + 1)) && (k != frames)) {
4711                                 sgechain = (pMpi2SGEChain64_t)sge;
4712                                 j--;
4713                                 chainflags = (
4714                                     MPI2_SGE_FLAGS_CHAIN_ELEMENT |
4715                                     MPI2_SGE_FLAGS_SYSTEM_ADDRESS |
4716                                     MPI2_SGE_FLAGS_64_BIT_ADDRESSING);
4717                                 ddi_put8(p->m_acc_hdl,
4718                                     &sgechain->Flags, chainflags);
4719                                 /*
4720                                  * k is the frame counter and (k + 1)
4721                                  * is the number of the next frame.
4722                                  * Note that frames are in contiguous
4723                                  * memory space.
4724                                  */
4725                                 nframe_phys_addr = p->m_phys_addr +
4726                                     (mpt->m_req_frame_size * k);
4727                                 ddi_put32(p->m_acc_hdl,
4728                                     &sgechain->Address.Low,
4729                                     nframe_phys_addr&0xffffffffull);

4730                                 ddi_put32(p->m_acc_hdl,
4731                                     &sgechain->Address.High,
4732                                     nframe_phys_addr>>32);
4733 
4734                                 /*
4735                                  * If there are more than 2 frames left
4736                                  * we have to next chain offset to
4737                                  * the location of the chain element
4738                                  * in the next frame and fill in the
4739                                  * length of the next chain
4740                                  */
4741                                 if ((frames - k) >= 2) {
4742                                         ddi_put8(p->m_acc_hdl,
4743                                             &sgechain->NextChainOffset,
4744                                             (sgemax *
4745                                             sizeof (MPI2_SGE_SIMPLE64))
4746                                             >> 2);
4747                                         ddi_put16(p->m_acc_hdl,
4748                                             &sgechain->Length,
4749                                             mpt->m_req_frame_size /
4750                                             sizeof (MPI2_SGE_SIMPLE64) *
4751                                             sizeof (MPI2_SGE_SIMPLE64));
4752                                 } else {


4815                         if (cmd->cmd_flags & CFLAG_DMASEND) {
4816                                 flags |=
4817                                     (MPI2_SGE_FLAGS_HOST_TO_IOC <<
4818                                     MPI2_SGE_FLAGS_SHIFT);
4819                         } else {
4820                                 flags |=
4821                                     (MPI2_SGE_FLAGS_IOC_TO_HOST <<
4822                                     MPI2_SGE_FLAGS_SHIFT);
4823                         }
4824                         ddi_put32(p->m_acc_hdl,
4825                             &sge->FlagsLength, flags);
4826                         dmap++;
4827                         sge++;
4828                 }
4829         }
4830 
4831         /*
4832          * Sync DMA with the chain buffers that were just created
4833          */
4834         (void) ddi_dma_sync(p->m_dma_hdl, 0, 0, DDI_DMA_SYNC_FORDEV);

4835 }
4836 
4837 static void
4838 mptsas_ieee_sge_mainframe(mptsas_cmd_t *cmd, pMpi2SCSIIORequest_t frame,
4839     ddi_acc_handle_t acc_hdl, uint_t cookiec,
4840     uint8_t end_flag)



4841 {
4842         pMpi2IeeeSgeSimple64_t  ieeesge;
4843         mptti_t                 *dmap;
4844         uint8_t                 flags;
4845 
4846         dmap = cmd->cmd_sg;
4847 
4848         NDBG1(("mptsas_ieee_sge_mainframe: cookiec=%d, %s", cookiec,
4849             cmd->cmd_flags & CFLAG_DMASEND?"Out":"In"));
4850 
4851         ieeesge = (pMpi2IeeeSgeSimple64_t)(&frame->SGL);
4852         while (cookiec--) {
4853                 ddi_put32(acc_hdl, &ieeesge->Address.Low,
4854                     dmap->addr.address64.Low);
4855                 ddi_put32(acc_hdl, &ieeesge->Address.High,
4856                     dmap->addr.address64.High);
4857                 ddi_put32(acc_hdl, &ieeesge->Length, dmap->count);
4858                 NDBG1(("mptsas_ieee_sge_mainframe: len=%d, high=0x%x",
4859                     dmap->count, dmap->addr.address64.High));
4860                 flags = (MPI2_IEEE_SGE_FLAGS_SIMPLE_ELEMENT |
4861                     MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR);
4862 
4863                 /*
4864                  * If this is the last cookie, we set the flags
4865                  * to indicate so










4866                  */
4867                 if (cookiec == 0) {
4868                         flags |= end_flag;




4869                 }
4870 


4871                 /*
4872                  * XXX: Hmmm, what about the direction based on
4873                  * cmd->cmd_flags & CFLAG_DMASEND?
4874                  */
4875                 ddi_put8(acc_hdl, &ieeesge->Flags, flags);
4876                 dmap++;
4877                 ieeesge++;
4878         }
4879 }

4880 
4881 static void
4882 mptsas_ieee_sge_chain(mptsas_t *mpt, mptsas_cmd_t *cmd,
4883     pMpi2SCSIIORequest_t frame, ddi_acc_handle_t acc_hdl)
4884 {
4885         pMpi2IeeeSgeSimple64_t  ieeesge;
4886         pMpi25IeeeSgeChain64_t  ieeesgechain;
4887         uint64_t                nframe_phys_addr;
4888         uint_t                  cookiec;
4889         mptti_t                 *dmap;
4890         uint8_t                 flags;
4891         int                     i, j, k, l, frames, sgemax;
4892         int                     temp, maxframe_sges;
4893         uint8_t                 chainflags;
4894         uint32_t                chainlength;
4895         mptsas_cache_frames_t   *p;
4896 
4897         cookiec = cmd->cmd_cookiec;
4898 
4899         NDBG1(("mptsas_ieee_sge_chain: cookiec=%d", cookiec));
4900 
4901         /*
4902          * Hereby we start to deal with multiple frames.
4903          * The process is as follows:
4904          * 1. Determine how many frames are needed for SGL element
4905          *    storage; Note that all frames are stored in contiguous
4906          *    memory space and in 64-bit DMA mode each element is
4907          *    4 double-words (16 bytes) long.
4908          * 2. Fill up the main frame. We need to do this separately
4909          *    since it contains the SCSI IO request header and needs
4910          *    dedicated processing. Note that the last 4 double-words
4911          *    of the SCSI IO header is for SGL element storage
4912          *    (MPI2_SGE_IO_UNION).
4913          * 3. Fill the chain element in the main frame, so the DMA
4914          *    engine can use the following frames.
4915          * 4. Enter a loop to fill the remaining frames. Note that the
4916          *    last frame contains no chain element.  The remaining
4917          *    frames go into the mpt SGL buffer allocated on the fly,
4918          *    not immediately following the main message frame, as in
4919          *    Gen1.
4920          * Some restrictions:
4921          * 1. For 64-bit DMA, the simple element and chain element
4922          *    are both of 4 double-words (16 bytes) in size, even
4923          *    though all frames are stored in the first 4G of mem
4924          *    range and the higher 32-bits of the address are always 0.
4925          * 2. On some controllers (like the 1064/1068), a frame can
4926          *    hold SGL elements with the last 1 or 2 double-words
4927          *    (4 or 8 bytes) un-used. On these controllers, we should
4928          *    recognize that there's not enough room for another SGL
4929          *    element and move the sge pointer to the next frame.
4930          */
4931 
4932         /*
4933          * Sgemax is the number of SGE's that will fit
4934          * each extra frame and frames is total
4935          * number of frames we'll need.  1 sge entry per
4936          * frame is reseverd for the chain element thus the -1 below.
4937          */
4938         sgemax = ((mpt->m_req_frame_size / sizeof (MPI2_IEEE_SGE_SIMPLE64))
4939             - 1);
4940         maxframe_sges = MPTSAS_MAX_FRAME_SGES64(mpt);
4941         temp = (cookiec - (maxframe_sges - 1)) / sgemax;
4942 
4943         /*
4944          * A little check to see if we need to round up the number
4945          * of frames we need
4946          */
4947         if ((cookiec - (maxframe_sges - 1)) - (temp * sgemax) > 1) {
4948                 frames = (temp + 1);
4949         } else {
4950                 frames = temp;
4951         }
4952         NDBG1(("mptsas_ieee_sge_chain: temp=%d, frames=%d", temp, frames));
4953         dmap = cmd->cmd_sg;
4954         ieeesge = (pMpi2IeeeSgeSimple64_t)(&frame->SGL);
4955 
4956         /*
4957          * First fill in the main frame
4958          */
4959         j = maxframe_sges - 1;
4960         mptsas_ieee_sge_mainframe(cmd, frame, acc_hdl, j, 0);
4961         dmap += j;
4962         ieeesge += j;
4963         j++;
4964 
4965         /*
4966          * Fill in the chain element in the main frame.
4967          * About calculation on ChainOffset:
4968          * 1. Struct msg_scsi_io_request has 4 double-words (16 bytes)
4969          *    in the end reserved for SGL element storage
4970          *    (MPI2_SGE_IO_UNION); we should count it in our
4971          *    calculation.  See its definition in the header file.
4972          * 2. Constant j is the counter of the current SGL element
4973          *    that will be processed, and (j - 1) is the number of
4974          *    SGL elements that have been processed (stored in the
4975          *    main frame).
4976          * 3. ChainOffset value should be in units of quad-words (16
4977          *    bytes) so the last value should be divided by 16.
4978          */
4979         ddi_put8(acc_hdl, &frame->ChainOffset,
4980             (sizeof (MPI2_SCSI_IO_REQUEST) -
4981             sizeof (MPI2_SGE_IO_UNION) +
4982             (j - 1) * sizeof (MPI2_IEEE_SGE_SIMPLE64)) >> 4);
4983         ieeesgechain = (pMpi25IeeeSgeChain64_t)ieeesge;
4984         chainflags = (MPI2_IEEE_SGE_FLAGS_CHAIN_ELEMENT |
4985             MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR);
4986         ddi_put8(acc_hdl, &ieeesgechain->Flags, chainflags);
4987 
4988         /*
4989          * The size of the next frame is the accurate size of space
4990          * (in bytes) used to store the SGL elements. j is the counter
4991          * of SGL elements. (j - 1) is the number of SGL elements that
4992          * have been processed (stored in frames).
4993          */
4994         if (frames >= 2) {
4995                 chainlength = mpt->m_req_frame_size /
4996                     sizeof (MPI2_IEEE_SGE_SIMPLE64) *
4997                     sizeof (MPI2_IEEE_SGE_SIMPLE64);
4998         } else {
4999                 chainlength = ((cookiec - (j - 1)) *
5000                     sizeof (MPI2_IEEE_SGE_SIMPLE64));
5001         }
5002 
5003         p = cmd->cmd_extra_frames;
5004 
5005         ddi_put32(acc_hdl, &ieeesgechain->Length, chainlength);
5006         ddi_put32(acc_hdl, &ieeesgechain->Address.Low,
5007             p->m_phys_addr&0xffffffffull);
5008         ddi_put32(acc_hdl, &ieeesgechain->Address.High, p->m_phys_addr>>32);
5009 
5010         /*
5011          * If there are more than 2 frames left we have to
5012          * fill in the next chain offset to the location of
5013          * the chain element in the next frame.
5014          * sgemax is the number of simple elements in an extra
5015          * frame. Note that the value NextChainOffset should be
5016          * in double-words (4 bytes).
5017          */
5018         if (frames >= 2) {
5019                 ddi_put8(acc_hdl, &ieeesgechain->NextChainOffset,
5020                     (sgemax * sizeof (MPI2_IEEE_SGE_SIMPLE64)) >> 4);
5021         } else {
5022                 ddi_put8(acc_hdl, &ieeesgechain->NextChainOffset, 0);
5023         }
5024 
5025         /*
5026          * Jump to next frame;
5027          * Starting here, chain buffers go into the per command SGL.
5028          * This buffer is allocated when chain buffers are needed.
5029          */
5030         ieeesge = (pMpi2IeeeSgeSimple64_t)p->m_frames_addr;
5031         i = cookiec;
5032 
5033         /*
5034          * Start filling in frames with SGE's.  If we
5035          * reach the end of frame and still have SGE's
5036          * to fill we need to add a chain element and
5037          * use another frame.  j will be our counter
5038          * for what cookie we are at and i will be
5039          * the total cookiec. k is the current frame
5040          */
5041         for (k = 1; k <= frames; k++) {
5042                 for (l = 1; (l <= (sgemax + 1)) && (j <= i); j++, l++) {
5043 
5044                         /*
5045                          * If we have reached the end of frame
5046                          * and we have more SGE's to fill in
5047                          * we have to fill the final entry
5048                          * with a chain element and then
5049                          * continue to the next frame
5050                          */
5051                         if ((l == (sgemax + 1)) && (k != frames)) {
5052                                 ieeesgechain = (pMpi25IeeeSgeChain64_t)ieeesge;
5053                                 j--;
5054                                 chainflags =
5055                                     MPI2_IEEE_SGE_FLAGS_CHAIN_ELEMENT |
5056                                     MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR;
5057                                 ddi_put8(p->m_acc_hdl,
5058                                     &ieeesgechain->Flags, chainflags);
5059                                 /*
5060                                  * k is the frame counter and (k + 1)
5061                                  * is the number of the next frame.
5062                                  * Note that frames are in contiguous
5063                                  * memory space.
5064                                  */
5065                                 nframe_phys_addr = p->m_phys_addr +
5066                                     (mpt->m_req_frame_size * k);
5067                                 ddi_put32(p->m_acc_hdl,
5068                                     &ieeesgechain->Address.Low,
5069                                     nframe_phys_addr&0xffffffffull);
5070                                 ddi_put32(p->m_acc_hdl,
5071                                     &ieeesgechain->Address.High,
5072                                     nframe_phys_addr>>32);
5073 
5074                                 /*
5075                                  * If there are more than 2 frames left
5076                                  * we have to next chain offset to
5077                                  * the location of the chain element
5078                                  * in the next frame and fill in the
5079                                  * length of the next chain
5080                                  */
5081                                 if ((frames - k) >= 2) {
5082                                         ddi_put8(p->m_acc_hdl,
5083                                             &ieeesgechain->NextChainOffset,
5084                                             (sgemax *
5085                                             sizeof (MPI2_IEEE_SGE_SIMPLE64))
5086                                             >> 4);
5087                                         ddi_put32(p->m_acc_hdl,
5088                                             &ieeesgechain->Length,
5089                                             mpt->m_req_frame_size /
5090                                             sizeof (MPI2_IEEE_SGE_SIMPLE64) *
5091                                             sizeof (MPI2_IEEE_SGE_SIMPLE64));
5092                                 } else {
5093                                         /*
5094                                          * This is the last frame. Set
5095                                          * the NextChainOffset to 0 and
5096                                          * Length is the total size of
5097                                          * all remaining simple elements
5098                                          */
5099                                         ddi_put8(p->m_acc_hdl,
5100                                             &ieeesgechain->NextChainOffset,
5101                                             0);
5102                                         ddi_put32(p->m_acc_hdl,
5103                                             &ieeesgechain->Length,
5104                                             (cookiec - j) *
5105                                             sizeof (MPI2_IEEE_SGE_SIMPLE64));
5106                                 }
5107 
5108                                 /* Jump to the next frame */
5109                                 ieeesge = (pMpi2IeeeSgeSimple64_t)
5110                                     ((char *)p->m_frames_addr +
5111                                     (int)mpt->m_req_frame_size * k);
5112 
5113                                 continue;
5114                         }
5115 
5116                         ddi_put32(p->m_acc_hdl,
5117                             &ieeesge->Address.Low,
5118                             dmap->addr.address64.Low);
5119                         ddi_put32(p->m_acc_hdl,
5120                             &ieeesge->Address.High,
5121                             dmap->addr.address64.High);
5122                         ddi_put32(p->m_acc_hdl,
5123                             &ieeesge->Length, dmap->count);
5124                         flags = (MPI2_IEEE_SGE_FLAGS_SIMPLE_ELEMENT |
5125                             MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR);
5126 
5127                         /*
5128                          * If we are at the end of the frame and
5129                          * there is another frame to fill in
5130                          * do we need to do anything?
5131                          * if ((l == sgemax) && (k != frames)) {
5132                          * }
5133                          */
5134 
5135                         /*
5136                          * If this is the final cookie set end of list.
5137                          */
5138                         if (j == i) {
5139                                 flags |= MPI25_IEEE_SGE_FLAGS_END_OF_LIST;
5140                         }
5141 
5142                         ddi_put8(p->m_acc_hdl, &ieeesge->Flags, flags);
5143                         dmap++;
5144                         ieeesge++;
5145                 }
5146         }
5147 
5148         /*
5149          * Sync DMA with the chain buffers that were just created
5150          */
5151         (void) ddi_dma_sync(p->m_dma_hdl, 0, 0, DDI_DMA_SYNC_FORDEV);
5152 }
5153 
5154 static void
5155 mptsas_sge_setup(mptsas_t *mpt, mptsas_cmd_t *cmd, uint32_t *control,
5156     pMpi2SCSIIORequest_t frame, ddi_acc_handle_t acc_hdl)
5157 {
5158         ASSERT(cmd->cmd_flags & CFLAG_DMAVALID);
5159 
5160         NDBG1(("mptsas_sge_setup: cookiec=%d", cmd->cmd_cookiec));
5161 
5162         /*
5163          * Set read/write bit in control.
5164          */
5165         if (cmd->cmd_flags & CFLAG_DMASEND) {
5166                 *control |= MPI2_SCSIIO_CONTROL_WRITE;
5167         } else {
5168                 *control |= MPI2_SCSIIO_CONTROL_READ;
5169         }
5170 
5171         ddi_put32(acc_hdl, &frame->DataLength, cmd->cmd_dmacount);
5172 
5173         /*
5174          * We have 4 cases here.  First where we can fit all the
5175          * SG elements into the main frame, and the case
5176          * where we can't. The SG element is also different when using
5177          * MPI2.5 interface.
5178          * If we have more cookies than we can attach to a frame
5179          * we will need to use a chain element to point
5180          * a location of memory where the rest of the S/G
5181          * elements reside.
5182          */
5183         if (cmd->cmd_cookiec <= MPTSAS_MAX_FRAME_SGES64(mpt)) {
5184                 if (mpt->m_MPI25) {
5185                         mptsas_ieee_sge_mainframe(cmd, frame, acc_hdl,
5186                             cmd->cmd_cookiec,
5187                             MPI25_IEEE_SGE_FLAGS_END_OF_LIST);
5188                 } else {
5189                         mptsas_sge_mainframe(cmd, frame, acc_hdl,
5190                             cmd->cmd_cookiec,
5191                             ((uint32_t)(MPI2_SGE_FLAGS_LAST_ELEMENT
5192                             | MPI2_SGE_FLAGS_END_OF_BUFFER
5193                             | MPI2_SGE_FLAGS_END_OF_LIST) <<
5194                             MPI2_SGE_FLAGS_SHIFT));
5195                 }
5196         } else {
5197                 if (mpt->m_MPI25) {
5198                         mptsas_ieee_sge_chain(mpt, cmd, frame, acc_hdl);
5199                 } else {
5200                         mptsas_sge_chain(mpt, cmd, frame, acc_hdl);
5201                 }
5202         }
5203 }
5204 
5205 /*
5206  * Interrupt handling
5207  * Utility routine.  Poll for status of a command sent to HBA
5208  * without interrupts (a FLAG_NOINTR command).
5209  */
5210 int
5211 mptsas_poll(mptsas_t *mpt, mptsas_cmd_t *poll_cmd, int polltime)
5212 {
5213         int             rval = TRUE;
5214         uint32_t        int_mask;
5215 
5216         NDBG5(("mptsas_poll: cmd=0x%p, flags 0x%x", (void *)poll_cmd,
5217             poll_cmd->cmd_flags));
5218 
5219         /*
5220          * Get the current interrupt mask and disable interrupts.  When
5221          * re-enabling ints, set mask to saved value.
5222          */
5223         int_mask = ddi_get32(mpt->m_datap, &mpt->m_reg->HostInterruptMask);
5224         MPTSAS_DISABLE_INTR(mpt);
5225 
5226         mpt->m_polled_intr = 1;
5227 
5228         if ((poll_cmd->cmd_flags & CFLAG_TM_CMD) == 0) {
5229                 mptsas_restart_hba(mpt);
5230         }
5231 
5232         /*
5233          * Wait, using drv_usecwait(), long enough for the command to
5234          * reasonably return from the target if the target isn't
5235          * "dead".  A polled command may well be sent from scsi_poll, and
5236          * there are retries built in to scsi_poll if the transport
5237          * accepted the packet (TRAN_ACCEPT).  scsi_poll waits 1 second
5238          * and retries the transport up to scsi_poll_busycnt times
5239          * (currently 60) if
5240          * 1. pkt_reason is CMD_INCOMPLETE and pkt_state is 0, or
5241          * 2. pkt_reason is CMD_CMPLT and *pkt_scbp has STATUS_BUSY
5242          *
5243          * limit the waiting to avoid a hang in the event that the
5244          * cmd never gets started but we are still receiving interrupts
5245          */
5246         while (!(poll_cmd->cmd_flags & CFLAG_FINISHED)) {
5247                 if (mptsas_wait_intr(mpt, polltime) == FALSE) {
5248                         NDBG5(("mptsas_poll: command incomplete"));
5249                         rval = FALSE;
5250                         break;
5251                 }
5252         }
5253 
5254         if (rval == FALSE) {
5255 
5256                 /*
5257                  * this isn't supposed to happen, the hba must be wedged
5258                  * Mark this cmd as a timeout.
5259                  */
5260                 mptsas_set_pkt_reason(mpt, poll_cmd, CMD_TIMEOUT,
5261                     (STAT_TIMEOUT|STAT_ABORTED));
5262 
5263                 if (poll_cmd->cmd_queued == FALSE) {
5264 
5265                         NDBG5(("mptsas_poll: not on waitq"));
5266 
5267                         poll_cmd->cmd_pkt->pkt_state |=
5268                             (STATE_GOT_BUS|STATE_GOT_TARGET|STATE_SENT_CMD);
5269                 } else {
5270 
5271                         /* find and remove it from the waitq */
5272                         NDBG5(("mptsas_poll: delete from waitq"));
5273                         mptsas_waitq_delete(mpt, poll_cmd);
5274                 }
5275 
5276         }
5277         mptsas_fma_check(mpt, poll_cmd);
5278 
5279         /*
5280          * Clear polling flag, re-enable interrupts.
5281          */
5282         mpt->m_polled_intr = 0;
5283         ddi_put32(mpt->m_datap, &mpt->m_reg->HostInterruptMask, int_mask);
5284 
5285         /*
5286          * If there are queued cmd, start them now.
5287          */
5288         if (mpt->m_waitq != NULL) {
5289                 mptsas_restart_waitq(mpt);
5290         }
5291 
5292         NDBG5(("mptsas_poll: done"));
5293         return (rval);
5294 }
5295 
5296 /*
5297  * Used for polling cmds and TM function
5298  */
5299 static int
5300 mptsas_wait_intr(mptsas_t *mpt, int polltime)
5301 {
5302         int                             cnt, rval = FALSE;
5303         pMpi2ReplyDescriptorsUnion_t    reply_desc_union;
5304         mptsas_reply_pqueue_t           *rpqp;
5305 
5306         NDBG5(("mptsas_wait_intr"));
5307         ASSERT(mutex_owned(&mpt->m_mutex));

5308 
5309         /*
5310          * Keep polling for at least (polltime * 1000) seconds

5311          */
5312         rpqp = mpt->m_rep_post_queues;

5313 
5314         /*
5315          * Drop the main mutex and grab the mutex for reply queue 0
5316          */
5317         mutex_exit(&mpt->m_mutex);
5318         mutex_enter(&rpqp->rpq_mutex);
5319         for (cnt = 0; cnt < polltime; cnt++) {
5320                 (void) ddi_dma_sync(mpt->m_dma_post_queue_hdl, 0, 0,
5321                     DDI_DMA_SYNC_FORCPU);
5322 
5323                 /*
5324                  * Polled requests should only come back through
5325                  * the first interrupt.
5326                  */
5327                 reply_desc_union = (pMpi2ReplyDescriptorsUnion_t)
5328                     MPTSAS_GET_NEXT_REPLY(rpqp, rpqp->rpq_index);
5329 
5330                 if (ddi_get32(mpt->m_acc_post_queue_hdl,
5331                     &reply_desc_union->Words.Low) == 0xFFFFFFFF ||
5332                     ddi_get32(mpt->m_acc_post_queue_hdl,
5333                     &reply_desc_union->Words.High) == 0xFFFFFFFF) {
5334                         drv_usecwait(1000);
5335                         continue;
5336                 }
5337 
5338                 /*
5339                  * The reply is valid, process it according to its
5340                  * type.
5341                  */
5342                 mptsas_process_intr(mpt, rpqp, reply_desc_union);











5343 
5344                 /*
5345                  * Clear the reply descriptor for re-use.
5346                  */
5347                 ddi_put64(mpt->m_acc_post_queue_hdl,
5348                     &((uint64_t *)(void *)rpqp->rpq_queue)[rpqp->rpq_index],
5349                     0xFFFFFFFFFFFFFFFF);
5350                 (void) ddi_dma_sync(mpt->m_dma_post_queue_hdl, 0, 0,
5351                     DDI_DMA_SYNC_FORDEV);
5352 
5353                 if (++rpqp->rpq_index == mpt->m_post_queue_depth) {
5354                         rpqp->rpq_index = 0;
5355                 }
5356 
5357                 /*
5358                  * Update the reply index
5359                  */
5360                 ddi_put32(mpt->m_datap,
5361                     &mpt->m_reg->ReplyPostHostIndex, rpqp->rpq_index);
5362                 rval = TRUE;
5363                 break;
5364         }
5365 
5366         mutex_exit(&rpqp->rpq_mutex);
5367         mutex_enter(&mpt->m_mutex);
5368 
5369         return (rval);
5370 }
5371 
5372 static void
5373 mptsas_handle_scsi_io_success(mptsas_t *mpt,
5374     mptsas_reply_pqueue_t *rpqp,
5375     pMpi2ReplyDescriptorsUnion_t reply_desc)
5376 {
5377         pMpi2SCSIIOSuccessReplyDescriptor_t     scsi_io_success;
5378         uint16_t                                SMID;
5379         mptsas_slots_t                          *slots = mpt->m_active;
5380         mptsas_cmd_t                            *cmd = NULL;
5381         struct scsi_pkt                         *pkt;
5382 


5383         scsi_io_success = (pMpi2SCSIIOSuccessReplyDescriptor_t)reply_desc;
5384         SMID = ddi_get16(mpt->m_acc_post_queue_hdl, &scsi_io_success->SMID);
5385 
5386         /*
5387          * This is a success reply so just complete the IO.  First, do a sanity
5388          * check on the SMID.  The final slot is used for TM requests, which
5389          * would not come into this reply handler.
5390          */
5391         if ((SMID == 0) || (SMID > slots->m_n_normal)) {
5392                 mptsas_log(mpt, CE_WARN, "?Received invalid SMID of %d\n",
5393                     SMID);
5394                 ddi_fm_service_impact(mpt->m_dip, DDI_SERVICE_UNAFFECTED);
5395                 return;
5396         }
5397 
5398         cmd = slots->m_slot[SMID];
5399 
5400         /*
5401          * print warning and return if the slot is empty
5402          */
5403         if (cmd == NULL) {
5404                 mptsas_log(mpt, CE_WARN, "?NULL command for successful SCSI IO "
5405                     "in slot %d", SMID);
5406                 return;
5407         }
5408         ASSERT(cmd->cmd_rpqidx == rpqp->rpq_num);
5409 
5410         pkt = CMD2PKT(cmd);
5411         pkt->pkt_state |= (STATE_GOT_BUS | STATE_GOT_TARGET | STATE_SENT_CMD |
5412             STATE_GOT_STATUS);
5413         if (cmd->cmd_flags & CFLAG_DMAVALID) {
5414                 pkt->pkt_state |= STATE_XFERRED_DATA;
5415         }
5416         pkt->pkt_resid = 0;
5417 
5418         if (cmd->cmd_flags & CFLAG_PASSTHRU) {
5419                 cmd->cmd_flags |= CFLAG_FINISHED;
5420                 cv_broadcast(&mpt->m_passthru_cv);
5421                 return;
5422         }
5423         if (!(cmd->cmd_flags & CFLAG_TM_CMD)) {
5424                 if (cmd->cmd_flags & CFLAG_CMDIOC) {
5425                         mutex_enter(&mpt->m_mutex);
5426                         mptsas_remove_cmd(mpt, cmd);
5427                         mutex_exit(&mpt->m_mutex);
5428                 } else {
5429 #ifdef MPTSAS_DEBUG
5430                         /*
5431                          * In order to test timeout for a command set
5432                          * mptsas_test_timeout via mdb to avoid completion
5433                          * processing here.
5434                          */
5435                         if (mptsas_test_timeout) {
5436                                 mptsas_test_timeout = 0;
5437                                 return;
5438                         }
5439 #endif
5440                         /*
5441                          * This is the normal path, avoid grabbing
5442                          * the m_mutex.
5443                          */
5444                         mptsas_remove_cmd_nomtx(mpt, cmd);
5445                 }
5446         }
5447 
5448         if (cmd->cmd_flags & CFLAG_RETRY) {
5449                 /*
5450                  * The target returned QFULL or busy, do not add tihs
5451                  * pkt to the doneq since the hba will retry
5452                  * this cmd.
5453                  *
5454                  * The pkt has already been resubmitted in
5455                  * mptsas_handle_qfull() or in mptsas_check_scsi_io_error().
5456                  * Remove this cmd_flag here.
5457                  */
5458                 cmd->cmd_flags &= ~CFLAG_RETRY;
5459         } else {
5460                 mptsas_rpdoneq_add(mpt, rpqp, cmd);
5461         }
5462 }
5463 
5464 static void
5465 mptsas_handle_address_reply(mptsas_t *mpt,
5466     pMpi2ReplyDescriptorsUnion_t reply_desc)
5467 {
5468         pMpi2AddressReplyDescriptor_t   address_reply;
5469         pMPI2DefaultReply_t             reply;
5470         mptsas_fw_diagnostic_buffer_t   *pBuffer;
5471         uint32_t                        reply_addr, reply_frame_dma_baseaddr;
5472         uint16_t                        SMID, iocstatus;
5473         mptsas_slots_t                  *slots = mpt->m_active;
5474         mptsas_cmd_t                    *cmd = NULL;
5475         uint8_t                         function, buffer_type;
5476         m_replyh_arg_t                  *args;
5477         int                             reply_frame_no;
5478 
5479         ASSERT(mutex_owned(&mpt->m_mutex));
5480 
5481         address_reply = (pMpi2AddressReplyDescriptor_t)reply_desc;
5482         reply_addr = ddi_get32(mpt->m_acc_post_queue_hdl,
5483             &address_reply->ReplyFrameAddress);
5484         SMID = ddi_get16(mpt->m_acc_post_queue_hdl, &address_reply->SMID);
5485 
5486         /*
5487          * If reply frame is not in the proper range we should ignore this
5488          * message and exit the interrupt handler.
5489          */
5490         reply_frame_dma_baseaddr = mpt->m_reply_frame_dma_addr & 0xfffffffful;
5491         if ((reply_addr < reply_frame_dma_baseaddr) ||
5492             (reply_addr >= (reply_frame_dma_baseaddr +
5493             (mpt->m_reply_frame_size * mpt->m_max_replies))) ||
5494             ((reply_addr - reply_frame_dma_baseaddr) %
5495             mpt->m_reply_frame_size != 0)) {
5496                 mptsas_log(mpt, CE_WARN, "?Received invalid reply frame "
5497                     "address 0x%x\n", reply_addr);
5498                 ddi_fm_service_impact(mpt->m_dip, DDI_SERVICE_UNAFFECTED);
5499                 return;
5500         }
5501 
5502         (void) ddi_dma_sync(mpt->m_dma_reply_frame_hdl, 0, 0,
5503             DDI_DMA_SYNC_FORCPU);
5504         reply = (pMPI2DefaultReply_t)(mpt->m_reply_frame + (reply_addr -
5505             reply_frame_dma_baseaddr));
5506         function = ddi_get8(mpt->m_acc_reply_frame_hdl, &reply->Function);
5507 
5508         NDBG31(("mptsas_handle_address_reply: function 0x%x, reply_addr=0x%x",
5509             function, reply_addr));
5510 
5511         /*
5512          * don't get slot information and command for events since these values
5513          * don't exist
5514          */
5515         if ((function != MPI2_FUNCTION_EVENT_NOTIFICATION) &&
5516             (function != MPI2_FUNCTION_DIAG_BUFFER_POST)) {
5517                 /*
5518                  * This could be a TM reply, which use the last allocated SMID,
5519                  * so allow for that.
5520                  */
5521                 if ((SMID == 0) || (SMID > (slots->m_n_normal + 1))) {
5522                         mptsas_log(mpt, CE_WARN, "?Received invalid SMID of "
5523                             "%d\n", SMID);
5524                         ddi_fm_service_impact(mpt->m_dip,
5525                             DDI_SERVICE_UNAFFECTED);
5526                         return;
5527                 }
5528 
5529                 cmd = slots->m_slot[SMID];
5530 
5531                 /*
5532                  * print warning and return if the slot is empty
5533                  */
5534                 if (cmd == NULL) {
5535                         mptsas_log(mpt, CE_WARN, "?NULL command for address "
5536                             "reply in slot %d", SMID);
5537                         return;
5538                 }
5539                 if ((cmd->cmd_flags &
5540                     (CFLAG_PASSTHRU | CFLAG_CONFIG | CFLAG_FW_DIAG))) {

5541                         cmd->cmd_rfm = reply_addr;
5542                         cmd->cmd_flags |= CFLAG_FINISHED;
5543                         cv_broadcast(&mpt->m_passthru_cv);
5544                         cv_broadcast(&mpt->m_config_cv);
5545                         cv_broadcast(&mpt->m_fw_diag_cv);
5546                         return;
5547                 } else if (!(cmd->cmd_flags & CFLAG_FW_CMD)) {
5548                         mptsas_remove_cmd(mpt, cmd);
5549                 }
5550                 NDBG31(("\t\tmptsas_process_intr: slot=%d", SMID));
5551         }
5552         /*
5553          * Depending on the function, we need to handle
5554          * the reply frame (and cmd) differently.
5555          */
5556         switch (function) {
5557         case MPI2_FUNCTION_SCSI_IO_REQUEST:
5558                 mptsas_check_scsi_io_error(mpt, (pMpi2SCSIIOReply_t)reply, cmd);
5559                 break;
5560         case MPI2_FUNCTION_SCSI_TASK_MGMT:
5561                 cmd->cmd_rfm = reply_addr;
5562                 mptsas_check_task_mgt(mpt, (pMpi2SCSIManagementReply_t)reply,
5563                     cmd);
5564                 break;
5565         case MPI2_FUNCTION_FW_DOWNLOAD:
5566                 cmd->cmd_flags |= CFLAG_FINISHED;
5567                 cv_signal(&mpt->m_fw_cv);
5568                 break;
5569         case MPI2_FUNCTION_EVENT_NOTIFICATION:
5570                 reply_frame_no = (reply_addr - reply_frame_dma_baseaddr) /
5571                     mpt->m_reply_frame_size;
5572                 args = &mpt->m_replyh_args[reply_frame_no];
5573                 args->mpt = (void *)mpt;
5574                 args->rfm = reply_addr;
5575 
5576                 /*
5577                  * Record the event if its type is enabled in
5578                  * this mpt instance by ioctl.
5579                  */
5580                 mptsas_record_event(args);
5581 
5582                 /*
5583                  * Handle time critical events
5584                  * NOT_RESPONDING/ADDED only now
5585                  */
5586                 if (mptsas_handle_event_sync(args) == DDI_SUCCESS) {
5587                         /*
5588                          * Would not return main process,
5589                          * just let taskq resolve ack action
5590                          * and ack would be sent in taskq thread


5661 
5662         /*
5663          * Return the reply frame to the free queue.
5664          */
5665         ddi_put32(mpt->m_acc_free_queue_hdl,
5666             &((uint32_t *)(void *)mpt->m_free_queue)[mpt->m_free_index],
5667             reply_addr);
5668         (void) ddi_dma_sync(mpt->m_dma_free_queue_hdl, 0, 0,
5669             DDI_DMA_SYNC_FORDEV);
5670         if (++mpt->m_free_index == mpt->m_free_queue_depth) {
5671                 mpt->m_free_index = 0;
5672         }
5673         ddi_put32(mpt->m_datap, &mpt->m_reg->ReplyFreeHostIndex,
5674             mpt->m_free_index);
5675 
5676         if (cmd->cmd_flags & CFLAG_FW_CMD)
5677                 return;
5678 
5679         if (cmd->cmd_flags & CFLAG_RETRY) {
5680                 /*
5681                  * The target returned QFULL or busy, do not add this
5682                  * pkt to the doneq since the hba will retry
5683                  * this cmd.
5684                  *
5685                  * The pkt has already been resubmitted in
5686                  * mptsas_handle_qfull() or in mptsas_check_scsi_io_error().
5687                  * Remove this cmd_flag here.
5688                  */
5689                 cmd->cmd_flags &= ~CFLAG_RETRY;
5690         } else {
5691                 mptsas_doneq_add(mpt, cmd);
5692         }
5693 }
5694 
5695 #ifdef MPTSAS_DEBUG
5696 static uint8_t mptsas_last_sense[256];
5697 #endif
5698 
5699 static void
5700 mptsas_check_scsi_io_error(mptsas_t *mpt, pMpi2SCSIIOReply_t reply,
5701     mptsas_cmd_t *cmd)
5702 {
5703         uint8_t                 scsi_status, scsi_state;
5704         uint16_t                ioc_status, cmd_rqs_len;
5705         uint32_t                xferred, sensecount, responsedata, loginfo = 0;
5706         struct scsi_pkt         *pkt;
5707         struct scsi_arq_status  *arqstat;

5708         mptsas_target_t         *ptgt = cmd->cmd_tgt_addr;
5709         uint8_t                 *sensedata = NULL;
5710         uint64_t                sas_wwn;
5711         uint8_t                 phy;
5712         char                    wwn_str[MPTSAS_WWN_STRLEN];




5713 
5714         scsi_status = ddi_get8(mpt->m_acc_reply_frame_hdl, &reply->SCSIStatus);
5715         ioc_status = ddi_get16(mpt->m_acc_reply_frame_hdl, &reply->IOCStatus);
5716         scsi_state = ddi_get8(mpt->m_acc_reply_frame_hdl, &reply->SCSIState);
5717         xferred = ddi_get32(mpt->m_acc_reply_frame_hdl, &reply->TransferCount);
5718         sensecount = ddi_get32(mpt->m_acc_reply_frame_hdl, &reply->SenseCount);
5719         responsedata = ddi_get32(mpt->m_acc_reply_frame_hdl,
5720             &reply->ResponseInfo);
5721 
5722         if (ioc_status & MPI2_IOCSTATUS_FLAG_LOG_INFO_AVAILABLE) {
5723                 sas_wwn = ptgt->m_addr.mta_wwn;
5724                 phy = ptgt->m_phynum;
5725                 if (sas_wwn == 0) {
5726                         (void) sprintf(wwn_str, "p%x", phy);
5727                 } else {
5728                         (void) sprintf(wwn_str, "w%016"PRIx64, sas_wwn);
5729                 }
5730                 loginfo = ddi_get32(mpt->m_acc_reply_frame_hdl,
5731                     &reply->IOCLogInfo);
5732                 mptsas_log(mpt, CE_NOTE,
5733                     "?Log info 0x%x received for target %d %s.\n"
5734                     "\tscsi_status=0x%x, ioc_status=0x%x, scsi_state=0x%x",
5735                     loginfo, Tgt(cmd), wwn_str, scsi_status, ioc_status,
5736                     scsi_state);
5737         }
5738 
5739         NDBG31(("\t\tscsi_status=0x%x, ioc_status=0x%x, scsi_state=0x%x",
5740             scsi_status, ioc_status, scsi_state));
5741 
5742         pkt = CMD2PKT(cmd);
5743         *(pkt->pkt_scbp) = scsi_status;
5744 
5745         if (loginfo == 0x31170000) {
5746                 /*
5747                  * if loginfo PL_LOGINFO_CODE_IO_DEVICE_MISSING_DELAY_RETRY
5748                  * 0x31170000 comes, that means the device missing delay
5749                  * is in progressing, the command need retry later.
5750                  */
5751                 *(pkt->pkt_scbp) = STATUS_BUSY;
5752                 return;
5753         }
5754 
5755         if ((scsi_state & MPI2_SCSI_STATE_NO_SCSI_STATUS) &&
5756             ((ioc_status & MPI2_IOCSTATUS_MASK) ==
5757             MPI2_IOCSTATUS_SCSI_DEVICE_NOT_THERE)) {
5758                 pkt->pkt_reason = CMD_INCOMPLETE;
5759                 pkt->pkt_state |= STATE_GOT_BUS;
5760                 mutex_enter(&ptgt->m_t_mutex);
5761                 if (ptgt->m_reset_delay == 0) {
5762                         mptsas_set_throttle(mpt, ptgt,
5763                             DRAIN_THROTTLE);
5764                 }
5765                 mutex_exit(&ptgt->m_t_mutex);
5766                 return;
5767         }
5768 
5769         if (scsi_state & MPI2_SCSI_STATE_RESPONSE_INFO_VALID) {
5770                 responsedata &= 0x000000FF;
5771                 if (responsedata & MPTSAS_SCSI_RESPONSE_CODE_TLR_OFF) {
5772                         mptsas_log(mpt, CE_NOTE, "Do not support the TLR\n");
5773                         pkt->pkt_reason = CMD_TLR_OFF;
5774                         return;
5775                 }
5776         }
5777 
5778 
5779         switch (scsi_status) {
5780         case MPI2_SCSI_STATUS_CHECK_CONDITION:
5781                 (void) ddi_dma_sync(mpt->m_dma_req_sense_hdl, 0, 0,
5782                     DDI_DMA_SYNC_FORCPU);
5783                 pkt->pkt_resid = (cmd->cmd_dmacount - xferred);
5784                 arqstat = (void*)(pkt->pkt_scbp);
5785                 arqstat->sts_rqpkt_status = *((struct scsi_status *)
5786                     (pkt->pkt_scbp));
5787                 pkt->pkt_state |= (STATE_GOT_BUS | STATE_GOT_TARGET |
5788                     STATE_SENT_CMD | STATE_GOT_STATUS | STATE_ARQ_DONE);
5789                 if (cmd->cmd_flags & CFLAG_XARQ) {
5790                         pkt->pkt_state |= STATE_XARQ_DONE;
5791                 }
5792                 if (pkt->pkt_resid != cmd->cmd_dmacount) {
5793                         pkt->pkt_state |= STATE_XFERRED_DATA;
5794                 }
5795                 arqstat->sts_rqpkt_reason = pkt->pkt_reason;
5796                 arqstat->sts_rqpkt_state  = pkt->pkt_state;
5797                 arqstat->sts_rqpkt_state |= STATE_XFERRED_DATA;
5798                 arqstat->sts_rqpkt_statistics = pkt->pkt_statistics;
5799                 sensedata = (uint8_t *)&arqstat->sts_sensedata;
5800 #ifdef MPTSAS_DEBUG
5801                 bcopy((uchar_t *)cmd->cmd_arq_buf, mptsas_last_sense,
5802                     cmd->cmd_rqslen);
5803 #endif
5804                 if (cmd->cmd_extrqslen != 0) {
5805                         cmd_rqs_len = cmd->cmd_extrqslen;
5806                 } else {
5807                         cmd_rqs_len = cmd->cmd_rqslen;
5808                 }
5809                 bcopy((uchar_t *)cmd->cmd_arq_buf, sensedata,
5810                     ((cmd->cmd_rqslen >= sensecount) ? sensecount :
5811                     cmd_rqs_len));
5812                 arqstat->sts_rqpkt_resid = (cmd_rqs_len - sensecount);
5813                 cmd->cmd_flags |= CFLAG_CMDARQ;
5814                 /*
5815                  * Set proper status for pkt if autosense was valid
5816                  */
5817                 if (scsi_state & MPI2_SCSI_STATE_AUTOSENSE_VALID) {
5818                         struct scsi_status zero_status = { 0 };
5819                         arqstat->sts_rqpkt_status = zero_status;
5820                 }
5821 
5822                 /*
5823                  * ASC=0x47 is parity error
5824                  * ASC=0x48 is initiator detected error received
5825                  */
5826                 if ((scsi_sense_key(sensedata) == KEY_ABORTED_COMMAND) &&
5827                     ((scsi_sense_asc(sensedata) == 0x47) ||
5828                     (scsi_sense_asc(sensedata) == 0x48))) {
5829                         mptsas_log(mpt, CE_NOTE, "Aborted_command!");
5830                 }
5831 
5832                 /*


5844                         topo_node = kmem_zalloc(
5845                             sizeof (mptsas_topo_change_list_t),
5846                             KM_NOSLEEP);
5847                         if (topo_node == NULL) {
5848                                 mptsas_log(mpt, CE_NOTE, "No memory"
5849                                     "resource for handle SAS dynamic"
5850                                     "reconfigure.\n");
5851                                 break;
5852                         }
5853                         topo_node->mpt = mpt;
5854                         topo_node->event = MPTSAS_DR_EVENT_RECONFIG_TARGET;
5855                         topo_node->un.phymask = ptgt->m_addr.mta_phymask;
5856                         topo_node->devhdl = ptgt->m_devhdl;
5857                         topo_node->object = (void *)ptgt;
5858                         topo_node->flags = MPTSAS_TOPO_FLAG_LUN_ASSOCIATED;
5859 
5860                         if ((ddi_taskq_dispatch(mpt->m_dr_taskq,
5861                             mptsas_handle_dr,
5862                             (void *)topo_node,
5863                             DDI_NOSLEEP)) != DDI_SUCCESS) {
5864                                 kmem_free(topo_node,
5865                                     sizeof (mptsas_topo_change_list_t));
5866                                 mptsas_log(mpt, CE_NOTE, "mptsas start taskq"
5867                                     "for handle SAS dynamic reconfigure"
5868                                     "failed. \n");
5869                         }
5870                 }
5871                 break;
5872         case MPI2_SCSI_STATUS_GOOD:
5873                 switch (ioc_status & MPI2_IOCSTATUS_MASK) {
5874                 case MPI2_IOCSTATUS_SCSI_DEVICE_NOT_THERE:
5875                         pkt->pkt_reason = CMD_DEV_GONE;
5876                         pkt->pkt_state |= STATE_GOT_BUS;
5877                         mutex_enter(&ptgt->m_t_mutex);
5878                         if (ptgt->m_reset_delay == 0) {
5879                                 mptsas_set_throttle(mpt, ptgt, DRAIN_THROTTLE);
5880                         }
5881                         mutex_exit(&ptgt->m_t_mutex);
5882                         NDBG31(("lost disk for target%d, command:%x",
5883                             Tgt(cmd), pkt->pkt_cdbp[0]));
5884                         break;
5885                 case MPI2_IOCSTATUS_SCSI_DATA_OVERRUN:
5886                         NDBG31(("data overrun: xferred=%d", xferred));
5887                         NDBG31(("dmacount=%d", cmd->cmd_dmacount));
5888                         pkt->pkt_reason = CMD_DATA_OVR;
5889                         pkt->pkt_state |= (STATE_GOT_BUS | STATE_GOT_TARGET
5890                             | STATE_SENT_CMD | STATE_GOT_STATUS
5891                             | STATE_XFERRED_DATA);
5892                         pkt->pkt_resid = 0;
5893                         break;
5894                 case MPI2_IOCSTATUS_SCSI_RESIDUAL_MISMATCH:
5895                 case MPI2_IOCSTATUS_SCSI_DATA_UNDERRUN:
5896                         NDBG31(("data underrun: xferred=%d", xferred));
5897                         NDBG31(("dmacount=%d", cmd->cmd_dmacount));
5898                         pkt->pkt_state |= (STATE_GOT_BUS | STATE_GOT_TARGET
5899                             | STATE_SENT_CMD | STATE_GOT_STATUS);
5900                         pkt->pkt_resid = (cmd->cmd_dmacount - xferred);
5901                         if (pkt->pkt_resid != cmd->cmd_dmacount) {
5902                                 pkt->pkt_state |= STATE_XFERRED_DATA;
5903                         }
5904                         break;
5905                 case MPI2_IOCSTATUS_SCSI_TASK_TERMINATED:
5906                         if (cmd->cmd_active_expiration <= gethrtime()) {
5907                                 /*
5908                                  * When timeout requested, propagate
5909                                  * proper reason and statistics to
5910                                  * target drivers.
5911                                  */
5912                                 mptsas_set_pkt_reason(mpt, cmd, CMD_TIMEOUT,
5913                                     STAT_BUS_RESET | STAT_TIMEOUT);
5914                         } else {
5915                                 mptsas_set_pkt_reason(mpt, cmd, CMD_RESET,
5916                                     STAT_BUS_RESET);
5917                         }
5918                         break;
5919                 case MPI2_IOCSTATUS_SCSI_IOC_TERMINATED:
5920                 case MPI2_IOCSTATUS_SCSI_EXT_TERMINATED:
5921                         mptsas_set_pkt_reason(mpt,
5922                             cmd, CMD_RESET, STAT_DEV_RESET);
5923                         break;
5924                 case MPI2_IOCSTATUS_SCSI_IO_DATA_ERROR:
5925                 case MPI2_IOCSTATUS_SCSI_PROTOCOL_ERROR:
5926                         pkt->pkt_state |= (STATE_GOT_BUS | STATE_GOT_TARGET);
5927                         mptsas_set_pkt_reason(mpt,
5928                             cmd, CMD_TERMINATED, STAT_TERMINATED);
5929                         break;
5930                 case MPI2_IOCSTATUS_INSUFFICIENT_RESOURCES:
5931                 case MPI2_IOCSTATUS_BUSY:
5932                         /*
5933                          * set throttles to drain
5934                          */
5935                         for (ptgt = refhash_first(mpt->m_targets); ptgt != NULL;
5936                             ptgt = refhash_next(mpt->m_targets, ptgt)) {
5937                                 mptsas_set_throttle_mtx(mpt, ptgt,
5938                                     DRAIN_THROTTLE);
5939                         }
5940 
5941                         /*
5942                          * retry command
5943                          */
5944                         mptsas_retry_pkt(mpt, cmd);



5945                         break;
5946                 default:
5947                         mptsas_log(mpt, CE_WARN,
5948                             "unknown ioc_status = %x\n", ioc_status);
5949                         mptsas_log(mpt, CE_CONT, "scsi_state = %x, transfer "
5950                             "count = %x, scsi_status = %x", scsi_state,
5951                             xferred, scsi_status);
5952                         break;
5953                 }
5954                 break;
5955         case MPI2_SCSI_STATUS_TASK_SET_FULL:
5956                 mptsas_handle_qfull(mpt, cmd);
5957                 break;
5958         case MPI2_SCSI_STATUS_BUSY:
5959                 NDBG31(("scsi_status busy received"));
5960                 break;
5961         case MPI2_SCSI_STATUS_RESERVATION_CONFLICT:
5962                 NDBG31(("scsi_status reservation conflict received"));
5963                 break;
5964         default:


6008                  * Check for invalid DevHandle of 0 in case application
6009                  * sends bad command.  DevHandle of 0 could cause problems.
6010                  */
6011                 if (dev_handle == 0) {
6012                         mptsas_log(mpt, CE_WARN, "!Can't flush target with"
6013                             " DevHandle of 0.");
6014                 } else {
6015                         mptsas_flush_target(mpt, dev_handle, Lun(cmd),
6016                             task_type);
6017                 }
6018                 break;
6019         default:
6020                 mptsas_log(mpt, CE_WARN, "Unknown task management type %d.",
6021                     task_type);
6022                 mptsas_log(mpt, CE_WARN, "ioc status = %x", ioc_status);
6023                 break;
6024         }
6025 }
6026 
6027 static void
6028 mptsas_doneq_thread(mptsas_thread_arg_t *arg)
6029 {
6030         mptsas_t                        *mpt = arg->mpt;
6031         uint32_t                        t = arg->t;
6032         mptsas_cmd_t                    *cmd;
6033         struct scsi_pkt                 *pkt;
6034         mptsas_doneq_thread_list_t      *item = &mpt->m_doneq_thread_id[t];
6035 
6036         mutex_enter(&item->mutex);
6037         while (item->flag & MPTSAS_DONEQ_THREAD_ACTIVE) {
6038                 if (!item->dlist.dl_q) {
6039                         cv_wait(&item->cv, &item->mutex);
6040                 }
6041                 pkt = NULL;
6042                 if ((cmd = mptsas_doneq_thread_rm(mpt, t)) != NULL) {
6043                         cmd->cmd_flags |= CFLAG_COMPLETED;
6044                         pkt = CMD2PKT(cmd);
6045                 }
6046                 mutex_exit(&item->mutex);
6047                 if (pkt) {
6048                         mptsas_pkt_comp(pkt, cmd);
6049                 }
6050                 mutex_enter(&item->mutex);
6051         }
6052         mutex_exit(&item->mutex);
6053         mutex_enter(&mpt->m_qthread_mutex);
6054         mpt->m_doneq_thread_n--;
6055         cv_broadcast(&mpt->m_qthread_cv);
6056         mutex_exit(&mpt->m_qthread_mutex);
6057 }
6058 
6059 
6060 /*
6061  * mpt interrupt handler.
6062  */
6063 static uint_t
6064 mptsas_intr(caddr_t arg1, caddr_t arg2)
6065 {
6066         mptsas_t                        *mpt = (void *)arg1;
6067         mptsas_reply_pqueue_t           *rpqp;
6068         int                             reply_q = (int)(uintptr_t)arg2;
6069         pMpi2ReplyDescriptorsUnion_t    reply_desc_union;
6070         int                             found = 0, i, rpqidx;
6071         size_t                          dma_sync_len;
6072         off_t                           dma_sync_offset;
6073         uint32_t                        istat;
6074 
6075         NDBG18(("mptsas_intr: arg1 0x%p reply_q 0x%d", (void *)arg1, reply_q));
6076 
6077         rpqp = &mpt->m_rep_post_queues[reply_q];
6078 
6079         /*
6080          * If interrupts are shared by two channels then check whether this
6081          * interrupt is genuinely for this channel by making sure first the
6082          * chip is in high power state.
6083          */
6084         if ((mpt->m_options & MPTSAS_OPT_PM) &&
6085             (mpt->m_power_level != PM_LEVEL_D0)) {
6086                 mpt->m_unclaimed_pm_interrupt_count++;
6087                 return (DDI_INTR_UNCLAIMED);
6088         }
6089 
6090         istat = MPTSAS_GET_ISTAT(mpt);
6091         if (!(istat & MPI2_HIS_REPLY_DESCRIPTOR_INTERRUPT)) {
6092                 NDBG18(("Interrupt bit not set, istat 0x%x", istat));
6093                 mpt->m_unclaimed_no_interrupt_count++;
6094                 /*
6095                  * Really need a good definition of when this is valid.
6096                  * It appears not to be if you have multiple reply post
6097                  * queues, there may be a better way - need LSI info.
6098                  * For now just count them.
6099                  */
6100 #if 0
6101                 return (DDI_INTR_UNCLAIMED);
6102 #endif
6103         }
6104 
6105         /*
6106          * If polling, interrupt was triggered by some shared interrupt because
6107          * IOC interrupts are disabled during polling, so polling routine will
6108          * handle any replies.  Considering this, if polling is happening,
6109          * return with interrupt unclaimed.
6110          */
6111         if (mpt->m_polled_intr) {
6112                 mptsas_log(mpt, CE_WARN,
6113                     "Unclaimed interrupt, rpq %d (Polling), istat 0x%x",
6114                     reply_q, istat);
6115                 mpt->m_unclaimed_polled_interrupt_count++;
6116                 return (DDI_INTR_UNCLAIMED);
6117         }
6118 
6119         /*
6120          * At the moment this is the only place the mutex is grabbed.
6121          * So it should never fail!
6122          */
6123         if (mutex_tryenter(&rpqp->rpq_mutex) == 0) {
6124                 mutex_enter(&rpqp->rpq_mutex);
6125                 rpqp->rpq_intr_mutexbusy++;
6126         }
6127 
6128         dma_sync_len = mpt->m_post_queue_depth * 8;
6129         dma_sync_offset = dma_sync_len * reply_q;
6130         (void) ddi_dma_sync(mpt->m_dma_post_queue_hdl,
6131             dma_sync_offset, dma_sync_len, DDI_DMA_SYNC_FORCPU);
6132 
6133         /*
6134          * Go around the reply queue and process each descriptor until
6135          * we get to the next unused one.
6136          * It seems to be an occupational hazard that we get interrupts
6137          * with nothing to do. These are counted below.
6138          */
6139         rpqidx = rpqp->rpq_index;
6140 #ifndef __lock_lint
6141         _NOTE(CONSTCOND)
6142 #endif
6143         while (TRUE) {


6144                 reply_desc_union = (pMpi2ReplyDescriptorsUnion_t)
6145                     MPTSAS_GET_NEXT_REPLY(rpqp, rpqidx);
6146 
6147                 if (ddi_get32(mpt->m_acc_post_queue_hdl,
6148                     &reply_desc_union->Words.Low) == 0xFFFFFFFF ||
6149                     ddi_get32(mpt->m_acc_post_queue_hdl,
6150                     &reply_desc_union->Words.High) == 0xFFFFFFFF) {
6151                         break;
6152                 }
6153 
6154                 found++;
6155 
6156                 ASSERT(ddi_get8(mpt->m_acc_post_queue_hdl,
6157                     &reply_desc_union->Default.MSIxIndex) == reply_q);
6158 
6159                 /*
6160                  * Process it according to its type.


6161                  */
6162                 mptsas_process_intr(mpt, rpqp, reply_desc_union);
6163 
6164                 /*
6165                  * Clear the reply descriptor for re-use.
6166                  */
6167                 ddi_put64(mpt->m_acc_post_queue_hdl,
6168                     &((uint64_t *)(void *)rpqp->rpq_queue)[rpqidx],
6169                     0xFFFFFFFFFFFFFFFF);
6170 
6171                 /*
6172                  * Increment post index and roll over if needed.
6173                  */
6174                 if (++rpqidx == mpt->m_post_queue_depth) {
6175                         rpqidx = 0;
6176                 }
6177         }
6178 
6179         if (found == 0) {
6180                 rpqp->rpq_intr_unclaimed++;
6181                 mutex_exit(&rpqp->rpq_mutex);
6182                 mpt->m_unclaimed_nocmd_interrupt_count++;
6183                 return (DDI_INTR_UNCLAIMED);
6184         }
6185         rpqp->rpq_index = rpqidx;
6186 
6187         rpqp->rpq_intr_count++;
6188         NDBG18(("mptsas_intr complete(%d), did %d loops", reply_q, found));
6189 
6190         (void) ddi_dma_sync(mpt->m_dma_post_queue_hdl,
6191             dma_sync_offset, dma_sync_len, DDI_DMA_SYNC_FORDEV);
6192 
6193         mpt->m_interrupt_count++;
6194 
6195         /*
6196          * Update the reply index if at least one reply was processed.
6197          * For more than 8 reply queues on SAS3 controllers we have to do
6198          * things a little different. See Chapter 20 in the MPI 2.5 spec.
6199          */
6200         if (mpt->m_post_reply_qcount > 8) {
6201                 /*
6202                  * The offsets from the base are multiples of 0x10.
6203                  * We are indexing into 32 bit quantities so calculate
6204                  * the index for that.
6205                  */
6206                 i = (reply_q&~0x7) >> 1;
6207                 ddi_put32(mpt->m_datap,
6208                     &mpt->m_reg->SuppReplyPostHostIndex[i],
6209                     rpqp->rpq_index |
6210                     ((reply_q&0x7)<<MPI2_RPHI_MSIX_INDEX_SHIFT));
6211                 (void) ddi_get32(mpt->m_datap,
6212                     &mpt->m_reg->SuppReplyPostHostIndex[i]);
6213         } else {
6214                 ddi_put32(mpt->m_datap,
6215                     &mpt->m_reg->ReplyPostHostIndex,
6216                     rpqp->rpq_index | (reply_q<<MPI2_RPHI_MSIX_INDEX_SHIFT));
6217                 (void) ddi_get32(mpt->m_datap,
6218                     &mpt->m_reg->ReplyPostHostIndex);
6219         }

6220 
6221         /*
6222          * If no helper threads are created, process the doneq in ISR. If
6223          * helpers are created, use the doneq length as a metric to measure the
6224          * load on the interrupt CPU. If it is long enough, which indicates the
6225          * load is heavy, then we deliver the IO completions to the helpers.
6226          * This measurement has some limitations, although it is simple and
6227          * straightforward and works well for most of the cases at present.
6228          * To always use the threads set mptsas_doneq_length_threshold_prop
6229          * to zero in the mpt_sas3.conf file.
6230          *
6231          * Check the current reply queue done queue.
6232          */
6233         if (rpqp->rpq_dlist.dl_len) {
6234                 if (!mpt->m_doneq_thread_n ||
6235                     (rpqp->rpq_dlist.dl_len <= mpt->m_doneq_length_threshold)) {
6236                         mptsas_rpdoneq_empty(rpqp);
6237                 } else {
6238                         mptsas_deliver_doneq_thread(mpt, &rpqp->rpq_dlist);
6239                 }
6240         }
6241 
6242         mutex_exit(&rpqp->rpq_mutex);
6243 
6244         /*
6245          * Check the main done queue. If we find something
6246          * grab the mutex and check again before processing.
6247          */
6248         if (mpt->m_dlist.dl_len) {
6249                 mutex_enter(&mpt->m_mutex);
6250                 if (mpt->m_dlist.dl_len) {
6251                         if (!mpt->m_doneq_thread_n ||
6252                             (mpt->m_dlist.dl_len <=
6253                             mpt->m_doneq_length_threshold)) {
6254                                 mptsas_doneq_empty(mpt);
6255                         } else {
6256                                 mptsas_deliver_doneq_thread(mpt, &mpt->m_dlist);
6257                         }
6258                 }
6259                 mutex_exit(&mpt->m_mutex);
6260         }
6261 
6262         /*
6263          * If there are queued cmd, start them now.
6264          */
6265         if (mpt->m_waitq != NULL) {
6266                 mutex_enter(&mpt->m_mutex);
6267                 if (mpt->m_waitq != NULL && mpt->m_polled_intr == 0) {
6268                         mptsas_restart_waitq(mpt);
6269                 }

6270                 mutex_exit(&mpt->m_mutex);
6271         }
6272         return (DDI_INTR_CLAIMED);
6273 }
6274 
6275 static void
6276 mptsas_process_intr(mptsas_t *mpt, mptsas_reply_pqueue_t *rpqp,
6277     pMpi2ReplyDescriptorsUnion_t reply_desc_union)
6278 {
6279         uint8_t reply_type;
6280 
6281         /*
6282          * Should get here with the reply queue mutex held, but not
6283          * the main mpt mutex. Want to avoid grabbing that during
6284          * normal operations if possible.
6285          */
6286         ASSERT(mutex_owned(&rpqp->rpq_mutex));
6287 
6288         /*
6289          * The reply is valid, process it according to its
6290          * type.  Also, set a flag for updated the reply index
6291          * after they've all been processed.
6292          */
6293         reply_type = ddi_get8(mpt->m_acc_post_queue_hdl,
6294             &reply_desc_union->Default.ReplyFlags);
6295         NDBG18(("mptsas_process_intr(rpq %d) reply_type 0x%x", rpqp->rpq_num,
6296             reply_type));
6297         reply_type &= MPI2_RPY_DESCRIPT_FLAGS_TYPE_MASK;
6298         if (reply_type == MPI2_RPY_DESCRIPT_FLAGS_SCSI_IO_SUCCESS ||
6299             reply_type == MPI25_RPY_DESCRIPT_FLAGS_FAST_PATH_SCSI_IO_SUCCESS) {
6300                 mptsas_handle_scsi_io_success(mpt, rpqp, reply_desc_union);
6301         } else if (reply_type == MPI2_RPY_DESCRIPT_FLAGS_ADDRESS_REPLY) {
6302                 mutex_enter(&mpt->m_mutex);
6303                 mptsas_handle_address_reply(mpt, reply_desc_union);
6304                 mutex_exit(&mpt->m_mutex);
6305         } else {
6306                 mptsas_log(mpt, CE_WARN, "?Bad reply type %x", reply_type);
6307                 ddi_fm_service_impact(mpt->m_dip, DDI_SERVICE_UNAFFECTED);
6308         }










6309 }
6310 
6311 /*
6312  * handle qfull condition
6313  */
6314 static void
6315 mptsas_handle_qfull(mptsas_t *mpt, mptsas_cmd_t *cmd)
6316 {
6317         mptsas_target_t *ptgt = cmd->cmd_tgt_addr;
6318 
6319         mutex_enter(&ptgt->m_t_mutex);
6320         if ((++cmd->cmd_qfull_retries > ptgt->m_qfull_retries) ||
6321             (ptgt->m_qfull_retries == 0)) {
6322                 /*
6323                  * We have exhausted the retries on QFULL, or,
6324                  * the target driver has indicated that it
6325                  * wants to handle QFULL itself by setting
6326                  * qfull-retries capability to 0. In either case
6327                  * we want the target driver's QFULL handling
6328                  * to kick in. We do this by having pkt_reason
6329                  * as CMD_CMPLT and pkt_scbp as STATUS_QFULL.
6330                  */
6331                 mptsas_set_throttle(mpt, ptgt, DRAIN_THROTTLE);
6332         } else {
6333                 if (ptgt->m_reset_delay == 0) {
6334                         ptgt->m_t_throttle =
6335                             max((ptgt->m_t_ncmds - 2), 0);
6336                 }
6337                 mutex_exit(&ptgt->m_t_mutex);
6338 

6339                 cmd->cmd_flags &= ~(CFLAG_TRANFLAG);

6340 
6341                 mptsas_retry_pkt(mpt, cmd);
6342 
6343                 mutex_enter(&ptgt->m_t_mutex);
6344                 /*
6345                  * when target gives queue full status with no commands
6346                  * outstanding (m_t_ncmds == 0), throttle is set to 0
6347                  * (HOLD_THROTTLE), and the queue full handling start
6348                  * (see psarc/1994/313); if there are commands outstanding,
6349                  * throttle is set to (m_t_ncmds - 2)
6350                  */
6351                 if (ptgt->m_t_throttle == HOLD_THROTTLE) {
6352                         /*
6353                          * By setting throttle to QFULL_THROTTLE, we
6354                          * avoid submitting new commands and in
6355                          * mptsas_restart_cmd find out slots which need
6356                          * their throttles to be cleared.
6357                          */
6358                         mptsas_set_throttle(mpt, ptgt, QFULL_THROTTLE);
6359                         if (mpt->m_restart_cmd_timeid == 0) {
6360                                 mpt->m_restart_cmd_timeid =
6361                                     timeout(mptsas_restart_cmd, mpt,
6362                                     ptgt->m_qfull_retry_interval);
6363                         }
6364                 }
6365         }
6366         mutex_exit(&ptgt->m_t_mutex);
6367 }
6368 
6369 mptsas_phymask_t
6370 mptsas_physport_to_phymask(mptsas_t *mpt, uint8_t physport)
6371 {
6372         mptsas_phymask_t        phy_mask = 0;
6373         uint8_t                 i = 0;
6374 
6375         NDBG20(("mptsas3%d physport_to_phymask enter", mpt->m_instance));
6376 
6377         ASSERT(mutex_owned(&mpt->m_mutex));
6378 
6379         /*
6380          * If physport is 0xFF, this is a RAID volume.  Use phymask of 0.
6381          */
6382         if (physport == 0xFF) {
6383                 return (0);
6384         }
6385 
6386         for (i = 0; i < MPTSAS_MAX_PHYS; i++) {
6387                 if (mpt->m_phy_info[i].attached_devhdl &&
6388                     (mpt->m_phy_info[i].phy_mask != 0) &&
6389                     (mpt->m_phy_info[i].port_num == physport)) {
6390                         phy_mask = mpt->m_phy_info[i].phy_mask;
6391                         break;
6392                 }
6393         }
6394         NDBG20(("mptsas3%d physport_to_phymask:physport :%x phymask :%x, ",
6395             mpt->m_instance, physport, phy_mask));
6396         return (phy_mask);
6397 }
6398 
6399 /*
6400  * mpt free device handle after device gone, by use of passthrough
6401  */
6402 static int
6403 mptsas_free_devhdl(mptsas_t *mpt, uint16_t devhdl)
6404 {
6405         Mpi2SasIoUnitControlRequest_t   req;
6406         Mpi2SasIoUnitControlReply_t     rep;
6407         int                             ret;
6408 
6409         ASSERT(mutex_owned(&mpt->m_mutex));
6410 
6411         /*
6412          * Need to compose a SAS IO Unit Control request message
6413          * and call mptsas_do_passthru() function
6414          */


6428         }
6429 
6430         /* do passthrough success, check the ioc status */
6431         if (LE_16(rep.IOCStatus) != MPI2_IOCSTATUS_SUCCESS) {
6432                 cmn_err(CE_WARN, "mptsas_free_devhdl: passthru SAS IO Unit "
6433                     "Control IOCStatus %d", LE_16(rep.IOCStatus));
6434                 return (DDI_FAILURE);
6435         }
6436 
6437         return (DDI_SUCCESS);
6438 }
6439 
6440 static void
6441 mptsas_update_phymask(mptsas_t *mpt)
6442 {
6443         mptsas_phymask_t mask = 0, phy_mask;
6444         char            *phy_mask_name;
6445         uint8_t         current_port;
6446         int             i, j;
6447 
6448         NDBG20(("mptsas3%d update phymask ", mpt->m_instance));
6449 
6450         ASSERT(mutex_owned(&mpt->m_mutex));
6451 
6452         (void) mptsas_get_sas_io_unit_page(mpt);
6453 
6454         phy_mask_name = kmem_zalloc(MPTSAS_MAX_PHYS, KM_SLEEP);
6455 
6456         for (i = 0; i < mpt->m_num_phys; i++) {
6457                 phy_mask = 0x00;
6458 
6459                 if (mpt->m_phy_info[i].attached_devhdl == 0)
6460                         continue;
6461 
6462                 bzero(phy_mask_name, sizeof (phy_mask_name));
6463 
6464                 current_port = mpt->m_phy_info[i].port_num;
6465 
6466                 if ((mask & (1 << i)) != 0)
6467                         continue;
6468 


6474                 }
6475                 mask = mask | phy_mask;
6476 
6477                 for (j = 0; j < mpt->m_num_phys; j++) {
6478                         if ((phy_mask >> j) & 0x01) {
6479                                 mpt->m_phy_info[j].phy_mask = phy_mask;
6480                         }
6481                 }
6482 
6483                 (void) sprintf(phy_mask_name, "%x", phy_mask);
6484 
6485                 mutex_exit(&mpt->m_mutex);
6486                 /*
6487                  * register a iport, if the port has already been existed
6488                  * SCSA will do nothing and just return.
6489                  */
6490                 (void) scsi_hba_iport_register(mpt->m_dip, phy_mask_name);
6491                 mutex_enter(&mpt->m_mutex);
6492         }
6493         kmem_free(phy_mask_name, MPTSAS_MAX_PHYS);
6494         NDBG20(("mptsas3%d update phymask return", mpt->m_instance));
6495 }
6496 
6497 /*
6498  * mptsas_handle_dr is a task handler for DR, the DR action includes:
6499  * 1. Directly attched Device Added/Removed.
6500  * 2. Expander Device Added/Removed.
6501  * 3. Indirectly Attached Device Added/Expander.
6502  * 4. LUNs of a existing device status change.
6503  * 5. RAID volume created/deleted.
6504  * 6. Member of RAID volume is released because of RAID deletion.
6505  * 7. Physical disks are removed because of RAID creation.
6506  */
6507 static void
6508 mptsas_handle_dr(void *args) {
6509         mptsas_topo_change_list_t       *topo_node = NULL;
6510         mptsas_topo_change_list_t       *save_node = NULL;
6511         mptsas_t                        *mpt;
6512         dev_info_t                      *parent = NULL;
6513         mptsas_phymask_t                phymask = 0;
6514         char                            phy_mask_name[MPTSAS_MAX_PHYS];
6515         uint8_t                         flags = 0, physport = 0xff;
6516         uint8_t                         port_update = 0;
6517         uint_t                          event;
6518 
6519         topo_node = (mptsas_topo_change_list_t *)args;
6520 
6521         mpt = topo_node->mpt;
6522         event = topo_node->event;
6523         flags = topo_node->flags;
6524 
6525         NDBG20(("mptsas3%d handle_dr enter", mpt->m_instance));


6526 
6527         switch (event) {
6528         case MPTSAS_DR_EVENT_RECONFIG_TARGET:
6529                 if ((flags == MPTSAS_TOPO_FLAG_DIRECT_ATTACHED_DEVICE) ||
6530                     (flags == MPTSAS_TOPO_FLAG_EXPANDER_ATTACHED_DEVICE) ||
6531                     (flags == MPTSAS_TOPO_FLAG_RAID_PHYSDRV_ASSOCIATED)) {
6532                         /*
6533                          * Direct attached or expander attached device added
6534                          * into system or a Phys Disk that is being unhidden.
6535                          */
6536                         port_update = 1;
6537                 }
6538                 break;
6539         case MPTSAS_DR_EVENT_RECONFIG_SMP:
6540                 /*
6541                  * New expander added into system, it must be the head
6542                  * of topo_change_list_t
6543                  */
6544                 port_update = 1;
6545                 break;


6547                 port_update = 0;
6548                 break;
6549         }
6550         /*
6551          * All cases port_update == 1 may cause initiator port form change
6552          */
6553         mutex_enter(&mpt->m_mutex);
6554         if (mpt->m_port_chng && port_update) {
6555                 /*
6556                  * mpt->m_port_chng flag indicates some PHYs of initiator
6557                  * port have changed to online. So when expander added or
6558                  * directly attached device online event come, we force to
6559                  * update port information by issueing SAS IO Unit Page and
6560                  * update PHYMASKs.
6561                  */
6562                 (void) mptsas_update_phymask(mpt);
6563                 mpt->m_port_chng = 0;
6564 
6565         }
6566         mutex_exit(&mpt->m_mutex);
6567 
6568         while (topo_node) {
6569                 phymask = 0;
6570                 flags = topo_node->flags;
6571                 event = topo_node->event;
6572                 if (event == MPTSAS_DR_EVENT_REMOVE_HANDLE) {
6573                         goto handle_topo_change;
6574                 }
6575                 if ((event == MPTSAS_DR_EVENT_RECONFIG_TARGET) &&
6576                     (flags == MPTSAS_TOPO_FLAG_RAID_PHYSDRV_ASSOCIATED)) {
6577                         /*
6578                          * There is no any field in IR_CONFIG_CHANGE
6579                          * event indicate physport/phynum, let's get
6580                          * parent after SAS Device Page0 request.
6581                          */
6582                         goto handle_topo_change;
6583                 }
6584 
6585                 if (parent == NULL) {
6586                         physport = topo_node->un.physport;


6587                         if (event & (MPTSAS_DR_EVENT_OFFLINE_TARGET |
6588                             MPTSAS_DR_EVENT_OFFLINE_SMP)) {
6589                                 /*
6590                                  * For all offline events, phymask is known
6591                                  */
6592                                 phymask = topo_node->un.phymask;
6593                                 goto find_parent;
6594                         }



6595                         if (flags & MPTSAS_TOPO_FLAG_LUN_ASSOCIATED) {
6596                                 phymask = topo_node->un.phymask;
6597                                 goto find_parent;
6598                         }
6599 











6600                         mutex_enter(&mpt->m_mutex);
6601                         if (flags == MPTSAS_TOPO_FLAG_DIRECT_ATTACHED_DEVICE) {
6602                                 /*
6603                                  * If the direct attached device added or a
6604                                  * phys disk is being unhidden, argument
6605                                  * physport actually is PHY#, so we have to get
6606                                  * phymask according PHY#.
6607                                  */
6608                                 physport = mpt->m_phy_info[physport].port_num;
6609                         }
6610 
6611                         /*
6612                          * Translate physport to phymask so that we can search
6613                          * parent dip.
6614                          */
6615                         phymask = mptsas_physport_to_phymask(mpt, physport);

6616                         mutex_exit(&mpt->m_mutex);
6617 
6618 find_parent:
6619                         bzero(phy_mask_name, MPTSAS_MAX_PHYS);
6620                         /*
6621                          * For RAID topology change node, write the iport name
6622                          * as v0.
6623                          */
6624                         if (flags & MPTSAS_TOPO_FLAG_RAID_ASSOCIATED) {
6625                                 (void) sprintf(phy_mask_name, "v0");
6626                         } else {
6627                                 /*
6628                                  * phymask can be 0 if the drive has been
6629                                  * pulled by the time an add event is
6630                                  * processed.  If phymask is 0, just skip this
6631                                  * event and continue.
6632                                  */
6633                                 if (phymask == 0) {

6634                                         save_node = topo_node;
6635                                         topo_node = topo_node->next;
6636                                         ASSERT(save_node);
6637                                         kmem_free(save_node,
6638                                             sizeof (mptsas_topo_change_list_t));


6639                                         parent = NULL;
6640                                         continue;
6641                                 }
6642                                 (void) sprintf(phy_mask_name, "%x", phymask);
6643                         }
6644                         parent = scsi_hba_iport_find(mpt->m_dip,
6645                             phy_mask_name);
6646                         if (parent == NULL) {
6647                                 mptsas_log(mpt, CE_WARN, "Failed to find an "
6648                                     "iport for \"%s\", should not happen!",
6649                                     phy_mask_name);
6650                                 save_node = topo_node;
6651                                 topo_node = topo_node->next;
6652                                 ASSERT(save_node);
6653                                 kmem_free(save_node,
6654                                     sizeof (mptsas_topo_change_list_t));
6655                                 continue;
6656                         }
6657 
6658                 }
6659                 ASSERT(parent);
6660 handle_topo_change:
6661 
6662                 mutex_enter(&mpt->m_mutex);
6663                 /*
6664                  * If HBA is being reset, don't perform operations depending
6665                  * on the IOC. We must free the topo list, however.
6666                  */
6667                 if (!mpt->m_in_reset)
6668                         mptsas_handle_topo_change(topo_node, parent);
6669                 else
6670                         NDBG20(("skipping topo change received during reset"));
6671                 mutex_exit(&mpt->m_mutex);
6672                 save_node = topo_node;
6673                 topo_node = topo_node->next;
6674                 ASSERT(save_node);
6675                 kmem_free(save_node, sizeof (mptsas_topo_change_list_t));

6676 
6677                 if ((flags == MPTSAS_TOPO_FLAG_DIRECT_ATTACHED_DEVICE) ||
6678                     (flags == MPTSAS_TOPO_FLAG_RAID_PHYSDRV_ASSOCIATED) ||
6679                     (flags == MPTSAS_TOPO_FLAG_RAID_ASSOCIATED)) {
6680                         /*
6681                          * If direct attached device associated, make sure
6682                          * reset the parent before start the next one. But
6683                          * all devices associated with expander shares the
6684                          * parent.  Also, reset parent if this is for RAID.
6685                          */
6686                         parent = NULL;
6687                 }
6688         }
6689 }
6690 
6691 static void
6692 mptsas_offline_target(mptsas_t *mpt, mptsas_target_t *ptgt,
6693     uint8_t topo_flags, dev_info_t *parent)
6694 {
6695         uint64_t        sas_wwn = 0;
6696         uint8_t         phy;
6697         char            wwn_str[MPTSAS_WWN_STRLEN];
6698         uint16_t        devhdl;
6699         int             circ = 0, circ1 = 0;
6700         int             rval = 0;
6701 
6702         sas_wwn = ptgt->m_addr.mta_wwn;
6703         phy = ptgt->m_phynum;
6704         devhdl = ptgt->m_devhdl;
6705 
6706         if (sas_wwn) {
6707                 (void) sprintf(wwn_str, "w%016"PRIx64, sas_wwn);
6708         } else {
6709                 (void) sprintf(wwn_str, "p%x", phy);
6710         }
6711 
6712         /*
6713          * Abort all outstanding command on the device
6714          */
6715         rval = mptsas_do_scsi_reset(mpt, devhdl);
6716         if (rval) {
6717                 NDBG20(("mptsas3%d: mptsas_offline_target: reset target "
6718                     "before offline devhdl:%x, phymask:%x, rval:%x",
6719                     mpt->m_instance, ptgt->m_devhdl,
6720                     ptgt->m_addr.mta_phymask, rval));
6721         }
6722 
6723         mutex_exit(&mpt->m_mutex);
6724 
6725         ndi_devi_enter(scsi_vhci_dip, &circ);
6726         ndi_devi_enter(parent, &circ1);
6727         rval = mptsas_offline_targetdev(parent, wwn_str);
6728         ndi_devi_exit(parent, circ1);
6729         ndi_devi_exit(scsi_vhci_dip, circ);
6730         NDBG20(("mptsas3%d: mptsas_offline_target %s devhdl:%x, "
6731             "phymask:%x, rval:%x", mpt->m_instance, wwn_str,
6732             ptgt->m_devhdl, ptgt->m_addr.mta_phymask, rval));
6733 
6734         /*
6735          * Clear parent's props for SMHBA support
6736          */
6737         if (topo_flags == MPTSAS_TOPO_FLAG_DIRECT_ATTACHED_DEVICE) {
6738                 if (ddi_prop_update_string(DDI_DEV_T_NONE, parent,
6739                     SCSI_ADDR_PROP_ATTACHED_PORT, "") !=
6740                     DDI_PROP_SUCCESS) {
6741                         (void) ddi_prop_remove(DDI_DEV_T_NONE, parent,
6742                             SCSI_ADDR_PROP_ATTACHED_PORT);
6743                         mptsas_log(mpt, CE_WARN, "mptsas attached port "
6744                             "prop update failed");
6745                 }
6746                 if (ddi_prop_update_int(DDI_DEV_T_NONE, parent,
6747                     MPTSAS_NUM_PHYS, 0) != DDI_PROP_SUCCESS) {
6748                         (void) ddi_prop_remove(DDI_DEV_T_NONE, parent,
6749                             MPTSAS_NUM_PHYS);
6750                         mptsas_log(mpt, CE_WARN, "mptsas num phys "
6751                             "prop update failed");
6752                 }
6753                 if (ddi_prop_update_int(DDI_DEV_T_NONE, parent,
6754                     MPTSAS_VIRTUAL_PORT, 1) != DDI_PROP_SUCCESS) {
6755                         (void) ddi_prop_remove(DDI_DEV_T_NONE, parent,
6756                             MPTSAS_VIRTUAL_PORT);
6757                         mptsas_log(mpt, CE_WARN, "mptsas virtual port "
6758                             "prop update failed");
6759                 }
6760         }
6761 
6762         mutex_enter(&mpt->m_mutex);
6763         ptgt->m_led_status = 0;
6764         (void) mptsas_flush_led_status(mpt, ptgt);
6765         if (rval == DDI_SUCCESS) {
6766                 mutex_destroy(&ptgt->m_t_mutex);
6767                 refhash_remove(mpt->m_targets, ptgt);
6768                 ptgt = NULL;
6769         } else {
6770                 /*
6771                  * clean DR_INTRANSITION flag to allow I/O down to
6772                  * PHCI driver since failover finished.
6773                  * Invalidate the devhdl
6774                  */
6775                 ptgt->m_devhdl = MPTSAS_INVALID_DEVHDL;
6776                 ptgt->m_tgt_unconfigured = 0;
6777                 ptgt->m_dr_flag = MPTSAS_DR_INACTIVE;
6778         }
6779 }
6780 
6781 static void
6782 mptsas_handle_topo_change(mptsas_topo_change_list_t *topo_node,
6783     dev_info_t *parent)
6784 {
6785         mptsas_target_t *ptgt = NULL;
6786         mptsas_smp_t    *psmp = NULL;
6787         mptsas_t        *mpt = (void *)topo_node->mpt;
6788         uint16_t        devhdl;
6789         uint16_t        attached_devhdl;

6790         int             rval = 0;
6791         uint32_t        page_address;
6792         uint8_t         flags;

6793         dev_info_t      *lundip;
6794         int             circ = 0, circ1 = 0;
6795         char            attached_wwnstr[MPTSAS_WWN_STRLEN];
6796 
6797         NDBG20(("mptsas3%d handle_topo_change enter, devhdl 0x%x,"
6798             "event 0x%x, flags 0x%x", mpt->m_instance, topo_node->devhdl,
6799             topo_node->event, topo_node->flags));
6800 
6801         ASSERT(mutex_owned(&mpt->m_mutex));
6802 
6803         switch (topo_node->event) {
6804         case MPTSAS_DR_EVENT_RECONFIG_TARGET:
6805         {
6806                 char *phy_mask_name;
6807                 mptsas_phymask_t phymask = 0;
6808 
6809                 if (topo_node->flags == MPTSAS_TOPO_FLAG_RAID_ASSOCIATED) {
6810                         /*
6811                          * Get latest RAID info.
6812                          */
6813                         (void) mptsas_get_raid_info(mpt);
6814                         ptgt = refhash_linear_search(mpt->m_targets,
6815                             mptsas_target_eval_devhdl, &topo_node->devhdl);
6816                         if (ptgt == NULL)
6817                                 break;
6818                 } else {
6819                         ptgt = (void *)topo_node->object;


6938                                 /*
6939                                  * topo_node->un.physport is really the PHY#
6940                                  * for direct attached devices
6941                                  */
6942                                 mptsas_smhba_set_one_phy_props(mpt, parent,
6943                                     topo_node->un.physport, &attached_devhdl);
6944 
6945                                 if (ddi_prop_update_int(DDI_DEV_T_NONE, parent,
6946                                     MPTSAS_VIRTUAL_PORT, 0) !=
6947                                     DDI_PROP_SUCCESS) {
6948                                         (void) ddi_prop_remove(DDI_DEV_T_NONE,
6949                                             parent, MPTSAS_VIRTUAL_PORT);
6950                                         mptsas_log(mpt, CE_WARN,
6951                                             "mptsas virtual-port"
6952                                             "port prop update failed");
6953                                         return;
6954                                 }
6955                         }
6956                 }
6957                 mutex_enter(&mpt->m_mutex);
6958 
6959                 NDBG20(("mptsas3%d handle_topo_change to online devhdl:%x, "
6960                     "phymask:%x.", mpt->m_instance, ptgt->m_devhdl,
6961                     ptgt->m_addr.mta_phymask));
6962                 break;
6963         }
6964         case MPTSAS_DR_EVENT_OFFLINE_TARGET:
6965         {
6966                 devhdl = topo_node->devhdl;
6967                 ptgt = refhash_linear_search(mpt->m_targets,
6968                     mptsas_target_eval_devhdl, &devhdl);
6969                 if (ptgt == NULL)
6970                         break;
6971 
6972                 ASSERT(ptgt->m_devhdl == devhdl);
6973 
6974                 if ((topo_node->flags == MPTSAS_TOPO_FLAG_RAID_ASSOCIATED) ||
6975                     (topo_node->flags ==
6976                     MPTSAS_TOPO_FLAG_RAID_PHYSDRV_ASSOCIATED)) {


















































































6977                         /*
6978                          * Get latest RAID info if RAID volume status changes
6979                          * or Phys Disk status changes

6980                          */
6981                         (void) mptsas_get_raid_info(mpt);




6982                 }
6983 
6984                 mptsas_offline_target(mpt, ptgt, topo_node->flags, parent);
6985 
6986                 /*
6987                  * Send SAS IO Unit Control to free the dev handle
6988                  */
6989                 if ((flags == MPTSAS_TOPO_FLAG_DIRECT_ATTACHED_DEVICE) ||
6990                     (flags == MPTSAS_TOPO_FLAG_EXPANDER_ATTACHED_DEVICE)) {
6991                         rval = mptsas_free_devhdl(mpt, devhdl);
6992 
6993                         NDBG20(("mptsas3%d handle_topo_change to remove "
6994                             "devhdl:%x, rval:%x", mpt->m_instance, devhdl,
6995                             rval));
6996                 }
6997 
6998                 break;
6999         }
7000         case MPTSAS_DR_EVENT_REMOVE_HANDLE:
7001         {
7002                 devhdl = topo_node->devhdl;
7003 
7004                 /*
7005                  * Do a reset first.
7006                  */

7007                 rval = mptsas_do_scsi_reset(mpt, devhdl);

7008                 NDBG20(("mpt%d reset target before remove "
7009                     "devhdl:%x, rval:%x", mpt->m_instance, devhdl, rval));



7010 
7011                 /*
7012                  * Send SAS IO Unit Control to free the dev handle
7013                  */
7014                 rval = mptsas_free_devhdl(mpt, devhdl);
7015                 NDBG20(("mptsas3%d handle_topo_change to remove "
7016                     "devhdl:%x, rval:%x", mpt->m_instance, devhdl,
7017                     rval));
7018                 break;
7019         }
7020         case MPTSAS_DR_EVENT_RECONFIG_SMP:
7021         {
7022                 mptsas_smp_t smp;
7023                 dev_info_t *smpdip;
7024 
7025                 devhdl = topo_node->devhdl;
7026 
7027                 page_address = (MPI2_SAS_EXPAND_PGAD_FORM_HNDL &
7028                     MPI2_SAS_EXPAND_PGAD_FORM_MASK) | (uint32_t)devhdl;
7029                 rval = mptsas_get_sas_expander_page0(mpt, page_address, &smp);
7030                 if (rval != DDI_SUCCESS) {
7031                         mptsas_log(mpt, CE_WARN, "failed to online smp, "
7032                             "handle %x", devhdl);
7033                         return;
7034                 }
7035 


7088                                 mptsas_log(mpt, CE_WARN, "mptsas num phys"
7089                                     "prop update failed");
7090                                 return;
7091                         }
7092                         /*
7093                          * Clear parent's attached-port props
7094                          */
7095                         bzero(attached_wwnstr, sizeof (attached_wwnstr));
7096                         if (ddi_prop_update_string(DDI_DEV_T_NONE, parent,
7097                             SCSI_ADDR_PROP_ATTACHED_PORT, attached_wwnstr) !=
7098                             DDI_PROP_SUCCESS) {
7099                                 (void) ddi_prop_remove(DDI_DEV_T_NONE, parent,
7100                                     SCSI_ADDR_PROP_ATTACHED_PORT);
7101                                 mptsas_log(mpt, CE_WARN, "mptsas attached port "
7102                                     "prop update failed");
7103                                 return;
7104                         }
7105                 }
7106 
7107                 mutex_enter(&mpt->m_mutex);
7108                 NDBG20(("mptsas3%d handle_topo_change to remove devhdl:%x, "
7109                     "rval:%x", mpt->m_instance, psmp->m_devhdl, rval));
7110                 if (rval == DDI_SUCCESS) {
7111                         refhash_remove(mpt->m_smp_targets, psmp);
7112                 } else {
7113                         psmp->m_devhdl = MPTSAS_INVALID_DEVHDL;
7114                 }
7115 
7116                 bzero(attached_wwnstr, sizeof (attached_wwnstr));
7117 
7118                 break;
7119         }
7120         default:
7121                 return;
7122         }
7123 }
7124 
7125 /*
7126  * Record the event if its type is enabled in mpt instance by ioctl.
7127  */
7128 static void
7129 mptsas_record_event(void *args)
7130 {
7131         m_replyh_arg_t                  *replyh_arg;
7132         pMpi2EventNotificationReply_t   eventreply;
7133         uint32_t                        event, rfm;
7134         mptsas_t                        *mpt;
7135         int                             i, j;
7136         uint16_t                        event_data_len;
7137         boolean_t                       sendAEN = FALSE;
7138 
7139         replyh_arg = (m_replyh_arg_t *)args;
7140         rfm = replyh_arg->rfm;
7141         mpt = replyh_arg->mpt;
7142 
7143         eventreply = (pMpi2EventNotificationReply_t)
7144             (mpt->m_reply_frame + (rfm -
7145             (mpt->m_reply_frame_dma_addr&0xfffffffful)));
7146         event = ddi_get16(mpt->m_acc_reply_frame_hdl, &eventreply->Event);
7147 
7148 
7149         /*
7150          * Generate a system event to let anyone who cares know that a
7151          * LOG_ENTRY_ADDED event has occurred.  This is sent no matter what the
7152          * event mask is set to.
7153          */
7154         if (event == MPI2_EVENT_LOG_ENTRY_ADDED) {
7155                 sendAEN = TRUE;
7156         }
7157 
7158         /*
7159          * Record the event only if it is not masked.  Determine which dword
7160          * and bit of event mask to test.
7161          */
7162         i = (uint8_t)(event / 32);
7163         j = (uint8_t)(event % 32);
7164         if ((i < 4) && ((1 << j) & mpt->m_event_mask[i])) {
7165                 i = mpt->m_event_index;


7213  * return value:
7214  * DDI_SUCCESS: The event is handled by this func
7215  * DDI_FAILURE: Event is not handled
7216  */
7217 static int
7218 mptsas_handle_event_sync(void *args)
7219 {
7220         m_replyh_arg_t                  *replyh_arg;
7221         pMpi2EventNotificationReply_t   eventreply;
7222         uint32_t                        event, rfm;
7223         mptsas_t                        *mpt;
7224         uint_t                          iocstatus;
7225 
7226         replyh_arg = (m_replyh_arg_t *)args;
7227         rfm = replyh_arg->rfm;
7228         mpt = replyh_arg->mpt;
7229 
7230         ASSERT(mutex_owned(&mpt->m_mutex));
7231 
7232         eventreply = (pMpi2EventNotificationReply_t)
7233             (mpt->m_reply_frame + (rfm -
7234             (mpt->m_reply_frame_dma_addr&0xfffffffful)));
7235         event = ddi_get16(mpt->m_acc_reply_frame_hdl, &eventreply->Event);
7236 
7237         if (iocstatus = ddi_get16(mpt->m_acc_reply_frame_hdl,
7238             &eventreply->IOCStatus)) {
7239                 if (iocstatus == MPI2_IOCSTATUS_FLAG_LOG_INFO_AVAILABLE) {
7240                         mptsas_log(mpt, CE_WARN,
7241                             "!mptsas_handle_event_sync: event 0x%x, "
7242                             "IOCStatus=0x%x, "
7243                             "IOCLogInfo=0x%x", event, iocstatus,
7244                             ddi_get32(mpt->m_acc_reply_frame_hdl,
7245                             &eventreply->IOCLogInfo));
7246                 } else {
7247                         mptsas_log(mpt, CE_WARN,
7248                             "mptsas_handle_event_sync: event 0x%x, "
7249                             "IOCStatus=0x%x, "
7250                             "(IOCLogInfo=0x%x)", event, iocstatus,
7251                             ddi_get32(mpt->m_acc_reply_frame_hdl,
7252                             &eventreply->IOCLogInfo));
7253                 }
7254         }
7255 
7256         /*
7257          * figure out what kind of event we got and handle accordingly
7258          */
7259         switch (event) {
7260         case MPI2_EVENT_SAS_TOPOLOGY_CHANGE_LIST:
7261         {
7262                 pMpi2EventDataSasTopologyChangeList_t   sas_topo_change_list;
7263                 uint8_t                         num_entries, expstatus, phy;
7264                 uint8_t                         phystatus, physport, state, i;
7265                 uint8_t                         start_phy_num, link_rate;
7266                 uint16_t                        dev_handle, reason_code;
7267                 uint16_t                        enc_handle, expd_handle;
7268                 char                            string[80], curr[80], prev[80];
7269                 mptsas_topo_change_list_t       *topo_head = NULL;
7270                 mptsas_topo_change_list_t       *topo_tail = NULL;


7365                         dev_handle = ddi_get16(mpt->m_acc_reply_frame_hdl,
7366                             &sas_topo_change_list->PHY[i].AttachedDevHandle);
7367                         reason_code = phystatus & MPI2_EVENT_SAS_TOPO_RC_MASK;
7368                         /*
7369                          * Filter out processing of Phy Vacant Status unless
7370                          * the reason code is "Not Responding".  Process all
7371                          * other combinations of Phy Status and Reason Codes.
7372                          */
7373                         if ((phystatus &
7374                             MPI2_EVENT_SAS_TOPO_PHYSTATUS_VACANT) &&
7375                             (reason_code !=
7376                             MPI2_EVENT_SAS_TOPO_RC_TARG_NOT_RESPONDING)) {
7377                                 continue;
7378                         }
7379                         curr[0] = 0;
7380                         prev[0] = 0;
7381                         string[0] = 0;
7382                         switch (reason_code) {
7383                         case MPI2_EVENT_SAS_TOPO_RC_TARG_ADDED:
7384                         {
7385                                 NDBG20(("mptsas3%d phy %d physical_port %d "
7386                                     "dev_handle %d added", mpt->m_instance, phy,
7387                                     physport, dev_handle));
7388                                 link_rate = ddi_get8(mpt->m_acc_reply_frame_hdl,
7389                                     &sas_topo_change_list->PHY[i].LinkRate);
7390                                 state = (link_rate &
7391                                     MPI2_EVENT_SAS_TOPO_LR_CURRENT_MASK) >>
7392                                     MPI2_EVENT_SAS_TOPO_LR_CURRENT_SHIFT;
7393                                 switch (state) {
7394                                 case MPI2_EVENT_SAS_TOPO_LR_PHY_DISABLED:
7395                                         (void) sprintf(curr, "is disabled");
7396                                         break;
7397                                 case MPI2_EVENT_SAS_TOPO_LR_NEGOTIATION_FAILED:
7398                                         (void) sprintf(curr, "is offline, "
7399                                             "failed speed negotiation");
7400                                         break;
7401                                 case MPI2_EVENT_SAS_TOPO_LR_SATA_OOB_COMPLETE:
7402                                         (void) sprintf(curr, "SATA OOB "
7403                                             "complete");
7404                                         break;
7405                                 case SMP_RESET_IN_PROGRESS:
7406                                         (void) sprintf(curr, "SMP reset in "
7407                                             "progress");
7408                                         break;
7409                                 case MPI2_EVENT_SAS_TOPO_LR_RATE_1_5:
7410                                         (void) sprintf(curr, "is online at "
7411                                             "1.5 Gbps");
7412                                         break;
7413                                 case MPI2_EVENT_SAS_TOPO_LR_RATE_3_0:
7414                                         (void) sprintf(curr, "is online at 3.0 "
7415                                             "Gbps");
7416                                         break;
7417                                 case MPI2_EVENT_SAS_TOPO_LR_RATE_6_0:
7418                                         (void) sprintf(curr, "is online at 6.0 "
7419                                             "Gbps");
7420                                         break;
7421                                 case MPI25_EVENT_SAS_TOPO_LR_RATE_12_0:
7422                                         (void) sprintf(curr,
7423                                             "is online at 12.0 Gbps");
7424                                         break;
7425                                 default:
7426                                         (void) sprintf(curr, "state is "
7427                                             "unknown");
7428                                         break;
7429                                 }
7430                                 /*
7431                                  * New target device added into the system.
7432                                  * Set association flag according to if an
7433                                  * expander is used or not.
7434                                  */
7435                                 exp_flag =
7436                                     MPTSAS_TOPO_FLAG_EXPANDER_ATTACHED_DEVICE;
7437                                 if (flags ==
7438                                     MPTSAS_TOPO_FLAG_EXPANDER_ASSOCIATED) {
7439                                         flags = exp_flag;
7440                                 }
7441                                 topo_node = kmem_zalloc(
7442                                     sizeof (mptsas_topo_change_list_t),
7443                                     KM_SLEEP);
7444                                 topo_node->mpt = mpt;


7451                                          * device. So driver use PHY to decide
7452                                          * which iport is associated
7453                                          */
7454                                         physport = phy;
7455                                         mpt->m_port_chng = 1;
7456                                 }
7457                                 topo_node->un.physport = physport;
7458                                 topo_node->devhdl = dev_handle;
7459                                 topo_node->flags = flags;
7460                                 topo_node->object = NULL;
7461                                 if (topo_head == NULL) {
7462                                         topo_head = topo_tail = topo_node;
7463                                 } else {
7464                                         topo_tail->next = topo_node;
7465                                         topo_tail = topo_node;
7466                                 }
7467                                 break;
7468                         }
7469                         case MPI2_EVENT_SAS_TOPO_RC_TARG_NOT_RESPONDING:
7470                         {
7471                                 NDBG20(("mptsas3%d phy %d physical_port %d "
7472                                     "dev_handle %d removed", mpt->m_instance,
7473                                     phy, physport, dev_handle));
7474                                 /*
7475                                  * Set association flag according to if an
7476                                  * expander is used or not.
7477                                  */
7478                                 exp_flag =
7479                                     MPTSAS_TOPO_FLAG_EXPANDER_ATTACHED_DEVICE;
7480                                 if (flags ==
7481                                     MPTSAS_TOPO_FLAG_EXPANDER_ASSOCIATED) {
7482                                         flags = exp_flag;
7483                                 }
7484                                 /*
7485                                  * Target device is removed from the system
7486                                  * Before the device is really offline from
7487                                  * from system.
7488                                  */
7489                                 ptgt = refhash_linear_search(mpt->m_targets,
7490                                     mptsas_target_eval_devhdl, &dev_handle);
7491                                 /*
7492                                  * If ptgt is NULL here, it means that the
7493                                  * DevHandle is not in the hash table.  This is
7494                                  * reasonable sometimes.  For example, if a
7495                                  * disk was pulled, then added, then pulled
7496                                  * again, the disk will not have been put into
7497                                  * the hash table because the add event will
7498                                  * have an invalid phymask.  BUT, this does not
7499                                  * mean that the DevHandle is invalid.  The
7500                                  * controller will still have a valid DevHandle
7501                                  * that must be removed.  To do this, use the
7502                                  * MPTSAS_DR_EVENT_REMOVE_HANDLE event.
7503                                  */
7504                                 if (ptgt == NULL) {
7505                                         topo_node = kmem_zalloc(
7506                                             sizeof (mptsas_topo_change_list_t),
7507                                             KM_SLEEP);
7508                                         topo_node->mpt = mpt;
7509                                         topo_node->un.phymask = 0;
7510                                         topo_node->event =
7511                                             MPTSAS_DR_EVENT_REMOVE_HANDLE;
7512                                         topo_node->devhdl = dev_handle;
7513                                         topo_node->flags = flags;
7514                                         topo_node->object = NULL;
7515                                         if (topo_head == NULL) {
7516                                                 topo_head = topo_tail =
7517                                                     topo_node;
7518                                         } else {
7519                                                 topo_tail->next = topo_node;
7520                                                 topo_tail = topo_node;
7521                                         }
7522                                         break;
7523                                 }
7524 
7525                                 /*
7526                                  * Update DR flag immediately avoid I/O failure
7527                                  * before failover finish. We won't add
7528                                  * any following commands into waitq, instead,


7529                                  * we need return TRAN_BUSY in the tran_start
7530                                  * context.
7531                                  */

7532                                 ptgt->m_dr_flag = MPTSAS_DR_INTRANSITION;

7533 
7534                                 topo_node = kmem_zalloc(
7535                                     sizeof (mptsas_topo_change_list_t),
7536                                     KM_SLEEP);
7537                                 topo_node->mpt = mpt;
7538                                 topo_node->un.phymask =
7539                                     ptgt->m_addr.mta_phymask;
7540                                 topo_node->event =
7541                                     MPTSAS_DR_EVENT_OFFLINE_TARGET;
7542                                 topo_node->devhdl = dev_handle;
7543                                 topo_node->flags = flags;
7544                                 topo_node->object = NULL;
7545                                 if (topo_head == NULL) {
7546                                         topo_head = topo_tail = topo_node;
7547                                 } else {
7548                                         topo_tail->next = topo_node;
7549                                         topo_tail = topo_node;
7550                                 }
7551                                 break;
7552                         }


7604                                             (enc_handle == 1)) {
7605                                                 mpt->m_port_chng = 1;
7606                                         }
7607                                         mptsas_smhba_log_sysevent(mpt,
7608                                             ESC_SAS_PHY_EVENT,
7609                                             SAS_PHY_ONLINE,
7610                                             &mpt->m_phy_info[i].smhba_info);
7611                                         break;
7612                                 case MPI2_EVENT_SAS_TOPO_LR_RATE_6_0:
7613                                         (void) sprintf(curr, "is online at "
7614                                             "6.0 Gbps");
7615                                         if ((expd_handle == 0) &&
7616                                             (enc_handle == 1)) {
7617                                                 mpt->m_port_chng = 1;
7618                                         }
7619                                         mptsas_smhba_log_sysevent(mpt,
7620                                             ESC_SAS_PHY_EVENT,
7621                                             SAS_PHY_ONLINE,
7622                                             &mpt->m_phy_info[i].smhba_info);
7623                                         break;
7624                                 case MPI25_EVENT_SAS_TOPO_LR_RATE_12_0:
7625                                         (void) sprintf(curr, "is online at "
7626                                             "12.0 Gbps");
7627                                         if ((expd_handle == 0) &&
7628                                             (enc_handle == 1)) {
7629                                                 mpt->m_port_chng = 1;
7630                                         }
7631                                         mptsas_smhba_log_sysevent(mpt,
7632                                             ESC_SAS_PHY_EVENT,
7633                                             SAS_PHY_ONLINE,
7634                                             &mpt->m_phy_info[i].smhba_info);
7635                                         break;
7636                                 default:
7637                                         (void) sprintf(curr, "state is "
7638                                             "unknown");
7639                                         break;
7640                                 }
7641 
7642                                 state = (link_rate &
7643                                     MPI2_EVENT_SAS_TOPO_LR_PREV_MASK) >>
7644                                     MPI2_EVENT_SAS_TOPO_LR_PREV_SHIFT;
7645                                 switch (state) {
7646                                 case MPI2_EVENT_SAS_TOPO_LR_PHY_DISABLED:
7647                                         (void) sprintf(prev, ", was disabled");
7648                                         break;
7649                                 case MPI2_EVENT_SAS_TOPO_LR_NEGOTIATION_FAILED:
7650                                         (void) sprintf(prev, ", was offline, "
7651                                             "failed speed negotiation");
7652                                         break;
7653                                 case MPI2_EVENT_SAS_TOPO_LR_SATA_OOB_COMPLETE:
7654                                         (void) sprintf(prev, ", was SATA OOB "
7655                                             "complete");
7656                                         break;
7657                                 case SMP_RESET_IN_PROGRESS:
7658                                         (void) sprintf(prev, ", was SMP reset "
7659                                             "in progress");
7660                                         break;
7661                                 case MPI2_EVENT_SAS_TOPO_LR_RATE_1_5:
7662                                         (void) sprintf(prev, ", was online at "
7663                                             "1.5 Gbps");
7664                                         break;
7665                                 case MPI2_EVENT_SAS_TOPO_LR_RATE_3_0:
7666                                         (void) sprintf(prev, ", was online at "
7667                                             "3.0 Gbps");
7668                                         break;
7669                                 case MPI2_EVENT_SAS_TOPO_LR_RATE_6_0:
7670                                         (void) sprintf(prev, ", was online at "
7671                                             "6.0 Gbps");
7672                                         break;
7673                                 case MPI25_EVENT_SAS_TOPO_LR_RATE_12_0:
7674                                         (void) sprintf(prev, ", was online at "
7675                                             "12.0 Gbps");
7676                                         break;
7677                                 default:
7678                                 break;
7679                                 }
7680                                 (void) sprintf(&string[strlen(string)], "link "
7681                                     "changed, ");
7682                                 break;
7683                         case MPI2_EVENT_SAS_TOPO_RC_NO_CHANGE:
7684                                 continue;
7685                         case MPI2_EVENT_SAS_TOPO_RC_DELAY_NOT_RESPONDING:
7686                                 (void) sprintf(&string[strlen(string)],
7687                                     "target not responding, delaying "
7688                                     "removal");
7689                                 break;
7690                         }
7691                         NDBG20(("mptsas3%d phy %d DevHandle %x, %s%s%s\n",
7692                             mpt->m_instance, phy, dev_handle, string, curr,
7693                             prev));
7694                 }
7695                 if (topo_head != NULL) {
7696                         /*
7697                          * Launch DR taskq to handle topology change
7698                          */
7699                         if ((ddi_taskq_dispatch(mpt->m_dr_taskq,
7700                             mptsas_handle_dr, (void *)topo_head,
7701                             DDI_NOSLEEP)) != DDI_SUCCESS) {
7702                                 while (topo_head != NULL) {
7703                                         topo_node = topo_head;
7704                                         topo_head = topo_head->next;
7705                                         kmem_free(topo_node,
7706                                             sizeof (mptsas_topo_change_list_t));
7707                                 }
7708                                 mptsas_log(mpt, CE_NOTE, "mptsas start taskq "
7709                                     "for handle SAS DR event failed. \n");
7710                         }
7711                 }
7712                 break;
7713         }
7714         case MPI2_EVENT_IR_CONFIGURATION_CHANGE_LIST:
7715         {
7716                 Mpi2EventDataIrConfigChangeList_t       *irChangeList;
7717                 mptsas_topo_change_list_t               *topo_head = NULL;
7718                 mptsas_topo_change_list_t               *topo_tail = NULL;
7719                 mptsas_topo_change_list_t               *topo_node = NULL;
7720                 mptsas_target_t                         *ptgt;
7721                 uint8_t                                 num_entries, i, reason;
7722                 uint16_t                                volhandle, diskhandle;
7723 
7724                 irChangeList = (pMpi2EventDataIrConfigChangeList_t)
7725                     eventreply->EventData;
7726                 num_entries = ddi_get8(mpt->m_acc_reply_frame_hdl,
7727                     &irChangeList->NumElements);
7728 
7729                 NDBG20(("mptsas3%d IR_CONFIGURATION_CHANGE_LIST event received",
7730                     mpt->m_instance));
7731 
7732                 for (i = 0; i < num_entries; i++) {
7733                         reason = ddi_get8(mpt->m_acc_reply_frame_hdl,
7734                             &irChangeList->ConfigElement[i].ReasonCode);
7735                         volhandle = ddi_get16(mpt->m_acc_reply_frame_hdl,
7736                             &irChangeList->ConfigElement[i].VolDevHandle);
7737                         diskhandle = ddi_get16(mpt->m_acc_reply_frame_hdl,
7738                             &irChangeList->ConfigElement[i].PhysDiskDevHandle);
7739 
7740                         switch (reason) {
7741                         case MPI2_EVENT_IR_CHANGE_RC_ADDED:
7742                         case MPI2_EVENT_IR_CHANGE_RC_VOLUME_CREATED:
7743                         {
7744                                 NDBG20(("mptsas %d volume added\n",
7745                                     mpt->m_instance));
7746 
7747                                 topo_node = kmem_zalloc(
7748                                     sizeof (mptsas_topo_change_list_t),
7749                                     KM_SLEEP);


7765                                 break;
7766                         }
7767                         case MPI2_EVENT_IR_CHANGE_RC_REMOVED:
7768                         case MPI2_EVENT_IR_CHANGE_RC_VOLUME_DELETED:
7769                         {
7770                                 NDBG20(("mptsas %d volume deleted\n",
7771                                     mpt->m_instance));
7772                                 ptgt = refhash_linear_search(mpt->m_targets,
7773                                     mptsas_target_eval_devhdl, &volhandle);
7774                                 if (ptgt == NULL)
7775                                         break;
7776 
7777                                 /*
7778                                  * Clear any flags related to volume
7779                                  */
7780                                 (void) mptsas_delete_volume(mpt, volhandle);
7781 
7782                                 /*
7783                                  * Update DR flag immediately avoid I/O failure
7784                                  */

7785                                 ptgt->m_dr_flag = MPTSAS_DR_INTRANSITION;

7786 
7787                                 topo_node = kmem_zalloc(
7788                                     sizeof (mptsas_topo_change_list_t),
7789                                     KM_SLEEP);
7790                                 topo_node->mpt = mpt;
7791                                 topo_node->un.phymask =
7792                                     ptgt->m_addr.mta_phymask;
7793                                 topo_node->event =
7794                                     MPTSAS_DR_EVENT_OFFLINE_TARGET;
7795                                 topo_node->devhdl = volhandle;
7796                                 topo_node->flags =
7797                                     MPTSAS_TOPO_FLAG_RAID_ASSOCIATED;
7798                                 topo_node->object = (void *)ptgt;
7799                                 if (topo_head == NULL) {
7800                                         topo_head = topo_tail = topo_node;
7801                                 } else {
7802                                         topo_tail->next = topo_node;
7803                                         topo_tail = topo_node;
7804                                 }
7805                                 break;
7806                         }
7807                         case MPI2_EVENT_IR_CHANGE_RC_PD_CREATED:
7808                         case MPI2_EVENT_IR_CHANGE_RC_HIDE:
7809                         {
7810                                 ptgt = refhash_linear_search(mpt->m_targets,
7811                                     mptsas_target_eval_devhdl, &diskhandle);
7812                                 if (ptgt == NULL)
7813                                         break;
7814 
7815                                 /*
7816                                  * Update DR flag immediately avoid I/O failure
7817                                  */

7818                                 ptgt->m_dr_flag = MPTSAS_DR_INTRANSITION;

7819 
7820                                 topo_node = kmem_zalloc(
7821                                     sizeof (mptsas_topo_change_list_t),
7822                                     KM_SLEEP);
7823                                 topo_node->mpt = mpt;
7824                                 topo_node->un.phymask =
7825                                     ptgt->m_addr.mta_phymask;
7826                                 topo_node->event =
7827                                     MPTSAS_DR_EVENT_OFFLINE_TARGET;
7828                                 topo_node->devhdl = diskhandle;
7829                                 topo_node->flags =
7830                                     MPTSAS_TOPO_FLAG_RAID_PHYSDRV_ASSOCIATED;
7831                                 topo_node->object = (void *)ptgt;
7832                                 if (topo_head == NULL) {
7833                                         topo_head = topo_tail = topo_node;
7834                                 } else {
7835                                         topo_tail->next = topo_node;
7836                                         topo_tail = topo_node;
7837                                 }
7838                                 break;


7862                                 if (topo_head == NULL) {
7863                                         topo_head = topo_tail = topo_node;
7864                                 } else {
7865                                         topo_tail->next = topo_node;
7866                                         topo_tail = topo_node;
7867                                 }
7868                                 break;
7869                         }
7870                         default:
7871                                 break;
7872                         }
7873                 }
7874 
7875                 if (topo_head != NULL) {
7876                         /*
7877                          * Launch DR taskq to handle topology change
7878                          */
7879                         if ((ddi_taskq_dispatch(mpt->m_dr_taskq,
7880                             mptsas_handle_dr, (void *)topo_head,
7881                             DDI_NOSLEEP)) != DDI_SUCCESS) {
7882                                 while (topo_head != NULL) {
7883                                         topo_node = topo_head;
7884                                         topo_head = topo_head->next;
7885                                         kmem_free(topo_node,
7886                                             sizeof (mptsas_topo_change_list_t));
7887                                 }
7888                                 mptsas_log(mpt, CE_NOTE, "mptsas start taskq "
7889                                     "for handle SAS DR event failed. \n");
7890                         }
7891                 }
7892                 break;
7893         }
7894         default:
7895                 return (DDI_FAILURE);
7896         }
7897 
7898         return (DDI_SUCCESS);
7899 }
7900 
7901 /*
7902  * handle events from ioc
7903  */
7904 static void
7905 mptsas_handle_event(void *args)
7906 {
7907         m_replyh_arg_t                  *replyh_arg;


7910         uint32_t                        status;
7911         uint8_t                         port;
7912         mptsas_t                        *mpt;
7913         uint_t                          iocstatus;
7914 
7915         replyh_arg = (m_replyh_arg_t *)args;
7916         rfm = replyh_arg->rfm;
7917         mpt = replyh_arg->mpt;
7918 
7919         mutex_enter(&mpt->m_mutex);
7920         /*
7921          * If HBA is being reset, drop incoming event.
7922          */
7923         if (mpt->m_in_reset) {
7924                 NDBG20(("dropping event received prior to reset"));
7925                 mutex_exit(&mpt->m_mutex);
7926                 return;
7927         }
7928 
7929         eventreply = (pMpi2EventNotificationReply_t)
7930             (mpt->m_reply_frame + (rfm -
7931             (mpt->m_reply_frame_dma_addr&0xfffffffful)));
7932         event = ddi_get16(mpt->m_acc_reply_frame_hdl, &eventreply->Event);
7933 
7934         if (iocstatus = ddi_get16(mpt->m_acc_reply_frame_hdl,
7935             &eventreply->IOCStatus)) {
7936                 if (iocstatus == MPI2_IOCSTATUS_FLAG_LOG_INFO_AVAILABLE) {
7937                         mptsas_log(mpt, CE_WARN,
7938                             "!mptsas_handle_event: IOCStatus=0x%x, "
7939                             "IOCLogInfo=0x%x", iocstatus,
7940                             ddi_get32(mpt->m_acc_reply_frame_hdl,
7941                             &eventreply->IOCLogInfo));
7942                 } else {
7943                         mptsas_log(mpt, CE_WARN,
7944                             "mptsas_handle_event: IOCStatus=0x%x, "
7945                             "IOCLogInfo=0x%x", iocstatus,
7946                             ddi_get32(mpt->m_acc_reply_frame_hdl,
7947                             &eventreply->IOCLogInfo));
7948                 }
7949         }
7950 
7951         /*
7952          * figure out what kind of event we got and handle accordingly
7953          */
7954         switch (event) {
7955         case MPI2_EVENT_LOG_ENTRY_ADDED:
7956                 break;
7957         case MPI2_EVENT_LOG_DATA:
7958                 iocloginfo = ddi_get32(mpt->m_acc_reply_frame_hdl,
7959                     &eventreply->IOCLogInfo);
7960                 NDBG20(("mptsas %d log info %x received.\n", mpt->m_instance,
7961                     iocloginfo));
7962                 break;
7963         case MPI2_EVENT_STATE_CHANGE:
7964                 NDBG20(("mptsas3%d state change.", mpt->m_instance));
7965                 break;
7966         case MPI2_EVENT_HARD_RESET_RECEIVED:
7967                 NDBG20(("mptsas3%d event change.", mpt->m_instance));
7968                 break;
7969         case MPI2_EVENT_SAS_DISCOVERY:
7970         {
7971                 MPI2_EVENT_DATA_SAS_DISCOVERY   *sasdiscovery;
7972                 char                            string[80];
7973                 uint8_t                         rc;
7974 
7975                 sasdiscovery =
7976                     (pMpi2EventDataSasDiscovery_t)eventreply->EventData;
7977 
7978                 rc = ddi_get8(mpt->m_acc_reply_frame_hdl,
7979                     &sasdiscovery->ReasonCode);
7980                 port = ddi_get8(mpt->m_acc_reply_frame_hdl,
7981                     &sasdiscovery->PhysicalPort);
7982                 status = ddi_get32(mpt->m_acc_reply_frame_hdl,
7983                     &sasdiscovery->DiscoveryStatus);
7984 
7985                 string[0] = 0;
7986                 switch (rc) {
7987                 case MPI2_EVENT_SAS_DISC_RC_STARTED:
7988                         (void) sprintf(string, "STARTING");
7989                         break;
7990                 case MPI2_EVENT_SAS_DISC_RC_COMPLETED:
7991                         (void) sprintf(string, "COMPLETED");
7992                         break;
7993                 default:
7994                         (void) sprintf(string, "UNKNOWN");
7995                         break;
7996                 }
7997 
7998                 NDBG20(("SAS DISCOVERY is %s for port %d, status %x", string,
7999                     port, status));
8000 
8001                 break;
8002         }
8003         case MPI2_EVENT_EVENT_CHANGE:
8004                 NDBG20(("mptsas3%d event change.", mpt->m_instance));
8005                 break;
8006         case MPI2_EVENT_TASK_SET_FULL:
8007         {
8008                 pMpi2EventDataTaskSetFull_t     taskfull;
8009 
8010                 taskfull = (pMpi2EventDataTaskSetFull_t)eventreply->EventData;
8011 
8012                 NDBG20(("TASK_SET_FULL received for mptsas3%d, depth %d\n",
8013                     mpt->m_instance,  ddi_get16(mpt->m_acc_reply_frame_hdl,
8014                     &taskfull->CurrentDepth)));
8015                 break;
8016         }
8017         case MPI2_EVENT_SAS_TOPOLOGY_CHANGE_LIST:
8018         {
8019                 /*
8020                  * SAS TOPOLOGY CHANGE LIST Event has already been handled
8021                  * in mptsas_handle_event_sync() of interrupt context
8022                  */
8023                 break;
8024         }
8025         case MPI2_EVENT_SAS_ENCL_DEVICE_STATUS_CHANGE:
8026         {
8027                 pMpi2EventDataSasEnclDevStatusChange_t  encstatus;
8028                 uint8_t                                 rc;
8029                 char                                    string[80];
8030 
8031                 encstatus = (pMpi2EventDataSasEnclDevStatusChange_t)
8032                     eventreply->EventData;
8033 
8034                 rc = ddi_get8(mpt->m_acc_reply_frame_hdl,
8035                     &encstatus->ReasonCode);
8036                 switch (rc) {
8037                 case MPI2_EVENT_SAS_ENCL_RC_ADDED:
8038                         (void) sprintf(string, "added");
8039                         break;
8040                 case MPI2_EVENT_SAS_ENCL_RC_NOT_RESPONDING:
8041                         (void) sprintf(string, ", not responding");
8042                         break;
8043                 default:
8044                 break;
8045                 }
8046                 NDBG20(("mptsas3%d ENCLOSURE STATUS CHANGE for enclosure "
8047                     "%x%s\n", mpt->m_instance,
8048                     ddi_get16(mpt->m_acc_reply_frame_hdl,
8049                     &encstatus->EnclosureHandle), string));
8050                 break;
8051         }
8052 
8053         /*
8054          * MPI2_EVENT_SAS_DEVICE_STATUS_CHANGE is handled by
8055          * mptsas_handle_event_sync,in here just send ack message.
8056          */
8057         case MPI2_EVENT_SAS_DEVICE_STATUS_CHANGE:
8058         {
8059                 pMpi2EventDataSasDeviceStatusChange_t   statuschange;
8060                 uint8_t                                 rc;
8061                 uint16_t                                devhdl;
8062                 uint64_t                                wwn = 0;
8063                 uint32_t                                wwn_lo, wwn_hi;
8064 
8065                 statuschange = (pMpi2EventDataSasDeviceStatusChange_t)
8066                     eventreply->EventData;
8067                 rc = ddi_get8(mpt->m_acc_reply_frame_hdl,
8068                     &statuschange->ReasonCode);


8153                     &irOpStatus->PercentComplete);
8154                 handle = ddi_get16(mpt->m_acc_reply_frame_hdl,
8155                     &irOpStatus->VolDevHandle);
8156 
8157                 switch (rc) {
8158                         case MPI2_EVENT_IR_RAIDOP_RESYNC:
8159                                 (void) sprintf(reason_str, "resync");
8160                                 break;
8161                         case MPI2_EVENT_IR_RAIDOP_ONLINE_CAP_EXPANSION:
8162                                 (void) sprintf(reason_str, "online capacity "
8163                                     "expansion");
8164                                 break;
8165                         case MPI2_EVENT_IR_RAIDOP_CONSISTENCY_CHECK:
8166                                 (void) sprintf(reason_str, "consistency check");
8167                                 break;
8168                         default:
8169                                 (void) sprintf(reason_str, "unknown reason %x",
8170                                     rc);
8171                 }
8172 
8173                 NDBG20(("mptsas3%d raid operational status: (%s)"
8174                     "\thandle(0x%04x), percent complete(%d)\n",
8175                     mpt->m_instance, reason_str, handle, percent));
8176                 break;
8177         }
8178         case MPI2_EVENT_SAS_BROADCAST_PRIMITIVE:
8179         {
8180                 pMpi2EventDataSasBroadcastPrimitive_t   sas_broadcast;
8181                 uint8_t                                 phy_num;
8182                 uint8_t                                 primitive;
8183 
8184                 sas_broadcast = (pMpi2EventDataSasBroadcastPrimitive_t)
8185                     eventreply->EventData;
8186 
8187                 phy_num = ddi_get8(mpt->m_acc_reply_frame_hdl,
8188                     &sas_broadcast->PhyNum);
8189                 primitive = ddi_get8(mpt->m_acc_reply_frame_hdl,
8190                     &sas_broadcast->Primitive);
8191 
8192                 switch (primitive) {
8193                 case MPI2_EVENT_PRIMITIVE_CHANGE:


8222                         break;
8223                 case MPI2_EVENT_PRIMITIVE_RESERVED4:
8224                         mptsas_smhba_log_sysevent(mpt,
8225                             ESC_SAS_HBA_PORT_BROADCAST,
8226                             SAS_PORT_BROADCAST_D29_7,
8227                             &mpt->m_phy_info[phy_num].smhba_info);
8228                         break;
8229                 case MPI2_EVENT_PRIMITIVE_CHANGE0_RESERVED:
8230                         mptsas_smhba_log_sysevent(mpt,
8231                             ESC_SAS_HBA_PORT_BROADCAST,
8232                             SAS_PORT_BROADCAST_D24_0,
8233                             &mpt->m_phy_info[phy_num].smhba_info);
8234                         break;
8235                 case MPI2_EVENT_PRIMITIVE_CHANGE1_RESERVED:
8236                         mptsas_smhba_log_sysevent(mpt,
8237                             ESC_SAS_HBA_PORT_BROADCAST,
8238                             SAS_PORT_BROADCAST_D27_4,
8239                             &mpt->m_phy_info[phy_num].smhba_info);
8240                         break;
8241                 default:
8242                         NDBG16(("mptsas3%d: unknown BROADCAST PRIMITIVE"
8243                             " %x received",
8244                             mpt->m_instance, primitive));
8245                         break;
8246                 }
8247                 NDBG16(("mptsas3%d sas broadcast primitive: "
8248                     "\tprimitive(0x%04x), phy(%d) complete\n",
8249                     mpt->m_instance, primitive, phy_num));
8250                 break;
8251         }
8252         case MPI2_EVENT_IR_VOLUME:
8253         {
8254                 Mpi2EventDataIrVolume_t         *irVolume;
8255                 uint16_t                        devhandle;
8256                 uint32_t                        state;
8257                 int                             config, vol;
8258                 uint8_t                         found = FALSE;
8259 
8260                 irVolume = (pMpi2EventDataIrVolume_t)eventreply->EventData;
8261                 state = ddi_get32(mpt->m_acc_reply_frame_hdl,
8262                     &irVolume->NewValue);
8263                 devhandle = ddi_get16(mpt->m_acc_reply_frame_hdl,
8264                     &irVolume->VolDevHandle);
8265 
8266                 NDBG20(("EVENT_IR_VOLUME event is received"));
8267 


8433                             state == MPI2_RAID_PD_STATE_REBUILDING
8434                             ? "rebuilding" :
8435                             state == MPI2_RAID_PD_STATE_DEGRADED
8436                             ? "degraded" :
8437                             state == MPI2_RAID_PD_STATE_HOT_SPARE
8438                             ? "a hot spare" :
8439                             state == MPI2_RAID_PD_STATE_ONLINE
8440                             ? "online" :
8441                             state == MPI2_RAID_PD_STATE_OFFLINE
8442                             ? "offline" :
8443                             state == MPI2_RAID_PD_STATE_NOT_COMPATIBLE
8444                             ? "not compatible" :
8445                             state == MPI2_RAID_PD_STATE_NOT_CONFIGURED
8446                             ? "not configured" :
8447                             "state unknown");
8448                         break;
8449                 }
8450                 break;
8451         }
8452         default:
8453                 NDBG20(("mptsas3%d: unknown event %x received",
8454                     mpt->m_instance, event));
8455                 break;
8456         }
8457 
8458         /*
8459          * Return the reply frame to the free queue.
8460          */
8461         ddi_put32(mpt->m_acc_free_queue_hdl,
8462             &((uint32_t *)(void *)mpt->m_free_queue)[mpt->m_free_index], rfm);
8463         (void) ddi_dma_sync(mpt->m_dma_free_queue_hdl, 0, 0,
8464             DDI_DMA_SYNC_FORDEV);
8465         if (++mpt->m_free_index == mpt->m_free_queue_depth) {
8466                 mpt->m_free_index = 0;
8467         }
8468         ddi_put32(mpt->m_datap, &mpt->m_reg->ReplyFreeHostIndex,
8469             mpt->m_free_index);
8470         mutex_exit(&mpt->m_mutex);
8471 }
8472 
8473 /*
8474  * invoked from timeout() to restart qfull cmds with throttle == 0
8475  */
8476 static void
8477 mptsas_restart_cmd(void *arg)
8478 {
8479         mptsas_t        *mpt = arg;
8480         mptsas_target_t *ptgt = NULL;
8481 
8482         mutex_enter(&mpt->m_mutex);
8483 
8484         mpt->m_restart_cmd_timeid = 0;
8485 
8486         for (ptgt = refhash_first(mpt->m_targets); ptgt != NULL;
8487             ptgt = refhash_next(mpt->m_targets, ptgt)) {
8488                 mutex_enter(&ptgt->m_t_mutex);
8489                 if (ptgt->m_reset_delay == 0) {
8490                         if (ptgt->m_t_throttle == QFULL_THROTTLE) {
8491                                 mptsas_set_throttle(mpt, ptgt,
8492                                     MAX_THROTTLE);
8493                         }
8494                 }
8495                 mutex_exit(&ptgt->m_t_mutex);
8496         }
8497         mptsas_restart_hba(mpt);
8498         mutex_exit(&mpt->m_mutex);
8499 }
8500 
8501 /*
8502  * Assume some checks have been done prior to calling this
8503  * function so we don't need to consider taking the m_mutex.
8504  */
8505 static void
8506 mptsas_remove_cmd_nomtx(mptsas_t *mpt, mptsas_cmd_t *cmd)
8507 {
8508         int             slot;
8509         mptsas_slots_t  *slots = mpt->m_active;
8510         mptsas_target_t *ptgt = cmd->cmd_tgt_addr;
8511 
8512         ASSERT(cmd != NULL);
8513         ASSERT(cmd->cmd_queued == FALSE);
8514         ASSERT((cmd->cmd_flags & CFLAG_CMDIOC) == 0);
8515 
8516         slot = cmd->cmd_slot;
8517 
8518         /*
8519          * remove the cmd.
8520          */
8521         if (cmd == slots->m_slot[slot]) {
8522                 NDBG31(("mptsas_remove_cmd_nomtx: removing cmd=0x%p, flags "
8523                     "0x%x", (void *)cmd, cmd->cmd_flags));
8524                 slots->m_slot[slot] = NULL;
8525                 ASSERT(mpt->m_ncmds != 0);
8526                 atomic_dec_32(&mpt->m_ncmds);
8527                 ASSERT(mpt->m_rep_post_queues[cmd->cmd_rpqidx].rpq_ncmds != 0);
8528                 atomic_dec_32(
8529                     &mpt->m_rep_post_queues[cmd->cmd_rpqidx].rpq_ncmds);
8530 
8531                 /*
8532                  * Decrement per target ncmds, we know this is not an
8533                  * IOC cmd and it therefore has a target associated with it.
8534                  */
8535                 mutex_enter(&ptgt->m_t_mutex);
8536                 ASSERT(ptgt->m_t_ncmds != 0);
8537                 ptgt->m_t_ncmds--;
8538 
8539                 /*
8540                  * reset throttle if we just ran an untagged command
8541                  * to a tagged target
8542                  */
8543                 if ((ptgt->m_t_ncmds == 0) &&
8544                     ((cmd->cmd_pkt_flags & FLAG_TAGMASK) == 0)) {
8545                         mptsas_set_throttle(mpt, ptgt, MAX_THROTTLE);
8546                 }
8547 
8548                 /*
8549                  * Remove this command from the active queue.
8550                  */
8551                 if (cmd->cmd_active_expiration != 0) {
8552                         TAILQ_REMOVE(&ptgt->m_active_cmdq, cmd,
8553                             cmd_active_link);
8554                         cmd->cmd_active_expiration = 0;
8555                 }
8556                 mutex_exit(&ptgt->m_t_mutex);
8557         }
8558 
8559         ASSERT(cmd != slots->m_slot[cmd->cmd_slot]);
8560 }
8561 
8562 void
8563 mptsas_remove_cmd(mptsas_t *mpt, mptsas_cmd_t *cmd)
8564 {
8565         int             slot;
8566         mptsas_slots_t  *slots = mpt->m_active;

8567         mptsas_target_t *ptgt = cmd->cmd_tgt_addr;
8568 
8569         ASSERT(cmd != NULL);
8570         ASSERT(cmd->cmd_queued == FALSE);
8571 
8572         /*
8573          * Task Management cmds are removed in their own routines.  Also,
8574          * we don't want to modify timeout based on TM cmds.
8575          */
8576         if (cmd->cmd_flags & CFLAG_TM_CMD) {
8577                 return;
8578         }
8579 

8580         slot = cmd->cmd_slot;
8581 
8582         /*
8583          * remove the cmd.
8584          */
8585         if (cmd == slots->m_slot[slot]) {
8586                 NDBG31(("mptsas_remove_cmd: removing cmd=0x%p, flags 0x%x",
8587                     (void *)cmd, cmd->cmd_flags));
8588                 slots->m_slot[slot] = NULL;
8589                 ASSERT(mpt->m_ncmds != 0);
8590                 atomic_dec_32(&mpt->m_ncmds);
8591                 ASSERT(mpt->m_rep_post_queues[cmd->cmd_rpqidx].rpq_ncmds != 0);
8592                 atomic_dec_32(
8593                     &mpt->m_rep_post_queues[cmd->cmd_rpqidx].rpq_ncmds);
8594 
8595                 /*
8596                  * only decrement per target ncmds if command
8597                  * has a target associated with it.
8598                  */
8599                 if ((cmd->cmd_flags & CFLAG_CMDIOC) == 0) {
8600                         mutex_enter(&ptgt->m_t_mutex);
8601                         ASSERT(ptgt->m_t_ncmds != 0);
8602                         ptgt->m_t_ncmds--;
8603 
8604                         /*
8605                          * reset throttle if we just ran an untagged command
8606                          * to a tagged target
8607                          */
8608                         if ((ptgt->m_t_ncmds == 0) &&
8609                             ((cmd->cmd_pkt_flags & FLAG_TAGMASK) == 0)) {
8610                                 mptsas_set_throttle(mpt, ptgt, MAX_THROTTLE);
8611                         }
8612 
8613                         /*
8614                          * Remove this command from the active queue.
8615                          */
8616                         if (cmd->cmd_active_expiration != 0) {
8617                                 TAILQ_REMOVE(&ptgt->m_active_cmdq, cmd,
8618                                     cmd_active_link);
8619                                 cmd->cmd_active_expiration = 0;
8620                         }
8621                         mutex_exit(&ptgt->m_t_mutex);
8622                 }
8623 
8624         }
8625 
8626         /*
8627          * This is all we need to do for ioc commands.
8628          */
8629         if (cmd->cmd_flags & CFLAG_CMDIOC) {
8630                 mptsas_return_to_pool(mpt, cmd);
8631                 return;
8632         }
8633 












































8634         ASSERT(cmd != slots->m_slot[cmd->cmd_slot]);
8635 }
8636 
8637 /*
8638  * accept all cmds on the tx_waitq if any and then
8639  * start a fresh request from the top of the device queue.
8640  *
8641  * since there are always cmds queued on the tx_waitq, and rare cmds on
8642  * the instance waitq, so this function should not be invoked in the ISR,
8643  * the mptsas_restart_waitq() is invoked in the ISR instead. otherwise, the
8644  * burden belongs to the IO dispatch CPUs is moved the interrupt CPU.
8645  */
8646 static void
8647 mptsas_restart_hba(mptsas_t *mpt)
8648 {
8649         ASSERT(mutex_owned(&mpt->m_mutex));
8650 
8651         mptsas_accept_tx_waitqs(mpt);




8652         mptsas_restart_waitq(mpt);
8653 }
8654 
8655 /*
8656  * start a fresh request from the top of the device queue
8657  */
8658 static void
8659 mptsas_restart_waitq(mptsas_t *mpt)
8660 {
8661         mptsas_cmd_t    *cmd, *next_cmd;
8662         mptsas_target_t *ptgt = NULL;
8663 
8664         NDBG1(("mptsas_restart_waitq: mpt=0x%p", (void *)mpt));
8665 
8666         ASSERT(mutex_owned(&mpt->m_mutex));
8667 
8668         /*
8669          * If there is a reset delay, don't start any cmds.  Otherwise, start
8670          * as many cmds as possible.
8671          * Since SMID 0 is reserved and the TM slot is reserved, the actual max


8699                                 mptsas_start_config_page_access(mpt, cmd);
8700                         }
8701                         cmd = next_cmd;
8702                         continue;
8703                 }
8704                 if (cmd->cmd_flags & CFLAG_FW_DIAG) {
8705                         if (mptsas_save_cmd(mpt, cmd) == TRUE) {
8706                                 /*
8707                                  * Send the FW Diag request and delete if from
8708                                  * the waitq.
8709                                  */
8710                                 cmd->cmd_flags |= CFLAG_PREPARED;
8711                                 mptsas_waitq_delete(mpt, cmd);
8712                                 mptsas_start_diag(mpt, cmd);
8713                         }
8714                         cmd = next_cmd;
8715                         continue;
8716                 }
8717 
8718                 ptgt = cmd->cmd_tgt_addr;
8719                 if (ptgt) {
8720                         mutex_enter(&ptgt->m_t_mutex);
8721                         if ((ptgt->m_t_throttle == DRAIN_THROTTLE) &&
8722                             (ptgt->m_t_ncmds == 0)) {
8723                                 mptsas_set_throttle(mpt, ptgt, MAX_THROTTLE);
8724                         }
8725                         if ((mpt->m_ncmds <= (mpt->m_max_requests - 2)) &&
8726                             (ptgt->m_reset_delay == 0) &&
8727                             (ptgt->m_t_ncmds < ptgt->m_t_throttle)) {
8728                                 mutex_exit(&ptgt->m_t_mutex);
8729 
8730                                 if (mptsas_save_cmd(mpt, cmd) == TRUE) {
8731                                         mptsas_waitq_delete(mpt, cmd);
8732                                         mutex_exit(&mpt->m_mutex);
8733                                         (void) mptsas_start_cmd(mpt, cmd);
8734                                         mutex_enter(&mpt->m_mutex);
8735                                         cmd = mpt->m_waitq;
8736                                         continue;
8737                                 }
8738                         } else {
8739                                 mutex_exit(&ptgt->m_t_mutex);
8740                         }
8741                 }
8742                 cmd = next_cmd;
8743         }
8744 }
8745 
8746 /*
8747  * Cmds are queued if scsi_start() doesn't get the m_mutex lock(no wait)
8748  * or if the decision has been made to always do that. Setting
8749  * mptsas_allow_txq_jumping to zero will allow higher performance on
8750  * a heavily loaded system as there is less disruption to the flow here.
8751  * There are 2 threads that handle one queue each. The idea is that
8752  * they take it in turn to grab the m_mutex to run the mptsas_accept_pkt()
8753  * function and then drop it while the cmd is started in mptsas_start_cmd().
8754  */
8755 static void
8756 mptsas_tx_waitq_thread(mptsas_thread_arg_t *arg)
8757 {
8758         mptsas_t *mpt = arg->mpt;
8759         mptsas_tx_waitqueue_t *txwq = &mpt->m_tx_waitq[arg->t];
8760 
8761         mutex_enter(&txwq->txwq_mutex);
8762         while (txwq->txwq_active) {
8763                 mptsas_drain_tx_waitq(mpt, txwq);
8764                 if (txwq->txwq_wdrain) {
8765                         cv_signal(&txwq->txwq_drain_cv);
8766                 }
8767                 cv_wait(&txwq->txwq_cv, &txwq->txwq_mutex);
8768         }
8769         mutex_exit(&txwq->txwq_mutex);
8770         mutex_enter(&mpt->m_qthread_mutex);
8771         mpt->m_txwq_thread_n--;
8772         cv_broadcast(&mpt->m_qthread_cv);
8773         mutex_exit(&mpt->m_qthread_mutex);
8774 }
8775 
8776 /*
8777  * Set the draining flag, disconnect the list and process one at a time
8778  * so that the cmds are sent in order.
8779  */
8780 static void
8781 mptsas_drain_tx_waitq(mptsas_t *mpt, mptsas_tx_waitqueue_t *txwq)
8782 {
8783         mptsas_cmd_t    *cmd, *ncmd;
8784         int             rval, start;
8785 #ifdef MPTSAS_DEBUG
8786         uint32_t        qlen;
8787 #endif
8788 
8789         txwq->txwq_draining = TRUE;
8790 #ifndef __lock_lint
8791         _NOTE(CONSTCOND)
8792 #endif
8793         while (TRUE) {
8794 
8795                 /*
8796                  * A Bus Reset could occur at any time but it will have to
8797                  * wait for the main mutex before flushing the tx_waitq.
8798                  * Pull all commands at once, then follow the list in order to
8799                  * reduce txwq_mutex hold time. If there is a Bus Reset at
8800                  * some point the commands will get to the waitq and then be
8801                  * flushed.
8802                  */
8803                 cmd = txwq->txwq_cmdq;
8804 
8805                 if (cmd == NULL) {
8806                         txwq->txwq_draining = FALSE;
8807                         return;
8808                 }
8809                 txwq->txwq_cmdq = NULL;
8810                 txwq->txwq_qtail = &txwq->txwq_cmdq;
8811 #ifdef MPTSAS_DEBUG
8812                 qlen = txwq->txwq_len;
8813 #endif
8814                 txwq->txwq_len = 0;
8815                 mutex_exit(&txwq->txwq_mutex);
8816 
8817                 while (cmd) {
8818                         ncmd = cmd->cmd_linkp;
8819                         cmd->cmd_linkp = NULL;
8820                         mutex_enter(&mpt->m_mutex);
8821                         start = mptsas_accept_pkt(mpt, cmd, &rval);
8822                         mutex_exit(&mpt->m_mutex);
8823                         if (start) {
8824                                 (void) mptsas_start_cmd(mpt, cmd);
8825                         }
8826                         if (rval != TRAN_ACCEPT)
8827                                 cmn_err(CE_WARN,
8828                                     "mpt: mptsas_drain_tx_waitq: failed "
8829                                     "(rval=0x%x) to accept cmd 0x%p on queue\n",
8830                                     rval, (void *)cmd);
8831                         cmd = ncmd;
8832 #ifdef MPTSAS_DEBUG
8833                         qlen--;
8834 #endif
8835                 }
8836                 ASSERT(qlen == 0);
8837                 mutex_enter(&txwq->txwq_mutex);
8838         }
8839 }
8840 
8841 /*
8842  * Stop the drain threads from picking up a new list.
8843  * Optionally wait for the current list being processed to drain through.
8844  * Add to and processing the tx waitq is now on hold until unblock is called.
8845  */
8846 static void
8847 mptsas_block_tx_waitqs(mptsas_t *mpt, int wait)
8848 {
8849         int             i;
8850         uint8_t         wdrain = 0;
8851         mptsas_tx_waitqueue_t *txwq;
8852 
8853         ASSERT(mutex_owned(&mpt->m_mutex));
8854 
8855         if (mpt->m_txwq_thread_n == 0) {
8856                 return;
8857         }
8858 
8859         /*
8860          * Turn off the use of the tx wait queues by scsi_start().
8861          * This is just a dynamic flag no need for a mutex.


8862          */
8863         mpt->m_txwq_enabled = BLOCKED;
8864 
8865         for (i = 0; i < NUM_TX_WAITQ; i++) {
8866                 txwq = &mpt->m_tx_waitq[i];
8867                 mutex_enter(&txwq->txwq_mutex);
8868                 txwq->txwq_wdrain = TRUE;
8869                 if (txwq->txwq_draining && wait)
8870                         wdrain |= (1<<i);
8871                 mutex_exit(&txwq->txwq_mutex);
8872         }
8873 
8874         if (wdrain) {
8875                 /*
8876                  * Because the threads disconnect the entire queue each time
8877                  * round in order to drain to completely drain we have to
8878                  * drop the main mutex otherwise the drain threads get stuck.
8879                  */
8880                 mutex_exit(&mpt->m_mutex);
8881                 for (i = 0; i < NUM_TX_WAITQ; i++) {
8882                         if (wdrain & (1<<i)) {
8883                                 txwq = &mpt->m_tx_waitq[i];
8884                                 mutex_enter(&txwq->txwq_mutex);
8885                                 while (txwq->txwq_draining) {
8886                                         cv_wait(&txwq->txwq_drain_cv,
8887                                             &txwq->txwq_mutex);
8888                                 }
8889                                 mutex_exit(&txwq->txwq_mutex);

8890                         }






8891                 }
8892                 mutex_enter(&mpt->m_mutex);
8893         }
8894 }
8895 
8896 static void
8897 mptsas_unblock_tx_waitqs(mptsas_t *mpt)
8898 {
8899         int                     i;
8900         mptsas_tx_waitqueue_t   *txwq;
8901 
8902         if (mpt->m_txwq_thread_n == 0) {
8903                 return;
8904         }
8905 
8906         for (i = 0; i < NUM_TX_WAITQ; i++) {
8907                 txwq = &mpt->m_tx_waitq[i];
8908                 mutex_enter(&txwq->txwq_mutex);
8909                 txwq->txwq_wdrain = FALSE;
8910                 cv_signal(&txwq->txwq_cv);
8911                 mutex_exit(&txwq->txwq_mutex);
8912         }
8913 
8914         mpt->m_txwq_enabled = FALSE;
8915 }
8916 
8917 static void
8918 mptsas_accept_tx_waitqs(mptsas_t *mpt)
8919 {
8920         /*
8921          * Block with drain and unblock will leave us in a state where
8922          * we have the main mutex, there is nothing on the tx wait queues
8923          * and they are not in use until watch notices high activity again.
8924          */
8925         mptsas_block_tx_waitqs(mpt, 1);
8926         mptsas_unblock_tx_waitqs(mpt);
8927 }
8928 
8929 /*
8930  * mpt tag type lookup
8931  */
8932 static char mptsas_tag_lookup[] =
8933         {0, MSG_HEAD_QTAG, MSG_ORDERED_QTAG, 0, MSG_SIMPLE_QTAG};
8934 
8935 static int
8936 mptsas_start_cmd(mptsas_t *mpt, mptsas_cmd_t *cmd)
8937 {
8938         struct scsi_pkt         *pkt = CMD2PKT(cmd);
8939         uint32_t                control = 0;
8940         caddr_t                 mem, arsbuf;

8941         pMpi2SCSIIORequest_t    io_request;
8942         ddi_dma_handle_t        dma_hdl = mpt->m_dma_req_frame_hdl;
8943         ddi_acc_handle_t        acc_hdl = mpt->m_acc_req_frame_hdl;
8944         mptsas_target_t         *ptgt = cmd->cmd_tgt_addr;
8945         uint16_t                SMID, io_flags = 0, ars_size;
8946         uint8_t                 MSIidx;
8947         uint64_t                request_desc;
8948         uint32_t                ars_dmaaddrlow;
8949         mptsas_cmd_t            *c;
8950 
8951         NDBG1(("mptsas_start_cmd: cmd=0x%p, flags 0x%x", (void *)cmd,
8952             cmd->cmd_flags));
8953 
8954         /*
8955          * Set SMID and increment index.  Rollover to 1 instead of 0 if index
8956          * is at the max.  0 is an invalid SMID, so we call the first index 1.
8957          */
8958         SMID = cmd->cmd_slot;
8959         MSIidx = cmd->cmd_rpqidx;
8960 
8961         /*
8962          * It is possible for back to back device reset to
8963          * happen before the reset delay has expired.  That's
8964          * ok, just let the device reset go out on the bus.
8965          */
8966         if ((cmd->cmd_pkt_flags & FLAG_NOINTR) == 0) {
8967                 ASSERT(ptgt->m_reset_delay == 0);
8968         }
8969 
8970         /*
8971          * if a non-tagged cmd is submitted to an active tagged target
8972          * then drain before submitting this cmd; SCSI-2 allows RQSENSE
8973          * to be untagged
8974          */
8975         mutex_enter(&ptgt->m_t_mutex);
8976         if (((cmd->cmd_pkt_flags & FLAG_TAGMASK) == 0) &&
8977             (ptgt->m_t_ncmds > 1) &&
8978             ((cmd->cmd_flags & CFLAG_TM_CMD) == 0) &&
8979             (*(cmd->cmd_pkt->pkt_cdbp) != SCMD_REQUEST_SENSE)) {
8980                 if ((cmd->cmd_pkt_flags & FLAG_NOINTR) == 0) {
8981                         NDBG23(("target=%d, untagged cmd, start draining\n",
8982                             ptgt->m_devhdl));
8983 
8984                         if (ptgt->m_reset_delay == 0) {
8985                                 mptsas_set_throttle(mpt, ptgt, DRAIN_THROTTLE);
8986                         }
8987                         mutex_exit(&ptgt->m_t_mutex);
8988 
8989                         mutex_enter(&mpt->m_mutex);
8990                         mptsas_remove_cmd(mpt, cmd);
8991                         cmd->cmd_pkt_flags |= FLAG_HEAD;
8992                         mptsas_waitq_add(mpt, cmd);
8993                         mutex_exit(&mpt->m_mutex);
8994                 } else {
8995                         mutex_exit(&ptgt->m_t_mutex);
8996                 }
8997                 return (DDI_FAILURE);
8998         }
8999 
9000         /*
9001          * Set correct tag bits.
9002          */
9003         if (cmd->cmd_pkt_flags & FLAG_TAGMASK) {
9004                 switch (mptsas_tag_lookup[((cmd->cmd_pkt_flags &
9005                     FLAG_TAGMASK) >> 12)]) {
9006                 case MSG_SIMPLE_QTAG:
9007                         control |= MPI2_SCSIIO_CONTROL_SIMPLEQ;
9008                         break;
9009                 case MSG_HEAD_QTAG:
9010                         control |= MPI2_SCSIIO_CONTROL_HEADOFQ;
9011                         break;
9012                 case MSG_ORDERED_QTAG:
9013                         control |= MPI2_SCSIIO_CONTROL_ORDEREDQ;
9014                         break;
9015                 default:
9016                         mptsas_log(mpt, CE_WARN, "mpt: Invalid tag type\n");
9017                         break;
9018                 }
9019         } else {
9020                 if (*(cmd->cmd_pkt->pkt_cdbp) != SCMD_REQUEST_SENSE) {
9021                                 ptgt->m_t_throttle = 1;
9022                 }
9023                 control |= MPI2_SCSIIO_CONTROL_SIMPLEQ;
9024         }
9025 
9026         /*
9027          * Set timeout.
9028          */
9029         cmd->cmd_active_expiration =
9030             gethrtime() + (hrtime_t)pkt->pkt_time * NANOSEC;
9031 
9032         c = TAILQ_FIRST(&ptgt->m_active_cmdq);
9033         if (c == NULL ||
9034             c->cmd_active_expiration < cmd->cmd_active_expiration) {
9035                 /*
9036                  * Common case is that this is the last pending expiration
9037                  * (or queue is empty). Insert at head of the queue.
9038                  */
9039                 TAILQ_INSERT_HEAD(&ptgt->m_active_cmdq, cmd, cmd_active_link);
9040         } else {
9041                 /*
9042                  * Queue is not empty and first element expires later than
9043                  * this command. Search for element expiring sooner.
9044                  */
9045                 while ((c = TAILQ_NEXT(c, cmd_active_link)) != NULL) {
9046                         if (c->cmd_active_expiration <
9047                             cmd->cmd_active_expiration) {
9048                                 TAILQ_INSERT_BEFORE(c, cmd, cmd_active_link);
9049                                 break;
9050                         }
9051                 }
9052                 if (c == NULL) {
9053                         /*
9054                          * No element found expiring sooner, append to
9055                          * non-empty queue.
9056                          */
9057                         TAILQ_INSERT_TAIL(&ptgt->m_active_cmdq, cmd,
9058                             cmd_active_link);
9059                 }
9060         }
9061 
9062         mutex_exit(&ptgt->m_t_mutex);
9063 
9064         if (cmd->cmd_pkt_flags & FLAG_TLR) {
9065                 control |= MPI2_SCSIIO_CONTROL_TLR_ON;
9066         }
9067 
9068         mem = mpt->m_req_frame + (mpt->m_req_frame_size * SMID);
9069         io_request = (pMpi2SCSIIORequest_t)mem;
9070         if (cmd->cmd_extrqslen != 0) {
9071                 /*
9072                  * Mapping of the buffer was done in mptsas_pkt_alloc_extern().
9073                  * Calculate the DMA address with the same offset.
9074                  */
9075                 arsbuf = cmd->cmd_arq_buf;
9076                 ars_size = cmd->cmd_extrqslen;
9077                 ars_dmaaddrlow = (mpt->m_req_sense_dma_addr +
9078                     ((uintptr_t)arsbuf - (uintptr_t)mpt->m_req_sense)) &
9079                     0xffffffffull;
9080         } else {
9081                 arsbuf = mpt->m_req_sense + (mpt->m_req_sense_size * (SMID-1));
9082                 cmd->cmd_arq_buf = arsbuf;
9083                 ars_size = mpt->m_req_sense_size;
9084                 ars_dmaaddrlow = (mpt->m_req_sense_dma_addr +
9085                     (mpt->m_req_sense_size * (SMID-1))) &
9086                     0xffffffffull;
9087         }
9088         bzero(io_request, sizeof (Mpi2SCSIIORequest_t));
9089         bzero(arsbuf, ars_size);
9090 
9091         ddi_put8(acc_hdl, &io_request->SGLOffset0, offsetof
9092             (MPI2_SCSI_IO_REQUEST, SGL) / 4);
9093         mptsas_init_std_hdr(acc_hdl, io_request, ptgt->m_devhdl, Lun(cmd), 0,
9094             MPI2_FUNCTION_SCSI_IO_REQUEST);
9095 
9096         (void) ddi_rep_put8(acc_hdl, (uint8_t *)pkt->pkt_cdbp,
9097             io_request->CDB.CDB32, cmd->cmd_cdblen, DDI_DEV_AUTOINCR);
9098 
9099         io_flags = cmd->cmd_cdblen;
9100         if (mptsas3_use_fastpath &&
9101             ptgt->m_io_flags & MPI25_SAS_DEVICE0_FLAGS_ENABLED_FAST_PATH) {
9102                 io_flags |= MPI25_SCSIIO_IOFLAGS_FAST_PATH;
9103                 request_desc = MPI25_REQ_DESCRIPT_FLAGS_FAST_PATH_SCSI_IO;
9104         } else {
9105                 request_desc = MPI2_REQ_DESCRIPT_FLAGS_SCSI_IO;
9106         }
9107         ddi_put16(acc_hdl, &io_request->IoFlags, io_flags);
9108         /*
9109          * setup the Scatter/Gather DMA list for this request
9110          */
9111         if (cmd->cmd_cookiec > 0) {
9112                 mptsas_sge_setup(mpt, cmd, &control, io_request, acc_hdl);
9113         } else {
9114                 ddi_put32(acc_hdl, &io_request->SGL.MpiSimple.FlagsLength,
9115                     ((uint32_t)MPI2_SGE_FLAGS_LAST_ELEMENT |
9116                     MPI2_SGE_FLAGS_END_OF_BUFFER |
9117                     MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
9118                     MPI2_SGE_FLAGS_END_OF_LIST) << MPI2_SGE_FLAGS_SHIFT);
9119         }
9120 
9121         /*
9122          * save ARQ information
9123          */
9124         ddi_put8(acc_hdl, &io_request->SenseBufferLength, cmd->cmd_rqslen);
9125         ddi_put32(acc_hdl, &io_request->SenseBufferLowAddress, ars_dmaaddrlow);







9126 
9127         ddi_put32(acc_hdl, &io_request->Control, control);
9128 
9129         NDBG31(("starting message=%d(0x%p), with cmd=0x%p",
9130             SMID, (void *)io_request, (void *)cmd));
9131 
9132         (void) ddi_dma_sync(dma_hdl, 0, 0, DDI_DMA_SYNC_FORDEV);
9133 
9134         /*
9135          * Build request descriptor and write it to the request desc post reg.
9136          */
9137         request_desc |= (SMID << 16) + (MSIidx << 8);
9138         request_desc |= ((uint64_t)ptgt->m_devhdl << 48);
9139         MPTSAS_START_CMD(mpt, request_desc);



































9140 
9141 #if 0
9142         /* Is this of any benefit here, what is it going to catch? */
9143         if ((mptsas_check_dma_handle(dma_hdl) != DDI_SUCCESS) ||
9144             (mptsas_check_acc_handle(acc_hdl) != DDI_SUCCESS)) {
9145                 ddi_fm_service_impact(mpt->m_dip, DDI_SERVICE_UNAFFECTED);
9146                 return (DDI_FAILURE);
9147         }
9148 #endif
9149         return (DDI_SUCCESS);
9150 }
9151 
9152 /*
9153  * Select a helper thread to handle given doneq.
9154  * Note that we don't require to have the main m_mutex here, but worst case
9155  * is that we wont follow the thread rotation to the letter.
9156  * However must ensure we have the mutex that covers the source dlist when
9157  * we actually hand off.
9158  */
9159 static void
9160 mptsas_deliver_doneq_thread(mptsas_t *mpt, mptsas_done_list_t *dlist)
9161 {
9162         uint32_t                        t, i, j = mpt->m_doneq_next_thread;
9163         uint32_t                        min = 0xffffffff;
9164         mptsas_doneq_thread_list_t      *item;
9165 
9166         /*
9167          * No need to take indivudual list mutex's during the loop.
9168          * We are only reading values and the worst that will happen is that
9169          * we pick the wrong thread.
9170          */
9171         for (i = 0; i < mpt->m_doneq_thread_n; i++) {
9172                 item = &mpt->m_doneq_thread_id[j];
9173 
9174                 /*
9175                  * If the completed command on help thread[i] less than
9176                  * doneq_thread_threshold, then pick the thread[j]. Otherwise
9177                  * pick a thread which has least completed command.
9178                  */
9179                 if (item->dlist.dl_len < mpt->m_doneq_thread_threshold) {
9180                         t = j;



9181                         break;
9182                 }
9183                 if (item->dlist.dl_len < min) {
9184                         min = item->dlist.dl_len;
9185                         t = j;
9186                 }
9187                 if (++j == mpt->m_doneq_thread_n) {
9188                         j = 0;
9189                 }
9190         }
9191         item = &mpt->m_doneq_thread_id[t];
9192         mutex_enter(&item->mutex);
9193         mptsas_doneq_mv(dlist, item);
9194         cv_signal(&item->cv);
9195         mutex_exit(&item->mutex);
9196 
9197         /*
9198          * Next time start at the next thread.
9199          * This will minimize the potential of grabing a lock
9200          * for a thread that is busy, either on a very busy systems
9201          * or on one that is configured to do all command completion
9202          * processing through threads.
9203          */
9204         if (++t == mpt->m_doneq_thread_n) {
9205                 t = 0;
9206         }
9207         mpt->m_doneq_next_thread = (uint16_t)t;



9208 }
9209 
9210 /*
9211  * move one doneq to another.
9212  */
9213 static void
9214 mptsas_doneq_mv(mptsas_done_list_t *from, mptsas_doneq_thread_list_t *item)
9215 {
9216         mptsas_done_list_t              *to = &item->dlist;
9217         mptsas_cmd_t                    *cmd;

9218 
9219         if ((cmd = from->dl_q) != NULL) {
9220                 *to->dl_tail = cmd;
9221                 to->dl_tail = from->dl_tail;
9222                 to->dl_len += from->dl_len;
9223                 from->dl_q = NULL;
9224                 from->dl_tail = &from->dl_q;
9225                 from->dl_len = 0;



9226         }
9227 }
9228 
9229 void
9230 mptsas_fma_check(mptsas_t *mpt, mptsas_cmd_t *cmd)
9231 {
9232         struct scsi_pkt *pkt = CMD2PKT(cmd);
9233 
9234         /* Check all acc and dma handles */
9235         if ((mptsas_check_acc_handle(mpt->m_datap) !=
9236             DDI_SUCCESS) ||
9237             (mptsas_check_acc_handle(mpt->m_acc_req_frame_hdl) !=
9238             DDI_SUCCESS) ||
9239             (mptsas_check_acc_handle(mpt->m_acc_req_sense_hdl) !=
9240             DDI_SUCCESS) ||
9241             (mptsas_check_acc_handle(mpt->m_acc_reply_frame_hdl) !=
9242             DDI_SUCCESS) ||
9243             (mptsas_check_acc_handle(mpt->m_acc_free_queue_hdl) !=
9244             DDI_SUCCESS) ||
9245             (mptsas_check_acc_handle(mpt->m_acc_post_queue_hdl) !=
9246             DDI_SUCCESS) ||
9247             (mptsas_check_acc_handle(mpt->m_hshk_acc_hdl) !=
9248             DDI_SUCCESS) ||
9249             (mptsas_check_acc_handle(mpt->m_config_handle) !=
9250             DDI_SUCCESS)) {
9251                 ddi_fm_service_impact(mpt->m_dip,
9252                     DDI_SERVICE_UNAFFECTED);
9253                 ddi_fm_acc_err_clear(mpt->m_config_handle,
9254                     DDI_FME_VER0);
9255                 pkt->pkt_reason = CMD_TRAN_ERR;
9256                 pkt->pkt_statistics = 0;
9257         }
9258         if ((mptsas_check_dma_handle(mpt->m_dma_req_frame_hdl) !=
9259             DDI_SUCCESS) ||
9260             (mptsas_check_dma_handle(mpt->m_dma_req_sense_hdl) !=
9261             DDI_SUCCESS) ||
9262             (mptsas_check_dma_handle(mpt->m_dma_reply_frame_hdl) !=
9263             DDI_SUCCESS) ||
9264             (mptsas_check_dma_handle(mpt->m_dma_free_queue_hdl) !=
9265             DDI_SUCCESS) ||
9266             (mptsas_check_dma_handle(mpt->m_dma_post_queue_hdl) !=
9267             DDI_SUCCESS) ||
9268             (mptsas_check_dma_handle(mpt->m_hshk_dma_hdl) !=
9269             DDI_SUCCESS)) {
9270                 ddi_fm_service_impact(mpt->m_dip,
9271                     DDI_SERVICE_UNAFFECTED);
9272                 pkt->pkt_reason = CMD_TRAN_ERR;
9273                 pkt->pkt_statistics = 0;
9274         }
9275         if (cmd->cmd_dmahandle &&
9276             (mptsas_check_dma_handle(cmd->cmd_dmahandle) != DDI_SUCCESS)) {
9277                 ddi_fm_service_impact(mpt->m_dip, DDI_SERVICE_UNAFFECTED);
9278                 pkt->pkt_reason = CMD_TRAN_ERR;
9279                 pkt->pkt_statistics = 0;
9280         }
9281         if ((cmd->cmd_extra_frames &&
9282             ((mptsas_check_dma_handle(cmd->cmd_extra_frames->m_dma_hdl) !=
9283             DDI_SUCCESS) ||
9284             (mptsas_check_acc_handle(cmd->cmd_extra_frames->m_acc_hdl) !=
9285             DDI_SUCCESS)))) {
9286                 ddi_fm_service_impact(mpt->m_dip, DDI_SERVICE_UNAFFECTED);
9287                 pkt->pkt_reason = CMD_TRAN_ERR;
9288                 pkt->pkt_statistics = 0;
9289         }












9290 }
9291 
9292 /*
9293  * These routines manipulate the queue of commands that
9294  * are waiting for their completion routines to be called.
9295  * The queue is usually in FIFO order but on an MP system
9296  * it's possible for the completion routines to get out
9297  * of order. If that's a problem you need to add a global
9298  * mutex around the code that calls the completion routine
9299  * in the interrupt handler.
9300  */
9301 static void
9302 mptsas_doneq_add(mptsas_t *mpt, mptsas_cmd_t *cmd)
9303 {
9304         struct scsi_pkt *pkt = CMD2PKT(cmd);
9305 
9306         NDBG31(("mptsas_doneq_add: cmd=0x%p", (void *)cmd));
9307 
9308         ASSERT((cmd->cmd_flags & CFLAG_COMPLETED) == 0);
9309         cmd->cmd_linkp = NULL;
9310         cmd->cmd_flags |= CFLAG_FINISHED;
9311         cmd->cmd_flags &= ~CFLAG_IN_TRANSPORT;
9312 
9313         mptsas_fma_check(mpt, cmd);
9314 
9315         /*
9316          * only add scsi pkts that have completion routines to
9317          * the doneq.  no intr cmds do not have callbacks.
9318          */
9319         if (pkt && (pkt->pkt_comp)) {
9320                 *mpt->m_dlist.dl_tail = cmd;
9321                 mpt->m_dlist.dl_tail = &cmd->cmd_linkp;
9322                 mpt->m_dlist.dl_len++;
9323         }
9324 }
9325 
9326 static void
9327 mptsas_rpdoneq_add(mptsas_t *mpt, mptsas_reply_pqueue_t *rpqp,
9328     mptsas_cmd_t *cmd)
9329 {
9330         struct scsi_pkt *pkt = CMD2PKT(cmd);
9331 
9332         NDBG31(("mptsas_rpdoneq_add: cmd=0x%p", (void *)cmd));
9333 
9334         ASSERT((cmd->cmd_flags & CFLAG_COMPLETED) == 0);
9335         cmd->cmd_linkp = NULL;
9336         cmd->cmd_flags |= CFLAG_FINISHED;
9337         cmd->cmd_flags &= ~CFLAG_IN_TRANSPORT;
9338 
9339         mptsas_fma_check(mpt, cmd);
9340 
9341         /*
9342          * only add scsi pkts that have completion routines to
9343          * the doneq.  no intr cmds do not have callbacks.
9344          */
9345         if (pkt && (pkt->pkt_comp)) {
9346                 *rpqp->rpq_dlist.dl_tail = cmd;
9347                 rpqp->rpq_dlist.dl_tail = &cmd->cmd_linkp;
9348                 rpqp->rpq_dlist.dl_len++;
9349         }
9350 }
9351 
9352 static mptsas_cmd_t *
9353 mptsas_doneq_thread_rm(mptsas_t *mpt, uint64_t t)
9354 {
9355         mptsas_cmd_t                    *cmd;
9356         mptsas_doneq_thread_list_t      *item = &mpt->m_doneq_thread_id[t];
9357 
9358         /* pop one off the done queue */
9359         if ((cmd = item->dlist.dl_q) != NULL) {
9360                 /* if the queue is now empty fix the tail pointer */
9361                 NDBG31(("mptsas_doneq_thread_rm: cmd=0x%p", (void *)cmd));
9362                 if ((item->dlist.dl_q = cmd->cmd_linkp) == NULL) {
9363                         item->dlist.dl_tail = &item->dlist.dl_q;
9364                 }
9365                 cmd->cmd_linkp = NULL;
9366                 item->dlist.dl_len--;
9367         }
9368         return (cmd);
9369 }
9370 
9371 static void
9372 mptsas_doneq_empty(mptsas_t *mpt)
9373 {
9374         if (mpt->m_dlist.dl_q) {
9375                 mptsas_cmd_t    *cmd, *next;
9376                 struct scsi_pkt *pkt;
9377 
9378                 cmd = mpt->m_dlist.dl_q;
9379                 mpt->m_dlist.dl_q = NULL;
9380                 mpt->m_dlist.dl_tail = &mpt->m_dlist.dl_q;
9381                 mpt->m_dlist.dl_len = 0;

9382 
9383                 mutex_exit(&mpt->m_mutex);
9384                 /*
9385                  * run the completion routines of all the
9386                  * completed commands
9387                  */
9388                 while (cmd != NULL) {
9389                         next = cmd->cmd_linkp;
9390                         cmd->cmd_linkp = NULL;
9391                         /* run this command's completion routine */
9392                         cmd->cmd_flags |= CFLAG_COMPLETED;
9393                         pkt = CMD2PKT(cmd);
9394                         mptsas_pkt_comp(pkt, cmd);
9395                         cmd = next;
9396                 }
9397                 mutex_enter(&mpt->m_mutex);
9398         }
9399 }
9400 
9401 static void
9402 mptsas_rpdoneq_empty(mptsas_reply_pqueue_t *rpqp)
9403 {
9404         if (rpqp->rpq_dlist.dl_q) {
9405                 mptsas_cmd_t    *cmd, *next;
9406                 struct scsi_pkt *pkt;
9407 
9408                 cmd = rpqp->rpq_dlist.dl_q;
9409                 rpqp->rpq_dlist.dl_q = NULL;
9410                 rpqp->rpq_dlist.dl_tail = &rpqp->rpq_dlist.dl_q;
9411                 rpqp->rpq_dlist.dl_len = 0;
9412 
9413                 mutex_exit(&rpqp->rpq_mutex);
9414                 /*
9415                  * run the completion routines of all the
9416                  * completed commands
9417                  */
9418                 while (cmd != NULL) {
9419                         next = cmd->cmd_linkp;
9420                         cmd->cmd_linkp = NULL;
9421                         /* run this command's completion routine */
9422                         cmd->cmd_flags |= CFLAG_COMPLETED;
9423                         pkt = CMD2PKT(cmd);
9424                         mptsas_pkt_comp(pkt, cmd);
9425                         cmd = next;
9426                 }
9427                 mutex_enter(&rpqp->rpq_mutex);
9428         }
9429 }
9430 
9431 /*
9432  * These routines manipulate the target's queue of pending requests
9433  */
9434 void
9435 mptsas_waitq_add(mptsas_t *mpt, mptsas_cmd_t *cmd)
9436 {
9437         NDBG7(("mptsas_waitq_add: cmd=0x%p", (void *)cmd));
9438         mptsas_target_t *ptgt = cmd->cmd_tgt_addr;
9439         cmd->cmd_queued = TRUE;
9440         if (ptgt)
9441                 ptgt->m_t_nwait++;
9442         if (cmd->cmd_pkt_flags & FLAG_HEAD) {
9443                 if ((cmd->cmd_linkp = mpt->m_waitq) == NULL) {
9444                         mpt->m_waitqtail = &cmd->cmd_linkp;
9445                 }
9446                 mpt->m_waitq = cmd;
9447         } else {


9497                     (void *)mpt, (void *)cmd));
9498                 return;
9499         }
9500 
9501         while (prevp != NULL) {
9502                 if (prevp->cmd_linkp == cmd) {
9503                         if ((prevp->cmd_linkp = cmd->cmd_linkp) == NULL)
9504                                 mpt->m_waitqtail = &prevp->cmd_linkp;
9505 
9506                         cmd->cmd_linkp = NULL;
9507                         cmd->cmd_queued = FALSE;
9508                         NDBG7(("mptsas_waitq_delete: mpt=0x%p cmd=0x%p",
9509                             (void *)mpt, (void *)cmd));
9510                         return;
9511                 }
9512                 prevp = prevp->cmd_linkp;
9513         }
9514         cmn_err(CE_PANIC, "mpt: mptsas_waitq_delete: queue botch");
9515 }
9516 



















































9517 /*
9518  * device and bus reset handling
9519  *
9520  * Notes:
9521  *      - RESET_ALL:    reset the controller
9522  *      - RESET_TARGET: reset the target specified in scsi_address
9523  */
9524 static int
9525 mptsas_scsi_reset(struct scsi_address *ap, int level)
9526 {
9527         mptsas_t                *mpt = ADDR2MPT(ap);
9528         int                     rval;
9529         mptsas_tgt_private_t    *tgt_private;
9530         mptsas_target_t         *ptgt = NULL;
9531 
9532         tgt_private = (mptsas_tgt_private_t *)ap->a_hba_tran->tran_tgt_private;
9533         ptgt = tgt_private->t_private;
9534         if (ptgt == NULL) {
9535                 return (FALSE);
9536         }


9612         dev_info_t      *lun_dip = NULL;
9613 
9614         ASSERT(sd != NULL);
9615         ASSERT(name != NULL);
9616         lun_dip = sd->sd_dev;
9617         ASSERT(lun_dip != NULL);
9618 
9619         if (mptsas_name_child(lun_dip, name, len) == DDI_SUCCESS) {
9620                 return (1);
9621         } else {
9622                 return (0);
9623         }
9624 }
9625 
9626 static int
9627 mptsas_get_bus_addr(struct scsi_device *sd, char *name, int len)
9628 {
9629         return (mptsas_get_name(sd, name, len));
9630 }
9631 
9632 static void
9633 mptsas_set_throttle(mptsas_t *mpt, mptsas_target_t *ptgt, int what)
9634 {
9635 
9636         NDBG25(("mptsas_set_throttle: throttle=%x", what));
9637 
9638         /*
9639          * if the bus is draining/quiesced, no changes to the throttles
9640          * are allowed. Not allowing change of throttles during draining
9641          * limits error recovery but will reduce draining time
9642          *
9643          * all throttles should have been set to HOLD_THROTTLE
9644          */
9645         if (mpt->m_softstate & (MPTSAS_SS_QUIESCED | MPTSAS_SS_DRAINING)) {
9646                 return;
9647         }
9648 
9649         if (what == HOLD_THROTTLE) {
9650                 ptgt->m_t_throttle = HOLD_THROTTLE;
9651         } else if (ptgt->m_reset_delay == 0) {
9652                 ptgt->m_t_throttle = what;
9653         }
9654 }
9655 
9656 static void
9657 mptsas_set_throttle_mtx(mptsas_t *mpt, mptsas_target_t *ptgt, int what)
9658 {
9659         if (mpt->m_softstate & (MPTSAS_SS_QUIESCED | MPTSAS_SS_DRAINING)) {
9660                 return;
9661         }
9662 
9663         mutex_enter(&ptgt->m_t_mutex);
9664         mptsas_set_throttle(mpt, ptgt, what);
9665         mutex_exit(&ptgt->m_t_mutex);
9666 }
9667 
9668 /*
9669  * Find all commands in the tx_waitq's for target and lun (if lun not -1),
9670  * remove them from the queues and return the linked list.
9671  */
9672 static mptsas_cmd_t *
9673 mptsas_strip_targetlun_from_txwqs(mptsas_t *mpt, ushort_t target, int lun)
9674 {
9675         mptsas_cmd_t            *cmd, *clist, **tailp, **prev_tailp;
9676         mptsas_tx_waitqueue_t   *txwq;
9677         int                     i;
9678 
9679         clist = NULL;
9680         tailp = &clist;
9681 
9682         for (i = 0; i < NUM_TX_WAITQ; i++) {
9683                 txwq = &mpt->m_tx_waitq[i];
9684                 mutex_enter(&txwq->txwq_mutex);
9685                 prev_tailp = &txwq->txwq_cmdq;
9686                 cmd = txwq->txwq_cmdq;
9687                 while (cmd != NULL) {
9688                         if (Tgt(cmd) == target &&
9689                             (lun == -1 || (Lun(cmd) == lun))) {
9690                                 *prev_tailp = cmd->cmd_linkp;
9691                                 *tailp = cmd;
9692                                 tailp = &cmd->cmd_linkp;
9693                                 cmd = cmd->cmd_linkp;
9694                                 *tailp = NULL;
9695                         } else {
9696                                 prev_tailp = &cmd->cmd_linkp;
9697                                 cmd = cmd->cmd_linkp;
9698                         }
9699                 }
9700                 txwq->txwq_qtail = prev_tailp;
9701                 mutex_exit(&txwq->txwq_mutex);
9702         }
9703         return (clist);
9704 }
9705 
9706 /*
9707  * Clean up from a device reset.
9708  * For the case of target reset, this function clears the waitq of all
9709  * commands for a particular target.   For the case of abort task set, this
9710  * function clears the waitq of all commonds for a particular target/lun.
9711  */
9712 static void
9713 mptsas_flush_target(mptsas_t *mpt, ushort_t target, int lun, uint8_t tasktype)
9714 {
9715         mptsas_slots_t  *slots = mpt->m_active;
9716         mptsas_cmd_t    *cmd, *next_cmd;
9717         int             slot;
9718         uchar_t         reason;
9719         uint_t          stat;
9720         hrtime_t        timestamp;
9721 
9722         NDBG25(("mptsas_flush_target: target=%d lun=%d", target, lun));
9723 
9724         timestamp = gethrtime();
9725 
9726         /*
9727          * Make sure the I/O Controller has flushed all cmds
9728          * that are associated with this target for a target reset
9729          * and target/lun for abort task set.
9730          * Account for TM requests, which use the last SMID.
9731          */
9732         for (slot = 0; slot <= mpt->m_active->m_n_normal; slot++) {
9733                 if ((cmd = slots->m_slot[slot]) == NULL)
9734                         continue;
9735                 reason = CMD_RESET;
9736                 stat = STAT_DEV_RESET;
9737                 switch (tasktype) {
9738                 case MPI2_SCSITASKMGMT_TASKTYPE_TARGET_RESET:
9739                         if (Tgt(cmd) == target) {
9740                                 if (cmd->cmd_active_expiration <= timestamp) {
9741                                         /*
9742                                          * When timeout requested, propagate
9743                                          * proper reason and statistics to
9744                                          * target drivers.
9745                                          */
9746                                         reason = CMD_TIMEOUT;
9747                                         stat |= STAT_TIMEOUT;
9748                                 }
9749                                 NDBG25(("mptsas_flush_target discovered non-"
9750                                     "NULL cmd in slot %d, tasktype 0x%x", slot,
9751                                     tasktype));
9752                                 mptsas_dump_cmd(mpt, cmd);
9753                                 mptsas_remove_cmd(mpt, cmd);
9754                                 mptsas_set_pkt_reason(mpt, cmd, reason, stat);
9755                                 mptsas_doneq_add(mpt, cmd);
9756                         }
9757                         break;
9758                 case MPI2_SCSITASKMGMT_TASKTYPE_ABRT_TASK_SET:
9759                         reason = CMD_ABORTED;
9760                         stat = STAT_ABORTED;
9761                         /*FALLTHROUGH*/
9762                 case MPI2_SCSITASKMGMT_TASKTYPE_LOGICAL_UNIT_RESET:
9763                         if ((Tgt(cmd) == target) && (Lun(cmd) == lun)) {
9764                                 if (cmd->cmd_active_expiration <= timestamp) {
9765                                         stat |= STAT_TIMEOUT;
9766                                 }
9767 
9768                                 NDBG25(("mptsas_flush_target discovered non-"
9769                                     "NULL cmd in slot %d, tasktype 0x%x", slot,
9770                                     tasktype));
9771                                 mptsas_dump_cmd(mpt, cmd);
9772                                 mptsas_remove_cmd(mpt, cmd);
9773                                 mptsas_set_pkt_reason(mpt, cmd, reason, stat);

9774                                 mptsas_doneq_add(mpt, cmd);
9775                         }
9776                         break;
9777                 default:
9778                         break;
9779                 }
9780         }
9781 
9782         /*
9783          * Flush the waitq and tx_waitq of this target's cmds
9784          */
9785         cmd = mpt->m_waitq;
9786 
9787         reason = CMD_RESET;
9788         stat = STAT_DEV_RESET;
9789 
9790         switch (tasktype) {
9791         case MPI2_SCSITASKMGMT_TASKTYPE_TARGET_RESET:
9792                 while (cmd != NULL) {
9793                         next_cmd = cmd->cmd_linkp;
9794                         if (Tgt(cmd) == target) {
9795                                 mptsas_waitq_delete(mpt, cmd);
9796                                 mptsas_set_pkt_reason(mpt, cmd,
9797                                     reason, stat);
9798                                 mptsas_doneq_add(mpt, cmd);
9799                         }
9800                         cmd = next_cmd;
9801                 }
9802                 cmd = mptsas_strip_targetlun_from_txwqs(mpt, target, -1);

9803                 while (cmd != NULL) {
9804                         next_cmd = cmd->cmd_linkp;
9805                         mptsas_set_pkt_reason(mpt, cmd, reason, stat);




9806                         mptsas_doneq_add(mpt, cmd);


9807                         cmd = next_cmd;
9808                 }

9809                 break;
9810         case MPI2_SCSITASKMGMT_TASKTYPE_ABRT_TASK_SET:
9811                 reason = CMD_ABORTED;
9812                 stat =  STAT_ABORTED;
9813                 /*FALLTHROUGH*/
9814         case MPI2_SCSITASKMGMT_TASKTYPE_LOGICAL_UNIT_RESET:
9815                 while (cmd != NULL) {
9816                         next_cmd = cmd->cmd_linkp;
9817                         if ((Tgt(cmd) == target) && (Lun(cmd) == lun)) {
9818                                 mptsas_waitq_delete(mpt, cmd);
9819                                 mptsas_set_pkt_reason(mpt, cmd,
9820                                     reason, stat);
9821                                 mptsas_doneq_add(mpt, cmd);
9822                         }
9823                         cmd = next_cmd;
9824                 }
9825                 cmd = mptsas_strip_targetlun_from_txwqs(mpt, target, lun);

9826                 while (cmd != NULL) {
9827                         next_cmd = cmd->cmd_linkp;
9828                         mptsas_set_pkt_reason(mpt, cmd, reason, stat);




9829                         mptsas_doneq_add(mpt, cmd);


9830                         cmd = next_cmd;
9831                 }

9832                 break;
9833         default:
9834                 mptsas_log(mpt, CE_WARN, "Unknown task management type %d.",
9835                     tasktype);
9836                 break;
9837         }
9838 }
9839 
9840 /*
9841  * Clean up hba state, abort all outstanding command and commands in waitq
9842  * reset timeout of all targets.
9843  */
9844 static void
9845 mptsas_flush_hba(mptsas_t *mpt)
9846 {
9847         mptsas_slots_t  *slots = mpt->m_active;
9848         mptsas_cmd_t    *cmd, *ncmd;
9849         int             slot, i;
9850 
9851         NDBG25(("mptsas_flush_hba"));
9852 
9853         /*
9854          * The I/O Controller should have already sent back
9855          * all commands via the scsi I/O reply frame.  Make
9856          * sure all commands have been flushed.
9857          * Account for TM request, which use the last SMID.
9858          */
9859         for (slot = 0; slot <= mpt->m_active->m_n_normal; slot++) {
9860                 if ((cmd = slots->m_slot[slot]) == NULL)
9861                         continue;
9862 
9863                 if (cmd->cmd_flags & CFLAG_CMDIOC) {
9864                         /*
9865                          * Need to make sure to tell everyone that might be
9866                          * waiting on this command that it's going to fail.  If
9867                          * we get here, this command will never timeout because
9868                          * the active command table is going to be re-allocated,
9869                          * so there will be nothing to check against a time out.
9870                          * Instead, mark the command as failed due to reset.
9871                          */
9872                         mptsas_set_pkt_reason(mpt, cmd, CMD_RESET,
9873                             STAT_BUS_RESET);
9874                         if ((cmd->cmd_flags &
9875                             (CFLAG_PASSTHRU | CFLAG_CONFIG | CFLAG_FW_DIAG))) {

9876                                 cmd->cmd_flags |= CFLAG_FINISHED;
9877                                 cv_broadcast(&mpt->m_passthru_cv);
9878                                 cv_broadcast(&mpt->m_config_cv);
9879                                 cv_broadcast(&mpt->m_fw_diag_cv);
9880                         }
9881                         continue;
9882                 }
9883 
9884                 NDBG25(("mptsas_flush_hba discovered non-NULL cmd in slot %d",
9885                     slot));
9886                 mptsas_dump_cmd(mpt, cmd);
9887 
9888                 mptsas_remove_cmd(mpt, cmd);
9889                 mptsas_set_pkt_reason(mpt, cmd, CMD_RESET, STAT_BUS_RESET);
9890                 mptsas_doneq_add(mpt, cmd);
9891         }
9892 
9893         /*
9894          * Flush the waitq.
9895          */
9896         while ((cmd = mptsas_waitq_rm(mpt)) != NULL) {
9897                 mptsas_set_pkt_reason(mpt, cmd, CMD_RESET, STAT_BUS_RESET);
9898                 if ((cmd->cmd_flags & CFLAG_PASSTHRU) ||
9899                     (cmd->cmd_flags & CFLAG_CONFIG) ||
9900                     (cmd->cmd_flags & CFLAG_FW_DIAG)) {
9901                         cmd->cmd_flags |= CFLAG_FINISHED;
9902                         cv_broadcast(&mpt->m_passthru_cv);
9903                         cv_broadcast(&mpt->m_config_cv);
9904                         cv_broadcast(&mpt->m_fw_diag_cv);
9905                 } else {
9906                         mptsas_doneq_add(mpt, cmd);
9907                 }
9908         }
9909 
9910         /*
9911          * Flush the tx_waitqs
9912          */
9913         for (i = 0; i < NUM_TX_WAITQ; i++) {
9914                 mutex_enter(&mpt->m_tx_waitq[i].txwq_mutex);
9915                 cmd = mpt->m_tx_waitq[i].txwq_cmdq;
9916                 mpt->m_tx_waitq[i].txwq_cmdq = NULL;
9917                 mpt->m_tx_waitq[i].txwq_qtail = &mpt->m_tx_waitq[i].txwq_cmdq;
9918                 mutex_exit(&mpt->m_tx_waitq[i].txwq_mutex);
9919                 while (cmd != NULL) {
9920                         ncmd = cmd->cmd_linkp;
9921                         mptsas_set_pkt_reason(mpt, cmd, CMD_RESET,
9922                             STAT_BUS_RESET);
9923                         mptsas_doneq_add(mpt, cmd);
9924                         cmd = ncmd;
9925                 }
9926         }

9927 
9928         /*
9929          * Drain the taskqs prior to reallocating resources.
9930          */
9931         mutex_exit(&mpt->m_mutex);
9932         ddi_taskq_wait(mpt->m_event_taskq);
9933         ddi_taskq_wait(mpt->m_dr_taskq);
9934         mutex_enter(&mpt->m_mutex);
9935 }
9936 
9937 /*
9938  * set pkt_reason and OR in pkt_statistics flag
9939  */
9940 static void
9941 mptsas_set_pkt_reason(mptsas_t *mpt, mptsas_cmd_t *cmd, uchar_t reason,
9942     uint_t stat)
9943 {
9944 #ifndef __lock_lint
9945         _NOTE(ARGUNUSED(mpt))
9946 #endif


9964         mutex_enter(&mptsas_global_mutex);
9965         if (mptsas_reset_watch == NULL && mptsas_timeouts_enabled) {
9966                 mptsas_reset_watch = timeout(mptsas_watch_reset_delay, NULL,
9967                     drv_usectohz((clock_t)
9968                     MPTSAS_WATCH_RESET_DELAY_TICK * 1000));
9969                 ASSERT(mptsas_reset_watch != NULL);
9970         }
9971         mutex_exit(&mptsas_global_mutex);
9972 }
9973 
9974 static void
9975 mptsas_setup_bus_reset_delay(mptsas_t *mpt)
9976 {
9977         mptsas_target_t *ptgt = NULL;
9978 
9979         ASSERT(MUTEX_HELD(&mpt->m_mutex));
9980 
9981         NDBG22(("mptsas_setup_bus_reset_delay"));
9982         for (ptgt = refhash_first(mpt->m_targets); ptgt != NULL;
9983             ptgt = refhash_next(mpt->m_targets, ptgt)) {
9984                 mutex_enter(&ptgt->m_t_mutex);
9985                 mptsas_set_throttle(mpt, ptgt, HOLD_THROTTLE);
9986                 ptgt->m_reset_delay = mpt->m_scsi_reset_delay;
9987                 mutex_exit(&ptgt->m_t_mutex);
9988         }
9989 
9990         mptsas_start_watch_reset_delay();
9991 }
9992 
9993 /*
9994  * mptsas_watch_reset_delay(_subr) is invoked by timeout() and checks every
9995  * mpt instance for active reset delays
9996  */
9997 static void
9998 mptsas_watch_reset_delay(void *arg)
9999 {
10000 #ifndef __lock_lint
10001         _NOTE(ARGUNUSED(arg))
10002 #endif
10003 
10004         mptsas_t        *mpt;
10005         int             not_done = 0;
10006 
10007         NDBG22(("mptsas_watch_reset_delay"));


10021         rw_exit(&mptsas_global_rwlock);
10022 
10023         if (not_done) {
10024                 mptsas_start_watch_reset_delay();
10025         }
10026 }
10027 
10028 static int
10029 mptsas_watch_reset_delay_subr(mptsas_t *mpt)
10030 {
10031         int             done = 0;
10032         int             restart = 0;
10033         mptsas_target_t *ptgt = NULL;
10034 
10035         NDBG22(("mptsas_watch_reset_delay_subr: mpt=0x%p", (void *)mpt));
10036 
10037         ASSERT(mutex_owned(&mpt->m_mutex));
10038 
10039         for (ptgt = refhash_first(mpt->m_targets); ptgt != NULL;
10040             ptgt = refhash_next(mpt->m_targets, ptgt)) {
10041                 mutex_enter(&ptgt->m_t_mutex);
10042                 if (ptgt->m_reset_delay != 0) {
10043                         ptgt->m_reset_delay -=
10044                             MPTSAS_WATCH_RESET_DELAY_TICK;
10045                         if (ptgt->m_reset_delay <= 0) {
10046                                 ptgt->m_reset_delay = 0;
10047                                 mptsas_set_throttle(mpt, ptgt,
10048                                     MAX_THROTTLE);
10049                                 restart++;
10050                         } else {
10051                                 done = -1;
10052                         }
10053                 }
10054                 mutex_exit(&ptgt->m_t_mutex);
10055         }
10056 
10057         if (restart > 0) {
10058                 mptsas_restart_hba(mpt);
10059         }
10060         return (done);
10061 }
10062 
10063 #ifdef MPTSAS_TEST
10064 static void
10065 mptsas_test_reset(mptsas_t *mpt, int target)
10066 {
10067         mptsas_target_t    *ptgt = NULL;
10068 
10069         if (mptsas_rtest == target) {
10070                 if (mptsas_do_scsi_reset(mpt, target) == TRUE) {
10071                         mptsas_rtest = -1;
10072                 }
10073                 if (mptsas_rtest == -1) {
10074                         NDBG22(("mptsas_test_reset success"));


10251                         rval = FALSE;
10252                 break;
10253         default:
10254                 rval = UNDEFINED;
10255                 break;
10256         }
10257 
10258         NDBG24(("mptsas_scsi_getcap: %s, rval=%x", cap, rval));
10259 
10260         mutex_exit(&mpt->m_mutex);
10261         return (rval);
10262 }
10263 
10264 /*
10265  * (*tran_setcap).  Set the capability named to the value given.
10266  */
10267 static int
10268 mptsas_scsi_setcap(struct scsi_address *ap, char *cap, int value, int tgtonly)
10269 {
10270         mptsas_t        *mpt = ADDR2MPT(ap);
10271         mptsas_target_t *ptgt;
10272         int             ckey;
10273         int             rval = FALSE;
10274 
10275         NDBG24(("mptsas_scsi_setcap: target=%d, cap=%s value=%x tgtonly=%x",
10276             ap->a_target, cap, value, tgtonly));
10277 
10278         if (!tgtonly) {
10279                 return (rval);
10280         }
10281 
10282         mutex_enter(&mpt->m_mutex);
10283 
10284         if ((mptsas_scsi_capchk(cap, tgtonly, &ckey)) != TRUE) {
10285                 mutex_exit(&mpt->m_mutex);
10286                 return (UNDEFINED);
10287         }
10288 
10289         switch (ckey) {
10290         case SCSI_CAP_DMA_MAX:
10291         case SCSI_CAP_MSG_OUT:


10293         case SCSI_CAP_INITIATOR_ID:
10294         case SCSI_CAP_LINKED_CMDS:
10295         case SCSI_CAP_UNTAGGED_QING:
10296         case SCSI_CAP_RESET_NOTIFICATION:
10297                 /*
10298                  * None of these are settable via
10299                  * the capability interface.
10300                  */
10301                 break;
10302         case SCSI_CAP_ARQ:
10303                 /*
10304                  * We cannot turn off arq so return false if asked to
10305                  */
10306                 if (value) {
10307                         rval = TRUE;
10308                 } else {
10309                         rval = FALSE;
10310                 }
10311                 break;
10312         case SCSI_CAP_TAGGED_QING:
10313                 ptgt = ((mptsas_tgt_private_t *)
10314                     (ap->a_hba_tran->tran_tgt_private))->t_private;
10315                 mptsas_set_throttle_mtx(mpt, ptgt, MAX_THROTTLE);
10316                 rval = TRUE;
10317                 break;
10318         case SCSI_CAP_QFULL_RETRIES:
10319                 ((mptsas_tgt_private_t *)(ap->a_hba_tran->tran_tgt_private))->
10320                     t_private->m_qfull_retries = (uchar_t)value;
10321                 rval = TRUE;
10322                 break;
10323         case SCSI_CAP_QFULL_RETRY_INTERVAL:
10324                 ((mptsas_tgt_private_t *)(ap->a_hba_tran->tran_tgt_private))->
10325                     t_private->m_qfull_retry_interval =
10326                     drv_usectohz(value * 1000);
10327                 rval = TRUE;
10328                 break;
10329         default:
10330                 rval = UNDEFINED;
10331                 break;
10332         }
10333         mutex_exit(&mpt->m_mutex);
10334         return (rval);
10335 }


10383 
10384         return (0);
10385 }
10386 
10387 static void
10388 mptsas_free_active_slots(mptsas_t *mpt)
10389 {
10390         mptsas_slots_t  *active = mpt->m_active;
10391         size_t          size;
10392 
10393         if (active == NULL)
10394                 return;
10395         size = active->m_size;
10396         kmem_free(active, size);
10397         mpt->m_active = NULL;
10398 }
10399 
10400 /*
10401  * Error logging, printing, and debug print routines.
10402  */
10403 static char *mptsas_label = "mpt_sas3";
10404 
10405 /*PRINTFLIKE3*/
10406 void
10407 mptsas_log(mptsas_t *mpt, int level, char *fmt, ...)
10408 {
10409         dev_info_t      *dev;
10410         va_list         ap;
10411 
10412         if (mpt) {
10413                 dev = mpt->m_dip;
10414         } else {
10415                 dev = 0;
10416         }
10417 
10418         mutex_enter(&mptsas_log_mutex);
10419 
10420         va_start(ap, fmt);
10421         (void) vsprintf(mptsas_log_buf, fmt, ap);
10422         va_end(ap);
10423 
10424         if (level == CE_CONT) {
10425                 scsi_log(dev, mptsas_label, level, "%s\n", mptsas_log_buf);
10426         } else {
10427                 scsi_log(dev, mptsas_label, level, "%s", mptsas_log_buf);
10428         }
10429 
10430         mutex_exit(&mptsas_log_mutex);
10431 }
10432 
10433 #ifdef MPTSAS_DEBUG
10434 /*
10435  * Use a circular buffer to log messages to private memory.
10436  * No mutexes, so there is the opportunity for this to miss lines.
10437  * But it's fast and does not hold up the proceedings too much.
10438  */
10439 static char mptsas_dbglog_bufs[32][256];
10440 static uint32_t mptsas_dbglog_idx = 1;
10441 
10442 /*PRINTFLIKE1*/
10443 void
10444 mptsas_debug_log(char *fmt, ...)
10445 {
10446         va_list         ap;
10447         uint32_t        idx;
10448 
10449         if (!mptsas_dbglog_idx) {
10450                 return;
10451         }
10452         idx = (mptsas_dbglog_idx++) & 0x1f;
10453 
10454         va_start(ap, fmt);
10455         (void) vsnprintf(mptsas_dbglog_bufs[idx],
10456             sizeof (mptsas_dbglog_bufs[0]), fmt, ap);
10457         va_end(ap);
10458 }
10459 
10460 /*PRINTFLIKE1*/
10461 void
10462 mptsas_printf(char *fmt, ...)
10463 {
10464         dev_info_t      *dev = 0;
10465         va_list         ap;
10466 
10467         mutex_enter(&mptsas_log_mutex);
10468 
10469         va_start(ap, fmt);
10470         (void) vsprintf(mptsas_log_buf, fmt, ap);
10471         va_end(ap);
10472 
10473 #ifdef PROM_PRINTF
10474         prom_printf("%s:\t%s\n", mptsas_label, mptsas_log_buf);
10475 #else
10476         scsi_log(dev, mptsas_label, CE_CONT, "!%s\n", mptsas_log_buf);
10477 #endif
10478         mutex_exit(&mptsas_log_mutex);
10479 }
10480 #endif
10481 
10482 /*
10483  * timeout handling
10484  */
10485 static void
10486 mptsas_watch(void *arg)
10487 {
10488 #ifndef __lock_lint
10489         _NOTE(ARGUNUSED(arg))
10490 #endif
10491 
10492         mptsas_t        *mpt;
10493         uint32_t        doorbell;
10494 
10495         NDBG30(("mptsas_watch"));
10496 


10528                 /*
10529                  * For now, always call mptsas_watchsubr.
10530                  */
10531                 mptsas_watchsubr(mpt);
10532 
10533                 if (mpt->m_options & MPTSAS_OPT_PM) {
10534                         mpt->m_busy = 0;
10535                         (void) pm_idle_component(mpt->m_dip, 0);
10536                 }
10537 
10538                 mutex_exit(&mpt->m_mutex);
10539         }
10540         rw_exit(&mptsas_global_rwlock);
10541 
10542         mutex_enter(&mptsas_global_mutex);
10543         if (mptsas_timeouts_enabled)
10544                 mptsas_timeout_id = timeout(mptsas_watch, NULL, mptsas_tick);
10545         mutex_exit(&mptsas_global_mutex);
10546 }
10547 
10548 int mptsas_monitor_for_txwqs = 1;
10549 static void
10550 mptsas_watchsubr(mptsas_t *mpt)
10551 {
10552         int             i;
10553         mptsas_cmd_t    *cmd;
10554         mptsas_target_t *ptgt = NULL;
10555         hrtime_t        timestamp = gethrtime();
10556         boolean_t       restart_hba = B_FALSE;
10557 
10558         ASSERT(MUTEX_HELD(&mpt->m_mutex));
10559 
10560         NDBG30(("mptsas_watchsubr: mpt=0x%p, ncmds %d, nstarted %d",
10561             (void *)mpt, mpt->m_ncmds, mpt->m_ncstarted));
10562 
10563         mpt->m_lncstarted = mpt->m_ncstarted;
10564         if (mpt->m_txwq_thread_n != 0 && mpt->m_txwq_enabled != BLOCKED &&
10565             mptsas_monitor_for_txwqs) {
10566                 i = mpt->m_ncstarted/mptsas_scsi_watchdog_tick;
10567                 if (i > mpt->m_txwq_thread_threshold) {
10568                         mpt->m_txwq_enabled = TRUE;
10569                 } else if (i < (mpt->m_txwq_thread_threshold>>1)) {
10570                         mpt->m_txwq_enabled = FALSE;
10571                 }
10572         }
10573         mpt->m_ncstarted = 0;
10574 
10575         /*
10576          * Check for commands stuck in active slot
10577          * Account for TM requests, which use the last SMID.
10578          */
10579         for (i = 0; i <= mpt->m_active->m_n_normal; i++) {
10580                 if ((cmd = mpt->m_active->m_slot[i]) != NULL) {
10581                         if (cmd->cmd_active_expiration <= timestamp) {
10582                                 if ((cmd->cmd_flags & CFLAG_CMDIOC) == 0) {



10583                                         /*
10584                                          * There seems to be a command stuck
10585                                          * in the active slot.  Drain throttle.
10586                                          */
10587                                         ptgt = cmd->cmd_tgt_addr;
10588                                         mptsas_set_throttle_mtx(mpt, ptgt,
10589                                             DRAIN_THROTTLE);
10590                                 } else if (cmd->cmd_flags &
10591                                     (CFLAG_PASSTHRU | CFLAG_CONFIG |
10592                                     CFLAG_FW_DIAG)) {





10593                                         /*
10594                                          * passthrough command timeout
10595                                          */
10596                                         cmd->cmd_flags |= (CFLAG_FINISHED |
10597                                             CFLAG_TIMEOUT);
10598                                         cv_broadcast(&mpt->m_passthru_cv);
10599                                         cv_broadcast(&mpt->m_config_cv);
10600                                         cv_broadcast(&mpt->m_fw_diag_cv);
10601                                 }
10602                         }
10603                 }
10604         }
10605 
10606         for (ptgt = refhash_first(mpt->m_targets); ptgt != NULL;
10607             ptgt = refhash_next(mpt->m_targets, ptgt)) {
10608                 mutex_enter(&ptgt->m_t_mutex);
10609                 /*
10610                  * If we were draining due to a qfull condition,
10611                  * go back to full throttle.
10612                  */
10613                 if ((ptgt->m_t_throttle < MAX_THROTTLE) &&
10614                     (ptgt->m_t_throttle > HOLD_THROTTLE) &&
10615                     (ptgt->m_t_ncmds < ptgt->m_t_throttle)) {
10616                         mptsas_set_throttle(mpt, ptgt, MAX_THROTTLE);
10617                         restart_hba = B_TRUE;
10618                 }
10619 
10620                 cmd = TAILQ_LAST(&ptgt->m_active_cmdq, mptsas_active_cmdq);
10621                 if (cmd != NULL) {
10622                         if (cmd->cmd_active_expiration <= timestamp) {
10623                                 /*
10624                                  * Earliest command timeout expired.
10625                                  * Drain throttle.
10626                                  */
10627                                 mptsas_set_throttle(mpt, ptgt, DRAIN_THROTTLE);
10628 
10629                                 /*
10630                                  * Check for remaining commands.
10631                                  */
10632                                 cmd = TAILQ_FIRST(&ptgt->m_active_cmdq);
10633                                 if (cmd->cmd_active_expiration > timestamp) {
10634                                         /*
10635                                          * Wait for remaining commands to
10636                                          * complete or time out.
10637                                          */
10638                                         NDBG23(("command timed out, "
10639                                             "pending drain"));
10640                                 } else {
10641                                         mutex_exit(&ptgt->m_t_mutex);
10642 
10643                                         /*
10644                                          * All command timeouts expired.
10645                                          */
10646                                         mptsas_log(mpt, CE_NOTE,
10647                                             "Timeout of %d seconds "
10648                                             "expired with %d commands on "
10649                                             "target %d lun %d.",
10650                                             cmd->cmd_pkt->pkt_time,
10651                                             ptgt->m_t_ncmds,
10652                                             ptgt->m_devhdl, Lun(cmd));
10653 
10654                                         mptsas_cmd_timeout(mpt, ptgt);

10655                                         continue;
10656                                 }
10657                         } else if (cmd->cmd_active_expiration <= timestamp +
10658                             (hrtime_t)mptsas_scsi_watchdog_tick * NANOSEC) {

10659                                 NDBG23(("pending timeout"));
10660                                 mptsas_set_throttle(mpt, ptgt, DRAIN_THROTTLE);
10661                         }
10662                 }
10663                 mutex_exit(&ptgt->m_t_mutex);
10664         }
10665         if (restart_hba == B_TRUE) {
10666                 mptsas_restart_hba(mpt);
10667         }
10668 }
10669 
10670 /*
10671  * timeout recovery
10672  */
10673 static void
10674 mptsas_cmd_timeout(mptsas_t *mpt, mptsas_target_t *ptgt)
10675 {
10676         uint16_t        devhdl;
10677         uint64_t        sas_wwn;
10678         uint8_t         phy;
10679         char            wwn_str[MPTSAS_WWN_STRLEN];
10680 
10681         devhdl = ptgt->m_devhdl;
10682         sas_wwn = ptgt->m_addr.mta_wwn;
10683         phy = ptgt->m_phynum;
10684         if (sas_wwn == 0) {
10685                 (void) sprintf(wwn_str, "p%x", phy);
10686         } else {
10687                 (void) sprintf(wwn_str, "w%016"PRIx64, sas_wwn);
10688         }
10689 
10690         NDBG29(("mptsas_cmd_timeout: target=%d", devhdl));
10691         mptsas_log(mpt, CE_WARN, "Disconnected command timeout for "
10692             "target %d %s,  enclosure %u .", devhdl, wwn_str,
10693             ptgt->m_enclosure);
10694 
10695         /*
10696          * Abort all outstanding commands on the device.

10697          */
10698         NDBG29(("mptsas_cmd_timeout: device reset"));
10699         if (mptsas_do_scsi_reset(mpt, devhdl) != TRUE) {
10700                 mptsas_log(mpt, CE_WARN, "Target %d reset for command timeout "
10701                     "recovery failed!", devhdl);
10702         }
10703 }
10704 
10705 /*
10706  * Device / Hotplug control
10707  */
10708 static int
10709 mptsas_scsi_quiesce(dev_info_t *dip)
10710 {
10711         mptsas_t        *mpt;
10712         scsi_hba_tran_t *tran;
10713 
10714         tran = ddi_get_driver_private(dip);
10715         if (tran == NULL || (mpt = TRAN2MPT(tran)) == NULL)
10716                 return (-1);


10725         scsi_hba_tran_t *tran;
10726 
10727         tran = ddi_get_driver_private(dip);
10728         if (tran == NULL || (mpt = TRAN2MPT(tran)) == NULL)
10729                 return (-1);
10730 
10731         return (mptsas_unquiesce_bus(mpt));
10732 }
10733 
10734 static int
10735 mptsas_quiesce_bus(mptsas_t *mpt)
10736 {
10737         mptsas_target_t *ptgt = NULL;
10738 
10739         NDBG28(("mptsas_quiesce_bus"));
10740         mutex_enter(&mpt->m_mutex);
10741 
10742         /* Set all the throttles to zero */
10743         for (ptgt = refhash_first(mpt->m_targets); ptgt != NULL;
10744             ptgt = refhash_next(mpt->m_targets, ptgt)) {
10745                 mptsas_set_throttle_mtx(mpt, ptgt, HOLD_THROTTLE);
10746         }
10747 
10748         /* If there are any outstanding commands in the queue */
10749         if (mpt->m_ncmds) {
10750                 mpt->m_softstate |= MPTSAS_SS_DRAINING;
10751                 mpt->m_quiesce_timeid = timeout(mptsas_ncmds_checkdrain,
10752                     mpt, (MPTSAS_QUIESCE_TIMEOUT * drv_usectohz(1000000)));
10753                 if (cv_wait_sig(&mpt->m_cv, &mpt->m_mutex) == 0) {
10754                         /*
10755                          * Quiesce has been interrupted
10756                          */
10757                         mpt->m_softstate &= ~MPTSAS_SS_DRAINING;
10758                         for (ptgt = refhash_first(mpt->m_targets); ptgt != NULL;
10759                             ptgt = refhash_next(mpt->m_targets, ptgt)) {
10760                                 mptsas_set_throttle_mtx(mpt, ptgt,
10761                                     MAX_THROTTLE);
10762                         }
10763                         mptsas_restart_hba(mpt);
10764                         if (mpt->m_quiesce_timeid != 0) {
10765                                 timeout_id_t tid = mpt->m_quiesce_timeid;
10766                                 mpt->m_quiesce_timeid = 0;
10767                                 mutex_exit(&mpt->m_mutex);
10768                                 (void) untimeout(tid);
10769                                 return (-1);
10770                         }
10771                         mutex_exit(&mpt->m_mutex);
10772                         return (-1);
10773                 } else {
10774                         /* Bus has been quiesced */
10775                         ASSERT(mpt->m_quiesce_timeid == 0);
10776                         mpt->m_softstate &= ~MPTSAS_SS_DRAINING;
10777                         mpt->m_softstate |= MPTSAS_SS_QUIESCED;
10778                         mutex_exit(&mpt->m_mutex);
10779                         return (0);
10780                 }
10781         }
10782         /* Bus was not busy - QUIESCED */
10783         mutex_exit(&mpt->m_mutex);
10784 
10785         return (0);
10786 }
10787 
10788 static int
10789 mptsas_unquiesce_bus(mptsas_t *mpt)
10790 {
10791         mptsas_target_t *ptgt = NULL;
10792 
10793         NDBG28(("mptsas_unquiesce_bus"));
10794         mutex_enter(&mpt->m_mutex);
10795         mpt->m_softstate &= ~MPTSAS_SS_QUIESCED;
10796         for (ptgt = refhash_first(mpt->m_targets); ptgt != NULL;
10797             ptgt = refhash_next(mpt->m_targets, ptgt)) {
10798                 mptsas_set_throttle_mtx(mpt, ptgt, MAX_THROTTLE);
10799         }
10800         mptsas_restart_hba(mpt);
10801         mutex_exit(&mpt->m_mutex);
10802         return (0);
10803 }
10804 
10805 static void
10806 mptsas_ncmds_checkdrain(void *arg)
10807 {
10808         mptsas_t        *mpt = arg;
10809         mptsas_target_t *ptgt = NULL;
10810 
10811         mutex_enter(&mpt->m_mutex);
10812         if (mpt->m_softstate & MPTSAS_SS_DRAINING) {
10813                 mpt->m_quiesce_timeid = 0;
10814                 if (mpt->m_ncmds == 0) {
10815                         /* Command queue has been drained */
10816                         cv_signal(&mpt->m_cv);
10817                 } else {
10818                         /*
10819                          * The throttle may have been reset because
10820                          * of a SCSI bus reset
10821                          */
10822                         for (ptgt = refhash_first(mpt->m_targets); ptgt != NULL;
10823                             ptgt = refhash_next(mpt->m_targets, ptgt)) {
10824                                 mptsas_set_throttle_mtx(mpt, ptgt,
10825                                     HOLD_THROTTLE);
10826                         }
10827 
10828                         mpt->m_quiesce_timeid = timeout(mptsas_ncmds_checkdrain,
10829                             mpt, (MPTSAS_QUIESCE_TIMEOUT *
10830                             drv_usectohz(1000000)));
10831                 }
10832         }
10833         mutex_exit(&mpt->m_mutex);
10834 }
10835 
10836 /*ARGSUSED*/
10837 static void
10838 mptsas_dump_cmd(mptsas_t *mpt, mptsas_cmd_t *cmd)
10839 {
10840         int     i;
10841         uint8_t *cp = (uchar_t *)cmd->cmd_pkt->pkt_cdbp;
10842         char    buf[128];
10843 
10844         buf[0] = '\0';
10845         NDBG25(("?Cmd (0x%p) dump for Target %d Lun %d:\n", (void *)cmd,
10846             Tgt(cmd), Lun(cmd)));
10847         (void) sprintf(&buf[0], "\tcdb=[");
10848         for (i = 0; i < (int)cmd->cmd_cdblen; i++) {
10849                 (void) sprintf(&buf[strlen(buf)], " 0x%x", *cp++);
10850         }
10851         (void) sprintf(&buf[strlen(buf)], " ]");
10852         NDBG25(("?%s\n", buf));
10853         NDBG25(("?pkt_flags=0x%x pkt_statistics=0x%x pkt_state=0x%x\n",
10854             cmd->cmd_pkt->pkt_flags, cmd->cmd_pkt->pkt_statistics,
10855             cmd->cmd_pkt->pkt_state));
10856         NDBG25(("?pkt_scbp=0x%x cmd_flags=0x%x\n", cmd->cmd_pkt->pkt_scbp ?
10857             *(cmd->cmd_pkt->pkt_scbp) : 0, cmd->cmd_flags));
10858 }
10859 
10860 static void
10861 mptsas_passthru_sge(ddi_acc_handle_t acc_hdl, mptsas_pt_request_t *pt,
10862     pMpi2SGESimple64_t sgep)
10863 {
10864         uint32_t                sge_flags;
10865         uint32_t                data_size, dataout_size;
10866         ddi_dma_cookie_t        data_cookie;
10867         ddi_dma_cookie_t        dataout_cookie;
10868 
10869         data_size = pt->data_size;
10870         dataout_size = pt->dataout_size;
10871         data_cookie = pt->data_cookie;
10872         dataout_cookie = pt->dataout_cookie;
10873 
10874         if (dataout_size) {
10875                 sge_flags = dataout_size |
10876                     ((uint32_t)(MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
10877                     MPI2_SGE_FLAGS_END_OF_BUFFER |
10878                     MPI2_SGE_FLAGS_HOST_TO_IOC |
10879                     MPI2_SGE_FLAGS_64_BIT_ADDRESSING) <<
10880                     MPI2_SGE_FLAGS_SHIFT);
10881                 ddi_put32(acc_hdl, &sgep->FlagsLength, sge_flags);
10882                 ddi_put32(acc_hdl, &sgep->Address.Low,
10883                     (uint32_t)(dataout_cookie.dmac_laddress & 0xffffffffull));
10884                 ddi_put32(acc_hdl, &sgep->Address.High,
10885                     (uint32_t)(dataout_cookie.dmac_laddress >> 32));
10886                 sgep++;
10887         }
10888         sge_flags = data_size;
10889         sge_flags |= ((uint32_t)(MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
10890             MPI2_SGE_FLAGS_LAST_ELEMENT |
10891             MPI2_SGE_FLAGS_END_OF_BUFFER |
10892             MPI2_SGE_FLAGS_END_OF_LIST |
10893             MPI2_SGE_FLAGS_64_BIT_ADDRESSING) <<
10894             MPI2_SGE_FLAGS_SHIFT);
10895         if (pt->direction == MPTSAS_PASS_THRU_DIRECTION_WRITE) {
10896                 sge_flags |= ((uint32_t)(MPI2_SGE_FLAGS_HOST_TO_IOC) <<
10897                     MPI2_SGE_FLAGS_SHIFT);
10898         } else {
10899                 sge_flags |= ((uint32_t)(MPI2_SGE_FLAGS_IOC_TO_HOST) <<
10900                     MPI2_SGE_FLAGS_SHIFT);
10901         }
10902         ddi_put32(acc_hdl, &sgep->FlagsLength, sge_flags);
10903         ddi_put32(acc_hdl, &sgep->Address.Low,
10904             (uint32_t)(data_cookie.dmac_laddress & 0xffffffffull));
10905         ddi_put32(acc_hdl, &sgep->Address.High,
10906             (uint32_t)(data_cookie.dmac_laddress >> 32));
10907 }
10908 
10909 static void
10910 mptsas_passthru_ieee_sge(ddi_acc_handle_t acc_hdl, mptsas_pt_request_t *pt,
10911     pMpi2IeeeSgeSimple64_t ieeesgep)
10912 {
10913         uint8_t                 sge_flags;
10914         uint32_t                data_size, dataout_size;
10915         ddi_dma_cookie_t        data_cookie;
10916         ddi_dma_cookie_t        dataout_cookie;
10917 
10918         data_size = pt->data_size;
10919         dataout_size = pt->dataout_size;
10920         data_cookie = pt->data_cookie;
10921         dataout_cookie = pt->dataout_cookie;
10922 
10923         sge_flags = (MPI2_IEEE_SGE_FLAGS_SIMPLE_ELEMENT |
10924             MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR);
10925         if (dataout_size) {
10926                 ddi_put32(acc_hdl, &ieeesgep->Length, dataout_size);
10927                 ddi_put32(acc_hdl, &ieeesgep->Address.Low,
10928                     (uint32_t)(dataout_cookie.dmac_laddress &
10929                     0xffffffffull));
10930                 ddi_put32(acc_hdl, &ieeesgep->Address.High,
10931                     (uint32_t)(dataout_cookie.dmac_laddress >> 32));
10932                 ddi_put8(acc_hdl, &ieeesgep->Flags, sge_flags);
10933                 ieeesgep++;
10934         }
10935         sge_flags |= MPI25_IEEE_SGE_FLAGS_END_OF_LIST;
10936         ddi_put32(acc_hdl, &ieeesgep->Length, data_size);
10937         ddi_put32(acc_hdl, &ieeesgep->Address.Low,
10938             (uint32_t)(data_cookie.dmac_laddress & 0xffffffffull));
10939         ddi_put32(acc_hdl, &ieeesgep->Address.High,
10940             (uint32_t)(data_cookie.dmac_laddress >> 32));
10941         ddi_put8(acc_hdl, &ieeesgep->Flags, sge_flags);
10942 }
10943 
10944 static void
10945 mptsas_start_passthru(mptsas_t *mpt, mptsas_cmd_t *cmd)
10946 {
10947         caddr_t                 memp;
10948         pMPI2RequestHeader_t    request_hdrp;
10949         struct scsi_pkt         *pkt = cmd->cmd_pkt;
10950         mptsas_pt_request_t     *pt = pkt->pkt_ha_private;
10951         uint32_t                request_size;
10952         uint64_t                request_desc = 0;
10953         uint64_t                sense_bufp;



10954         uint8_t                 desc_type;
10955         uint8_t                 *request, function;
10956         ddi_dma_handle_t        dma_hdl = mpt->m_dma_req_frame_hdl;
10957         ddi_acc_handle_t        acc_hdl = mpt->m_acc_req_frame_hdl;
10958 
10959         desc_type = MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE;
10960 
10961         request = pt->request;

10962         request_size = pt->request_size;




10963 
10964         /*
10965          * Store the passthrough message in memory location
10966          * corresponding to our slot number
10967          */
10968         memp = mpt->m_req_frame + (mpt->m_req_frame_size * cmd->cmd_slot);
10969         request_hdrp = (pMPI2RequestHeader_t)memp;
10970         bzero(memp, mpt->m_req_frame_size);
10971 
10972         bcopy(request, memp, request_size);






10973 
10974         NDBG15(("mptsas_start_passthru: Func 0x%x, MsgFlags 0x%x, "
10975             "size=%d, in %d, out %d", request_hdrp->Function,
10976             request_hdrp->MsgFlags, request_size,
10977             pt->data_size, pt->dataout_size));
10978 
10979         /*
10980          * Add an SGE, even if the length is zero.
10981          */
10982         if (mpt->m_MPI25 && pt->simple == 0) {
10983                 mptsas_passthru_ieee_sge(acc_hdl, pt,
10984                     (pMpi2IeeeSgeSimple64_t)
10985                     ((uint8_t *)request_hdrp + pt->sgl_offset));


















10986         } else {
10987                 mptsas_passthru_sge(acc_hdl, pt,
10988                     (pMpi2SGESimple64_t)
10989                     ((uint8_t *)request_hdrp + pt->sgl_offset));







10990         }
10991 
10992         function = request_hdrp->Function;
10993         if ((function == MPI2_FUNCTION_SCSI_IO_REQUEST) ||
10994             (function == MPI2_FUNCTION_RAID_SCSI_IO_PASSTHROUGH)) {
10995                 pMpi2SCSIIORequest_t    scsi_io_req;
10996 
10997                 NDBG15(("mptsas_start_passthru: Is SCSI IO Req"));
10998                 scsi_io_req = (pMpi2SCSIIORequest_t)request_hdrp;
10999                 /*
11000                  * Put SGE for data and data_out buffer at the end of
11001                  * scsi_io_request message header.(64 bytes in total)
11002                  * Following above SGEs, the residual space will be
11003                  * used by sense data.
11004                  */
11005                 ddi_put8(acc_hdl,
11006                     &scsi_io_req->SenseBufferLength,
11007                     (uint8_t)(request_size - 64));
11008 
11009                 sense_bufp = (uint32_t)(mpt->m_req_frame_dma_addr +
11010                     (mpt->m_req_frame_size * cmd->cmd_slot) & 0xffffffffull);
11011                 sense_bufp += 64;
11012                 ddi_put32(acc_hdl,
11013                     &scsi_io_req->SenseBufferLowAddress, sense_bufp);
11014 
11015                 /*
11016                  * Set SGLOffset0 value
11017                  */
11018                 ddi_put8(acc_hdl, &scsi_io_req->SGLOffset0,
11019                     offsetof(MPI2_SCSI_IO_REQUEST, SGL) / 4);
11020 
11021                 /*
11022                  * Setup descriptor info.  RAID passthrough must use the
11023                  * default request descriptor which is already set, so if this
11024                  * is a SCSI IO request, change the descriptor to SCSI IO.
11025                  */
11026                 if (function == MPI2_FUNCTION_SCSI_IO_REQUEST) {
11027                         desc_type = MPI2_REQ_DESCRIPT_FLAGS_SCSI_IO;
11028                         request_desc = (((uint64_t)ddi_get16(acc_hdl,
11029                             &scsi_io_req->DevHandle)) << 48);
11030                 }
11031         }
11032 
11033         /*
11034          * We must wait till the message has been completed before
11035          * beginning the next message so we wait for this one to
11036          * finish.
11037          */
11038         (void) ddi_dma_sync(dma_hdl, 0, 0, DDI_DMA_SYNC_FORDEV);
11039         request_desc |= ((cmd->cmd_slot << 16) | desc_type);
11040         cmd->cmd_rfm = NULL;
11041         MPTSAS_START_CMD(mpt, request_desc);
11042         if ((mptsas_check_dma_handle(dma_hdl) != DDI_SUCCESS) ||
11043             (mptsas_check_acc_handle(acc_hdl) != DDI_SUCCESS)) {
11044                 ddi_fm_service_impact(mpt->m_dip, DDI_SERVICE_UNAFFECTED);
11045         }
11046 }
11047 
11048 typedef void (mps_pre_f)(mptsas_t *, mptsas_pt_request_t *);
11049 static mps_pre_f        mpi_pre_ioc_facts;
11050 static mps_pre_f        mpi_pre_port_facts;
11051 static mps_pre_f        mpi_pre_fw_download;
11052 static mps_pre_f        mpi_pre_fw_25_download;
11053 static mps_pre_f        mpi_pre_fw_upload;
11054 static mps_pre_f        mpi_pre_fw_25_upload;
11055 static mps_pre_f        mpi_pre_sata_passthrough;
11056 static mps_pre_f        mpi_pre_smp_passthrough;
11057 static mps_pre_f        mpi_pre_config;
11058 static mps_pre_f        mpi_pre_sas_io_unit_control;
11059 static mps_pre_f        mpi_pre_scsi_io_req;
11060 
11061 /*
11062  * Prepare the pt for a SAS2 FW_DOWNLOAD request.
11063  */
11064 static void
11065 mpi_pre_fw_download(mptsas_t *mpt, mptsas_pt_request_t *pt)
11066 {
11067         pMpi2FWDownloadTCSGE_t tcsge;
11068         pMpi2FWDownloadRequest req;
11069 
11070         /*
11071          * If SAS3, call separate function.
11072          */
11073         if (mpt->m_MPI25) {
11074                 mpi_pre_fw_25_download(mpt, pt);
11075                 return;
11076         }
11077 
11078         /*
11079          * User requests should come in with the Transaction
11080          * context element where the SGL will go. Putting the
11081          * SGL after that seems to work, but don't really know
11082          * why. Other drivers tend to create an extra SGL and
11083          * refer to the TCE through that.
11084          */
11085         req = (pMpi2FWDownloadRequest)pt->request;
11086         tcsge = (pMpi2FWDownloadTCSGE_t)&req->SGL;
11087         if (tcsge->ContextSize != 0 || tcsge->DetailsLength != 12 ||
11088             tcsge->Flags != MPI2_SGE_FLAGS_TRANSACTION_ELEMENT) {
11089                 mptsas_log(mpt, CE_WARN, "FW Download tce invalid!");
11090         }
11091 
11092         pt->sgl_offset = offsetof(MPI2_FW_DOWNLOAD_REQUEST, SGL) +
11093             sizeof (*tcsge);
11094         if (pt->request_size != pt->sgl_offset)
11095                 NDBG15(("mpi_pre_fw_download(): Incorrect req size, "
11096                     "0x%x, should be 0x%x, dataoutsz 0x%x",
11097                     (int)pt->request_size, (int)pt->sgl_offset,
11098                     (int)pt->dataout_size));
11099         if (pt->data_size < sizeof (MPI2_FW_DOWNLOAD_REPLY))
11100                 NDBG15(("mpi_pre_fw_download(): Incorrect rep size, "
11101                     "0x%x, should be 0x%x", pt->data_size,
11102                     (int)sizeof (MPI2_FW_DOWNLOAD_REPLY)));
11103 }
11104 
11105 /*
11106  * Prepare the pt for a SAS3 FW_DOWNLOAD request.
11107  */
11108 static void
11109 mpi_pre_fw_25_download(mptsas_t *mpt, mptsas_pt_request_t *pt)
11110 {
11111         pMpi2FWDownloadTCSGE_t tcsge;
11112         pMpi2FWDownloadRequest req2;
11113         pMpi25FWDownloadRequest req25;
11114 
11115         /*
11116          * User requests should come in with the Transaction
11117          * context element where the SGL will go. The new firmware
11118          * Doesn't use TCE and has space in the main request for
11119          * this information. So move to the right place.
11120          */
11121         req2 = (pMpi2FWDownloadRequest)pt->request;
11122         req25 = (pMpi25FWDownloadRequest)pt->request;
11123         tcsge = (pMpi2FWDownloadTCSGE_t)&req2->SGL;
11124         if (tcsge->ContextSize != 0 || tcsge->DetailsLength != 12 ||
11125             tcsge->Flags != MPI2_SGE_FLAGS_TRANSACTION_ELEMENT) {
11126                 mptsas_log(mpt, CE_WARN, "FW Download tce invalid!");
11127         }
11128         req25->ImageOffset = tcsge->ImageOffset;
11129         req25->ImageSize = tcsge->ImageSize;
11130 
11131         pt->sgl_offset = offsetof(MPI25_FW_DOWNLOAD_REQUEST, SGL);
11132         if (pt->request_size != pt->sgl_offset)
11133                 NDBG15(("mpi_pre_fw_25_download(): Incorrect req size, "
11134                     "0x%x, should be 0x%x, dataoutsz 0x%x",
11135                     pt->request_size, pt->sgl_offset,
11136                     pt->dataout_size));
11137         if (pt->data_size < sizeof (MPI2_FW_DOWNLOAD_REPLY))
11138                 NDBG15(("mpi_pre_fw_25_download(): Incorrect rep size, "
11139                     "0x%x, should be 0x%x", pt->data_size,
11140                     (int)sizeof (MPI2_FW_UPLOAD_REPLY)));
11141 }
11142 
11143 /*
11144  * Prepare the pt for a SAS2 FW_UPLOAD request.
11145  */
11146 static void
11147 mpi_pre_fw_upload(mptsas_t *mpt, mptsas_pt_request_t *pt)
11148 {
11149         pMpi2FWUploadTCSGE_t tcsge;
11150         pMpi2FWUploadRequest_t req;
11151 
11152         /*
11153          * If SAS3, call separate function.
11154          */
11155         if (mpt->m_MPI25) {
11156                 mpi_pre_fw_25_upload(mpt, pt);
11157                 return;
11158         }
11159 
11160         /*
11161          * User requests should come in with the Transaction
11162          * context element where the SGL will go. Putting the
11163          * SGL after that seems to work, but don't really know
11164          * why. Other drivers tend to create an extra SGL and
11165          * refer to the TCE through that.
11166          */
11167         req = (pMpi2FWUploadRequest_t)pt->request;
11168         tcsge = (pMpi2FWUploadTCSGE_t)&req->SGL;
11169         if (tcsge->ContextSize != 0 || tcsge->DetailsLength != 12 ||
11170             tcsge->Flags != MPI2_SGE_FLAGS_TRANSACTION_ELEMENT) {
11171                 mptsas_log(mpt, CE_WARN, "FW Upload tce invalid!");
11172         }
11173 
11174         pt->sgl_offset = offsetof(MPI2_FW_UPLOAD_REQUEST, SGL) +
11175             sizeof (*tcsge);
11176         if (pt->request_size != pt->sgl_offset)
11177                 NDBG15(("mpi_pre_fw_upload(): Incorrect req size, "
11178                     "0x%x, should be 0x%x, dataoutsz 0x%x",
11179                     pt->request_size, pt->sgl_offset,
11180                     pt->dataout_size));
11181         if (pt->data_size < sizeof (MPI2_FW_UPLOAD_REPLY))
11182                 NDBG15(("mpi_pre_fw_upload(): Incorrect rep size, "
11183                     "0x%x, should be 0x%x", pt->data_size,
11184                     (int)sizeof (MPI2_FW_UPLOAD_REPLY)));
11185 }
11186 
11187 /*
11188  * Prepare the pt a SAS3 FW_UPLOAD request.
11189  */
11190 static void
11191 mpi_pre_fw_25_upload(mptsas_t *mpt, mptsas_pt_request_t *pt)
11192 {
11193         pMpi2FWUploadTCSGE_t tcsge;
11194         pMpi2FWUploadRequest_t req2;
11195         pMpi25FWUploadRequest_t req25;
11196 
11197         /*
11198          * User requests should come in with the Transaction
11199          * context element where the SGL will go. The new firmware
11200          * Doesn't use TCE and has space in the main request for
11201          * this information. So move to the right place.
11202          */
11203         req2 = (pMpi2FWUploadRequest_t)pt->request;
11204         req25 = (pMpi25FWUploadRequest_t)pt->request;
11205         tcsge = (pMpi2FWUploadTCSGE_t)&req2->SGL;
11206         if (tcsge->ContextSize != 0 || tcsge->DetailsLength != 12 ||
11207             tcsge->Flags != MPI2_SGE_FLAGS_TRANSACTION_ELEMENT) {
11208                 mptsas_log(mpt, CE_WARN, "FW Upload tce invalid!");
11209         }
11210         req25->ImageOffset = tcsge->ImageOffset;
11211         req25->ImageSize = tcsge->ImageSize;
11212 
11213         pt->sgl_offset = offsetof(MPI25_FW_UPLOAD_REQUEST, SGL);
11214         if (pt->request_size != pt->sgl_offset)
11215                 NDBG15(("mpi_pre_fw_25_upload(): Incorrect req size, "
11216                     "0x%x, should be 0x%x, dataoutsz 0x%x",
11217                     pt->request_size, pt->sgl_offset,
11218                     pt->dataout_size));
11219         if (pt->data_size < sizeof (MPI2_FW_UPLOAD_REPLY))
11220                 NDBG15(("mpi_pre_fw_25_upload(): Incorrect rep size, "
11221                     "0x%x, should be 0x%x", pt->data_size,
11222                     (int)sizeof (MPI2_FW_UPLOAD_REPLY)));
11223 }
11224 
11225 /*
11226  * Prepare the pt for an IOC_FACTS request.
11227  */
11228 static void
11229 mpi_pre_ioc_facts(mptsas_t *mpt, mptsas_pt_request_t *pt)
11230 {
11231 #ifndef __lock_lint
11232         _NOTE(ARGUNUSED(mpt))
11233 #endif
11234         if (pt->request_size != sizeof (MPI2_IOC_FACTS_REQUEST))
11235                 NDBG15(("mpi_pre_ioc_facts(): Incorrect req size, "
11236                     "0x%x, should be 0x%x, dataoutsz 0x%x",
11237                     pt->request_size,
11238                     (int)sizeof (MPI2_IOC_FACTS_REQUEST),
11239                     pt->dataout_size));
11240         if (pt->data_size != sizeof (MPI2_IOC_FACTS_REPLY))
11241                 NDBG15(("mpi_pre_ioc_facts(): Incorrect rep size, "
11242                     "0x%x, should be 0x%x", pt->data_size,
11243                     (int)sizeof (MPI2_IOC_FACTS_REPLY)));
11244         pt->sgl_offset = (uint16_t)pt->request_size;
11245 }
11246 
11247 /*
11248  * Prepare the pt for a PORT_FACTS request.
11249  */
11250 static void
11251 mpi_pre_port_facts(mptsas_t *mpt, mptsas_pt_request_t *pt)
11252 {
11253 #ifndef __lock_lint
11254         _NOTE(ARGUNUSED(mpt))
11255 #endif
11256         if (pt->request_size != sizeof (MPI2_PORT_FACTS_REQUEST))
11257                 NDBG15(("mpi_pre_port_facts(): Incorrect req size, "
11258                     "0x%x, should be 0x%x, dataoutsz 0x%x",
11259                     pt->request_size,
11260                     (int)sizeof (MPI2_PORT_FACTS_REQUEST),
11261                     pt->dataout_size));
11262         if (pt->data_size != sizeof (MPI2_PORT_FACTS_REPLY))
11263                 NDBG15(("mpi_pre_port_facts(): Incorrect rep size, "
11264                     "0x%x, should be 0x%x", pt->data_size,
11265                     (int)sizeof (MPI2_PORT_FACTS_REPLY)));
11266         pt->sgl_offset = (uint16_t)pt->request_size;
11267 }
11268 
11269 /*
11270  * Prepare pt for a SATA_PASSTHROUGH request.
11271  */
11272 static void
11273 mpi_pre_sata_passthrough(mptsas_t *mpt, mptsas_pt_request_t *pt)
11274 {
11275 #ifndef __lock_lint
11276         _NOTE(ARGUNUSED(mpt))
11277 #endif
11278         pt->sgl_offset = offsetof(MPI2_SATA_PASSTHROUGH_REQUEST, SGL);
11279         if (pt->request_size != pt->sgl_offset)
11280                 NDBG15(("mpi_pre_sata_passthrough(): Incorrect req size, "
11281                     "0x%x, should be 0x%x, dataoutsz 0x%x",
11282                     pt->request_size, pt->sgl_offset,
11283                     pt->dataout_size));
11284         if (pt->data_size != sizeof (MPI2_SATA_PASSTHROUGH_REPLY))
11285                 NDBG15(("mpi_pre_sata_passthrough(): Incorrect rep size, "
11286                     "0x%x, should be 0x%x", pt->data_size,
11287                     (int)sizeof (MPI2_SATA_PASSTHROUGH_REPLY)));
11288 }
11289 
11290 static void
11291 mpi_pre_smp_passthrough(mptsas_t *mpt, mptsas_pt_request_t *pt)
11292 {
11293 #ifndef __lock_lint
11294         _NOTE(ARGUNUSED(mpt))
11295 #endif
11296         pt->sgl_offset = offsetof(MPI2_SMP_PASSTHROUGH_REQUEST, SGL);
11297         if (pt->request_size != pt->sgl_offset)
11298                 NDBG15(("mpi_pre_smp_passthrough(): Incorrect req size, "
11299                     "0x%x, should be 0x%x, dataoutsz 0x%x",
11300                     pt->request_size, pt->sgl_offset,
11301                     pt->dataout_size));
11302         if (pt->data_size != sizeof (MPI2_SMP_PASSTHROUGH_REPLY))
11303                 NDBG15(("mpi_pre_smp_passthrough(): Incorrect rep size, "
11304                     "0x%x, should be 0x%x", pt->data_size,
11305                     (int)sizeof (MPI2_SMP_PASSTHROUGH_REPLY)));
11306 }
11307 
11308 /*
11309  * Prepare pt for a CONFIG request.
11310  */
11311 static void
11312 mpi_pre_config(mptsas_t *mpt, mptsas_pt_request_t *pt)
11313 {
11314 #ifndef __lock_lint
11315         _NOTE(ARGUNUSED(mpt))
11316 #endif
11317         pt->sgl_offset = offsetof(MPI2_CONFIG_REQUEST, PageBufferSGE);
11318         if (pt->request_size != pt->sgl_offset)
11319                 NDBG15(("mpi_pre_config(): Incorrect req size, 0x%x, "
11320                     "should be 0x%x, dataoutsz 0x%x", pt->request_size,
11321                     pt->sgl_offset, pt->dataout_size));
11322         if (pt->data_size != sizeof (MPI2_CONFIG_REPLY))
11323                 NDBG15(("mpi_pre_config(): Incorrect rep size, 0x%x, "
11324                     "should be 0x%x", pt->data_size,
11325                     (int)sizeof (MPI2_CONFIG_REPLY)));
11326         pt->simple = 1;
11327 }
11328 
11329 /*
11330  * Prepare pt for a SCSI_IO_REQ request.
11331  */
11332 static void
11333 mpi_pre_scsi_io_req(mptsas_t *mpt, mptsas_pt_request_t *pt)
11334 {
11335 #ifndef __lock_lint
11336         _NOTE(ARGUNUSED(mpt))
11337 #endif
11338         pt->sgl_offset = offsetof(MPI2_SCSI_IO_REQUEST, SGL);
11339         if (pt->request_size != pt->sgl_offset)
11340                 NDBG15(("mpi_pre_config(): Incorrect req size, 0x%x, "
11341                     "should be 0x%x, dataoutsz 0x%x", pt->request_size,
11342                     pt->sgl_offset,
11343                     pt->dataout_size));
11344         if (pt->data_size != sizeof (MPI2_SCSI_IO_REPLY))
11345                 NDBG15(("mpi_pre_config(): Incorrect rep size, 0x%x, "
11346                     "should be 0x%x", pt->data_size,
11347                     (int)sizeof (MPI2_SCSI_IO_REPLY)));
11348 }
11349 
11350 /*
11351  * Prepare the mps_command for a SAS_IO_UNIT_CONTROL request.
11352  */
11353 static void
11354 mpi_pre_sas_io_unit_control(mptsas_t *mpt, mptsas_pt_request_t *pt)
11355 {
11356 #ifndef __lock_lint
11357         _NOTE(ARGUNUSED(mpt))
11358 #endif
11359         pt->sgl_offset = (uint16_t)pt->request_size;
11360 }
11361 
11362 /*
11363  * A set of functions to prepare an mps_command for the various
11364  * supported requests.
11365  */
11366 struct mps_func {
11367         U8              Function;
11368         char            *Name;
11369         mps_pre_f       *f_pre;
11370 } mps_func_list[] = {
11371         { MPI2_FUNCTION_IOC_FACTS, "IOC_FACTS",         mpi_pre_ioc_facts },
11372         { MPI2_FUNCTION_PORT_FACTS, "PORT_FACTS",       mpi_pre_port_facts },
11373         { MPI2_FUNCTION_FW_DOWNLOAD, "FW_DOWNLOAD",     mpi_pre_fw_download },
11374         { MPI2_FUNCTION_FW_UPLOAD, "FW_UPLOAD",         mpi_pre_fw_upload },
11375         { MPI2_FUNCTION_SATA_PASSTHROUGH, "SATA_PASSTHROUGH",
11376             mpi_pre_sata_passthrough },
11377         { MPI2_FUNCTION_SMP_PASSTHROUGH, "SMP_PASSTHROUGH",
11378             mpi_pre_smp_passthrough},
11379         { MPI2_FUNCTION_SCSI_IO_REQUEST, "SCSI_IO_REQUEST",
11380             mpi_pre_scsi_io_req},
11381         { MPI2_FUNCTION_CONFIG, "CONFIG",               mpi_pre_config},
11382         { MPI2_FUNCTION_SAS_IO_UNIT_CONTROL, "SAS_IO_UNIT_CONTROL",
11383             mpi_pre_sas_io_unit_control },
11384         { 0xFF, NULL,                           NULL } /* list end */
11385 };
11386 
11387 static void
11388 mptsas_prep_sgl_offset(mptsas_t *mpt, mptsas_pt_request_t *pt)
11389 {
11390         pMPI2RequestHeader_t    hdr;
11391         struct mps_func         *f;
11392 
11393         hdr = (pMPI2RequestHeader_t)pt->request;
11394 
11395         for (f = mps_func_list; f->f_pre != NULL; f++) {
11396                 if (hdr->Function == f->Function) {
11397                         f->f_pre(mpt, pt);
11398                         NDBG15(("mptsas_prep_sgl_offset: Function %s,"
11399                             " sgl_offset 0x%x", f->Name,
11400                             pt->sgl_offset));
11401                         return;
11402                 }
11403         }
11404         NDBG15(("mptsas_prep_sgl_offset: Unknown Function 0x%02x,"
11405             " returning req_size 0x%x for sgl_offset",
11406             hdr->Function, pt->request_size));
11407         pt->sgl_offset = (uint16_t)pt->request_size;
11408 }
11409 
11410 
11411 static int
11412 mptsas_do_passthru(mptsas_t *mpt, uint8_t *request, uint8_t *reply,
11413     uint8_t *data, uint32_t request_size, uint32_t reply_size,
11414     uint32_t data_size, uint8_t direction, uint8_t *dataout,
11415     uint32_t dataout_size, short timeout, int mode)
11416 {
11417         mptsas_pt_request_t             pt;
11418         mptsas_dma_alloc_state_t        data_dma_state;
11419         mptsas_dma_alloc_state_t        dataout_dma_state;
11420         caddr_t                         memp;
11421         mptsas_cmd_t                    *cmd = NULL;
11422         struct scsi_pkt                 *pkt;
11423         uint32_t                        reply_len = 0, sense_len = 0;
11424         pMPI2RequestHeader_t            request_hdrp;
11425         pMPI2RequestHeader_t            request_msg;
11426         pMPI2DefaultReply_t             reply_msg;
11427         Mpi2SCSIIOReply_t               rep_msg;
11428         int                             i, status = 0, pt_flags = 0, rv = 0;
11429         int                             rvalue;
11430         uint8_t                         function;
11431 
11432         ASSERT(mutex_owned(&mpt->m_mutex));
11433 
11434         reply_msg = (pMPI2DefaultReply_t)(&rep_msg);


11471                         mptsas_log(mpt, CE_WARN, "failed to alloc DMA "
11472                             "resource");
11473                         goto out;
11474                 }
11475                 pt_flags |= MPTSAS_DATA_ALLOCATED;
11476                 if (direction == MPTSAS_PASS_THRU_DIRECTION_WRITE) {
11477                         mutex_exit(&mpt->m_mutex);
11478                         for (i = 0; i < data_size; i++) {
11479                                 if (ddi_copyin(data + i, (uint8_t *)
11480                                     data_dma_state.memp + i, 1, mode)) {
11481                                         mutex_enter(&mpt->m_mutex);
11482                                         status = EFAULT;
11483                                         mptsas_log(mpt, CE_WARN, "failed to "
11484                                             "copy read data");
11485                                         goto out;
11486                                 }
11487                         }
11488                         mutex_enter(&mpt->m_mutex);
11489                 }
11490         }
11491         else
11492                 bzero(&data_dma_state, sizeof (data_dma_state));
11493 
11494         if (dataout_size != 0) {
11495                 dataout_dma_state.size = dataout_size;
11496                 if (mptsas_dma_alloc(mpt, &dataout_dma_state) != DDI_SUCCESS) {
11497                         status = ENOMEM;
11498                         mptsas_log(mpt, CE_WARN, "failed to alloc DMA "
11499                             "resource");
11500                         goto out;
11501                 }
11502                 pt_flags |= MPTSAS_DATAOUT_ALLOCATED;
11503                 mutex_exit(&mpt->m_mutex);
11504                 for (i = 0; i < dataout_size; i++) {
11505                         if (ddi_copyin(dataout + i, (uint8_t *)
11506                             dataout_dma_state.memp + i, 1, mode)) {
11507                                 mutex_enter(&mpt->m_mutex);
11508                                 mptsas_log(mpt, CE_WARN, "failed to copy out"
11509                                     " data");
11510                                 status = EFAULT;
11511                                 goto out;
11512                         }
11513                 }
11514                 mutex_enter(&mpt->m_mutex);
11515         }
11516         else
11517                 bzero(&dataout_dma_state, sizeof (dataout_dma_state));
11518 
11519         if ((rvalue = (mptsas_request_from_pool(mpt, &cmd, &pkt))) == -1) {
11520                 status = EAGAIN;
11521                 mptsas_log(mpt, CE_NOTE, "event ack command pool is full");
11522                 goto out;
11523         }
11524         pt_flags |= MPTSAS_REQUEST_POOL_CMD;
11525 
11526         bzero((caddr_t)cmd, sizeof (*cmd));
11527         bzero((caddr_t)pkt, scsi_pkt_size());
11528         bzero((caddr_t)&pt, sizeof (pt));
11529 
11530         cmd->ioc_cmd_slot = (uint32_t)(rvalue);
11531 
11532         pt.request = (uint8_t *)request_msg;
11533         pt.direction = direction;
11534         pt.simple = 0;
11535         pt.request_size = request_size;
11536         pt.data_size = data_size;
11537         pt.dataout_size = dataout_size;
11538         pt.data_cookie = data_dma_state.cookie;
11539         pt.dataout_cookie = dataout_dma_state.cookie;
11540         mptsas_prep_sgl_offset(mpt, &pt);
11541 
11542         /*
11543          * Form a blank cmd/pkt to store the acknowledgement message
11544          */
11545         pkt->pkt_cdbp                = (opaque_t)&cmd->cmd_cdb[0];
11546         pkt->pkt_scbp                = (opaque_t)&cmd->cmd_scb;
11547         pkt->pkt_ha_private  = (opaque_t)&pt;
11548         pkt->pkt_flags               = FLAG_HEAD;
11549         pkt->pkt_time                = timeout;
11550         cmd->cmd_pkt         = pkt;
11551         cmd->cmd_flags               = CFLAG_CMDIOC | CFLAG_PASSTHRU;
11552 
11553         /*
11554          * Save the command in a slot
11555          */
11556         if (mptsas_save_cmd(mpt, cmd) == TRUE) {
11557                 /*
11558                  * Once passthru command get slot, set cmd_flags
11559                  * CFLAG_PREPARED.
11560                  */


11577         if (cmd->cmd_flags & CFLAG_TIMEOUT) {
11578                 status = ETIMEDOUT;
11579                 mptsas_log(mpt, CE_WARN, "passthrough command timeout");
11580                 pt_flags |= MPTSAS_CMD_TIMEOUT;
11581                 goto out;
11582         }
11583 
11584         if (cmd->cmd_rfm) {
11585                 /*
11586                  * cmd_rfm is zero means the command reply is a CONTEXT
11587                  * reply and no PCI Write to post the free reply SMFA
11588                  * because no reply message frame is used.
11589                  * cmd_rfm is non-zero means the reply is a ADDRESS
11590                  * reply and reply message frame is used.
11591                  */
11592                 pt_flags |= MPTSAS_ADDRESS_REPLY;
11593                 (void) ddi_dma_sync(mpt->m_dma_reply_frame_hdl, 0, 0,
11594                     DDI_DMA_SYNC_FORCPU);
11595                 reply_msg = (pMPI2DefaultReply_t)
11596                     (mpt->m_reply_frame + (cmd->cmd_rfm -
11597                     (mpt->m_reply_frame_dma_addr&0xfffffffful)));
11598         }
11599 
11600         mptsas_fma_check(mpt, cmd);
11601         if (pkt->pkt_reason == CMD_TRAN_ERR) {
11602                 status = EAGAIN;
11603                 mptsas_log(mpt, CE_WARN, "passthru fma error");
11604                 goto out;
11605         }
11606         if (pkt->pkt_reason == CMD_RESET) {
11607                 status = EAGAIN;
11608                 mptsas_log(mpt, CE_WARN, "ioc reset abort passthru");
11609                 goto out;
11610         }
11611 
11612         if (pkt->pkt_reason == CMD_INCOMPLETE) {
11613                 status = EIO;
11614                 mptsas_log(mpt, CE_WARN, "passthrough command incomplete");
11615                 goto out;
11616         }
11617 


11733         if (((data->DataSize == 0) &&
11734             (data->DataDirection == MPTSAS_PASS_THRU_DIRECTION_NONE)) ||
11735             ((data->DataSize != 0) &&
11736             ((data->DataDirection == MPTSAS_PASS_THRU_DIRECTION_READ) ||
11737             (data->DataDirection == MPTSAS_PASS_THRU_DIRECTION_WRITE) ||
11738             ((data->DataDirection == MPTSAS_PASS_THRU_DIRECTION_BOTH) &&
11739             (data->DataOutSize != 0))))) {
11740                 if (data->DataDirection == MPTSAS_PASS_THRU_DIRECTION_BOTH) {
11741                         data->DataDirection = MPTSAS_PASS_THRU_DIRECTION_READ;
11742                 } else {
11743                         data->DataOutSize = 0;
11744                 }
11745                 /*
11746                  * Send passthru request messages
11747                  */
11748                 return (mptsas_do_passthru(mpt,
11749                     (uint8_t *)((uintptr_t)data->PtrRequest),
11750                     (uint8_t *)((uintptr_t)data->PtrReply),
11751                     (uint8_t *)((uintptr_t)data->PtrData),
11752                     data->RequestSize, data->ReplySize,
11753                     data->DataSize, (uint8_t)data->DataDirection,
11754                     (uint8_t *)((uintptr_t)data->PtrDataOut),
11755                     data->DataOutSize, data->Timeout, mode));
11756         } else {
11757                 return (EINVAL);
11758         }
11759 }
11760 
11761 static uint8_t
11762 mptsas_get_fw_diag_buffer_number(mptsas_t *mpt, uint32_t unique_id)
11763 {
11764         uint8_t index;
11765 
11766         for (index = 0; index < MPI2_DIAG_BUF_TYPE_COUNT; index++) {
11767                 if (mpt->m_fw_diag_buffer_list[index].unique_id == unique_id) {
11768                         return (index);
11769                 }
11770         }
11771 
11772         return (MPTSAS_FW_DIAGNOSTIC_UID_NOT_FOUND);
11773 }
11774 
11775 static void
11776 mptsas_start_diag(mptsas_t *mpt, mptsas_cmd_t *cmd)
11777 {
11778         pMpi2DiagBufferPostRequest_t    pDiag_post_msg;
11779         pMpi2DiagReleaseRequest_t       pDiag_release_msg;
11780         struct scsi_pkt                 *pkt = cmd->cmd_pkt;
11781         mptsas_diag_request_t           *diag = pkt->pkt_ha_private;
11782         uint32_t                        i;
11783         uint64_t                        request_desc;
11784 
11785         ASSERT(mutex_owned(&mpt->m_mutex));
11786 
11787         /*
11788          * Form the diag message depending on the post or release function.
11789          */
11790         if (diag->function == MPI2_FUNCTION_DIAG_BUFFER_POST) {
11791                 pDiag_post_msg = (pMpi2DiagBufferPostRequest_t)
11792                     (mpt->m_req_frame + (mpt->m_req_frame_size *
11793                     cmd->cmd_slot));
11794                 bzero(pDiag_post_msg, mpt->m_req_frame_size);
11795                 ddi_put8(mpt->m_acc_req_frame_hdl, &pDiag_post_msg->Function,
11796                     diag->function);
11797                 ddi_put8(mpt->m_acc_req_frame_hdl, &pDiag_post_msg->BufferType,
11798                     diag->pBuffer->buffer_type);
11799                 ddi_put8(mpt->m_acc_req_frame_hdl,
11800                     &pDiag_post_msg->ExtendedType,
11801                     diag->pBuffer->extended_type);
11802                 ddi_put32(mpt->m_acc_req_frame_hdl,
11803                     &pDiag_post_msg->BufferLength,


11816                     &pDiag_post_msg->BufferAddress.High,
11817                     (uint32_t)(diag->pBuffer->buffer_data.cookie.dmac_laddress
11818                     >> 32));
11819         } else {
11820                 pDiag_release_msg = (pMpi2DiagReleaseRequest_t)
11821                     (mpt->m_req_frame + (mpt->m_req_frame_size *
11822                     cmd->cmd_slot));
11823                 bzero(pDiag_release_msg, mpt->m_req_frame_size);
11824                 ddi_put8(mpt->m_acc_req_frame_hdl,
11825                     &pDiag_release_msg->Function, diag->function);
11826                 ddi_put8(mpt->m_acc_req_frame_hdl,
11827                     &pDiag_release_msg->BufferType,
11828                     diag->pBuffer->buffer_type);
11829         }
11830 
11831         /*
11832          * Send the message
11833          */
11834         (void) ddi_dma_sync(mpt->m_dma_req_frame_hdl, 0, 0,
11835             DDI_DMA_SYNC_FORDEV);
11836         request_desc = (cmd->cmd_slot << 16) |
11837             MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE;
11838         cmd->cmd_rfm = NULL;
11839         MPTSAS_START_CMD(mpt, request_desc);
11840         if ((mptsas_check_dma_handle(mpt->m_dma_req_frame_hdl) !=
11841             DDI_SUCCESS) ||
11842             (mptsas_check_acc_handle(mpt->m_acc_req_frame_hdl) !=
11843             DDI_SUCCESS)) {
11844                 ddi_fm_service_impact(mpt->m_dip, DDI_SERVICE_UNAFFECTED);
11845         }
11846 }
11847 
11848 static int
11849 mptsas_post_fw_diag_buffer(mptsas_t *mpt,
11850     mptsas_fw_diagnostic_buffer_t *pBuffer, uint32_t *return_code)
11851 {
11852         mptsas_diag_request_t           diag;
11853         int                             status, slot_num, post_flags = 0;
11854         mptsas_cmd_t                    *cmd = NULL;
11855         struct scsi_pkt                 *pkt;
11856         pMpi2DiagBufferPostReply_t      reply;
11857         uint16_t                        iocstatus;
11858         uint32_t                        iocloginfo, transfer_length;
11859 


11917         while ((cmd->cmd_flags & CFLAG_FINISHED) == 0) {
11918                 cv_wait(&mpt->m_fw_diag_cv, &mpt->m_mutex);
11919         }
11920 
11921         if (cmd->cmd_flags & CFLAG_TIMEOUT) {
11922                 status = DDI_FAILURE;
11923                 mptsas_log(mpt, CE_WARN, "Post FW Diag command timeout");
11924                 goto out;
11925         }
11926 
11927         /*
11928          * cmd_rfm points to the reply message if a reply was given.  Check the
11929          * IOCStatus to make sure everything went OK with the FW diag request
11930          * and set buffer flags.
11931          */
11932         if (cmd->cmd_rfm) {
11933                 post_flags |= MPTSAS_ADDRESS_REPLY;
11934                 (void) ddi_dma_sync(mpt->m_dma_reply_frame_hdl, 0, 0,
11935                     DDI_DMA_SYNC_FORCPU);
11936                 reply = (pMpi2DiagBufferPostReply_t)(mpt->m_reply_frame +
11937                     (cmd->cmd_rfm -
11938                     (mpt->m_reply_frame_dma_addr&0xfffffffful)));
11939 
11940                 /*
11941                  * Get the reply message data
11942                  */
11943                 iocstatus = ddi_get16(mpt->m_acc_reply_frame_hdl,
11944                     &reply->IOCStatus);
11945                 iocloginfo = ddi_get32(mpt->m_acc_reply_frame_hdl,
11946                     &reply->IOCLogInfo);
11947                 transfer_length = ddi_get32(mpt->m_acc_reply_frame_hdl,
11948                     &reply->TransferLength);
11949 
11950                 /*
11951                  * If post failed quit.
11952                  */
11953                 if (iocstatus != MPI2_IOCSTATUS_SUCCESS) {
11954                         status = DDI_FAILURE;
11955                         NDBG13(("post FW Diag Buffer failed: IOCStatus=0x%x, "
11956                             "IOCLogInfo=0x%x, TransferLength=0x%x", iocstatus,
11957                             iocloginfo, transfer_length));
11958                         goto out;


12072         while ((cmd->cmd_flags & CFLAG_FINISHED) == 0) {
12073                 cv_wait(&mpt->m_fw_diag_cv, &mpt->m_mutex);
12074         }
12075 
12076         if (cmd->cmd_flags & CFLAG_TIMEOUT) {
12077                 status = DDI_FAILURE;
12078                 mptsas_log(mpt, CE_WARN, "Release FW Diag command timeout");
12079                 goto out;
12080         }
12081 
12082         /*
12083          * cmd_rfm points to the reply message if a reply was given.  Check the
12084          * IOCStatus to make sure everything went OK with the FW diag request
12085          * and set buffer flags.
12086          */
12087         if (cmd->cmd_rfm) {
12088                 rel_flags |= MPTSAS_ADDRESS_REPLY;
12089                 (void) ddi_dma_sync(mpt->m_dma_reply_frame_hdl, 0, 0,
12090                     DDI_DMA_SYNC_FORCPU);
12091                 reply = (pMpi2DiagReleaseReply_t)(mpt->m_reply_frame +
12092                     (cmd->cmd_rfm -
12093                     (mpt->m_reply_frame_dma_addr&0xfffffffful)));
12094 
12095                 /*
12096                  * Get the reply message data
12097                  */
12098                 iocstatus = ddi_get16(mpt->m_acc_reply_frame_hdl,
12099                     &reply->IOCStatus);
12100                 iocloginfo = ddi_get32(mpt->m_acc_reply_frame_hdl,
12101                     &reply->IOCLogInfo);
12102 
12103                 /*
12104                  * If release failed quit.
12105                  */
12106                 if ((iocstatus != MPI2_IOCSTATUS_SUCCESS) ||
12107                     pBuffer->owned_by_firmware) {
12108                         status = DDI_FAILURE;
12109                         NDBG13(("release FW Diag Buffer failed: "
12110                             "IOCStatus=0x%x, IOCLogInfo=0x%x", iocstatus,
12111                             iocloginfo));
12112                         goto out;
12113                 }


12821                  * If we can't determine the PCI data then we fill in FF's for
12822                  * the data to indicate this.
12823                  */
12824                 adapter_data->PCIDeviceHwId = 0xFFFFFFFF;
12825                 adapter_data->MpiPortNumber = 0xFFFFFFFF;
12826                 adapter_data->PciInformation.u.AsDWORD = 0xFFFFFFFF;
12827         }
12828 
12829         /*
12830          * Saved in the mpt->m_fwversion
12831          */
12832         adapter_data->MpiFirmwareVersion = mpt->m_fwversion;
12833 }
12834 
12835 static void
12836 mptsas_read_adapter_data(mptsas_t *mpt, mptsas_adapter_data_t *adapter_data)
12837 {
12838         char    *driver_verstr = MPTSAS_MOD_STRING;
12839 
12840         mptsas_lookup_pci_data(mpt, adapter_data);
12841         adapter_data->AdapterType = MPTIOCTL_ADAPTER_TYPE_SAS3;
12842         adapter_data->PCIDeviceHwId = (uint32_t)mpt->m_devid;
12843         adapter_data->PCIDeviceHwRev = (uint32_t)mpt->m_revid;
12844         adapter_data->SubSystemId = (uint32_t)mpt->m_ssid;
12845         adapter_data->SubsystemVendorId = (uint32_t)mpt->m_svid;
12846         (void) strcpy((char *)&adapter_data->DriverVersion[0], driver_verstr);
12847         adapter_data->BiosVersion = 0;
12848         (void) mptsas_get_bios_page3(mpt, &adapter_data->BiosVersion);
12849 }
12850 
12851 static void
12852 mptsas_read_pci_info(mptsas_t *mpt, mptsas_pci_info_t *pci_info)
12853 {
12854         int     *reg_data, i;
12855         uint_t  reglen;
12856 
12857         /*
12858          * Lookup the 'reg' property and extract the other data
12859          */
12860         if (ddi_prop_lookup_int_array(DDI_DEV_T_ANY, mpt->m_dip,
12861             DDI_PROP_DONTPASS, "reg", &reg_data, &reglen) ==


13095         int                     status = 0;
13096         mptsas_t                *mpt;
13097         mptsas_update_flash_t   flashdata;
13098         mptsas_pass_thru_t      passthru_data;
13099         mptsas_adapter_data_t   adapter_data;
13100         mptsas_pci_info_t       pci_info;
13101         int                     copylen;
13102 
13103         int                     iport_flag = 0;
13104         dev_info_t              *dip = NULL;
13105         mptsas_phymask_t        phymask = 0;
13106         struct devctl_iocdata   *dcp = NULL;
13107         char                    *addr = NULL;
13108         mptsas_target_t         *ptgt = NULL;
13109 
13110         *rval = MPTIOCTL_STATUS_GOOD;
13111         if (secpolicy_sys_config(credp, B_FALSE) != 0) {
13112                 return (EPERM);
13113         }
13114 
13115         mpt = ddi_get_soft_state(mptsas3_state, MINOR2INST(getminor(dev)));
13116         if (mpt == NULL) {
13117                 /*
13118                  * Called from iport node, get the states
13119                  */
13120                 iport_flag = 1;
13121                 dip = mptsas_get_dip_from_dev(dev, &phymask);
13122                 if (dip == NULL) {
13123                         return (ENXIO);
13124                 }
13125                 mpt = DIP2MPT(dip);
13126         }
13127         /* Make sure power level is D0 before accessing registers */
13128         mutex_enter(&mpt->m_mutex);
13129         if (mpt->m_options & MPTSAS_OPT_PM) {
13130                 (void) pm_busy_component(mpt->m_dip, 0);
13131                 if (mpt->m_power_level != PM_LEVEL_D0) {
13132                         mutex_exit(&mpt->m_mutex);
13133                         if (pm_raise_power(mpt->m_dip, 0, PM_LEVEL_D0) !=
13134                             DDI_SUCCESS) {
13135                                 mptsas_log(mpt, CE_WARN,
13136                                     "mptsas3%d: mptsas_ioctl: Raise power "
13137                                     "request failed.", mpt->m_instance);
13138                                 (void) pm_idle_component(mpt->m_dip, 0);
13139                                 return (ENXIO);
13140                         }
13141                 } else {
13142                         mutex_exit(&mpt->m_mutex);
13143                 }
13144         } else {
13145                 mutex_exit(&mpt->m_mutex);
13146         }
13147 
13148         if (iport_flag) {
13149                 status = scsi_hba_ioctl(dev, cmd, data, mode, credp, rval);
13150                 if (status != 0) {
13151                         goto out;
13152                 }
13153                 /*
13154                  * The following code control the OK2RM LED, it doesn't affect
13155                  * the ioctl return status.
13156                  */


13356 {
13357         int             rval = DDI_SUCCESS;
13358         mptsas_target_t *ptgt = NULL;
13359 
13360         ASSERT(mutex_owned(&mpt->m_mutex));
13361 
13362         /*
13363          * Set a flag telling I/O path that we're processing a reset.  This is
13364          * needed because after the reset is complete, the hash table still
13365          * needs to be rebuilt.  If I/Os are started before the hash table is
13366          * rebuilt, I/O errors will occur.  This flag allows I/Os to be marked
13367          * so that they can be retried.
13368          */
13369         mpt->m_in_reset = TRUE;
13370 
13371         /*
13372          * Set all throttles to HOLD
13373          */
13374         for (ptgt = refhash_first(mpt->m_targets); ptgt != NULL;
13375             ptgt = refhash_next(mpt->m_targets, ptgt)) {
13376                 mptsas_set_throttle_mtx(mpt, ptgt, HOLD_THROTTLE);
13377         }
13378 
13379         /*
13380          * Disable interrupts
13381          */
13382         MPTSAS_DISABLE_INTR(mpt);
13383 
13384         /*
13385          * Abort all commands: outstanding commands, commands in waitq and
13386          * tx_waitq.
13387          */
13388         mptsas_flush_hba(mpt);
13389 
13390         /*
13391          * Reinitialize the chip.
13392          */
13393         if (mptsas_init_chip(mpt, FALSE) == DDI_FAILURE) {
13394                 rval = DDI_FAILURE;
13395         }
13396 
13397         /*
13398          * Enable interrupts again
13399          */
13400         MPTSAS_ENABLE_INTR(mpt);
13401 
13402         /*
13403          * If mptsas_init_chip was successful, update the driver data.
13404          */
13405         if (rval == DDI_SUCCESS) {
13406                 mptsas_update_driver_data(mpt);
13407         }
13408 
13409         /*
13410          * Reset the throttles
13411          */
13412         for (ptgt = refhash_first(mpt->m_targets); ptgt != NULL;
13413             ptgt = refhash_next(mpt->m_targets, ptgt)) {
13414                 mptsas_set_throttle_mtx(mpt, ptgt, MAX_THROTTLE);
13415         }
13416 
13417         mptsas_doneq_empty(mpt);
13418         mptsas_restart_hba(mpt);
13419 
13420         if (rval != DDI_SUCCESS) {
13421                 mptsas_fm_ereport(mpt, DDI_FM_DEVICE_NO_RESPONSE);
13422                 ddi_fm_service_impact(mpt->m_dip, DDI_SERVICE_LOST);
13423         }
13424 
13425         /*
13426          * Clear the reset flag so that I/Os can continue.
13427          */
13428         mpt->m_in_reset = FALSE;
13429 
13430         return (rval);
13431 }
13432 
13433 static int
13434 mptsas_init_chip(mptsas_t *mpt, int first_time)
13435 {
13436         ddi_dma_cookie_t        cookie;
13437         mptsas_reply_pqueue_t   *rpqp;
13438         uint32_t                i, j;
13439         int                     rval;
13440 
13441         /*
13442          * Check to see if the firmware image is valid
13443          */
13444         if (ddi_get32(mpt->m_datap, &mpt->m_reg->HostDiagnostic) &
13445             MPI2_DIAG_FLASH_BAD_SIG) {
13446                 mptsas_log(mpt, CE_WARN, "mptsas bad flash signature!");
13447                 goto fail;
13448         }
13449 
13450         /*
13451          * Reset the chip
13452          */
13453         rval = mptsas_ioc_reset(mpt, first_time);
13454         if (rval == MPTSAS_RESET_FAIL) {
13455                 mptsas_log(mpt, CE_WARN, "hard reset failed!");
13456                 goto fail;
13457         }
13458 


13461         }
13462         /*
13463          * Setup configuration space
13464          */
13465         if (mptsas_config_space_init(mpt) == FALSE) {
13466                 mptsas_log(mpt, CE_WARN, "mptsas_config_space_init "
13467                     "failed!");
13468                 goto fail;
13469         }
13470 
13471         /*
13472          * IOC facts can change after a diag reset so all buffers that are
13473          * based on these numbers must be de-allocated and re-allocated.  Get
13474          * new IOC facts each time chip is initialized.
13475          */
13476         if (mptsas_ioc_get_facts(mpt) == DDI_FAILURE) {
13477                 mptsas_log(mpt, CE_WARN, "mptsas_ioc_get_facts failed");
13478                 goto fail;
13479         }
13480 
13481         /*
13482          * Now we know chip MSIX capabilitites and it's not been done
13483          * previously register interrupts accordingly. Need to know this
13484          * information before allocating the reply frames below.
13485          */
13486         if (mpt->m_intr_cnt == 0) {
13487                 if (mptsas_register_intrs(mpt) == FALSE)
13488                         goto fail;
13489         }
13490 
13491         mpt->m_targets = refhash_create(MPTSAS_TARGET_BUCKET_COUNT,
13492             mptsas_target_addr_hash, mptsas_target_addr_cmp,
13493             mptsas_target_free, sizeof (mptsas_target_t),
13494             offsetof(mptsas_target_t, m_link),
13495             offsetof(mptsas_target_t, m_addr), KM_SLEEP);
13496 
13497         if (mptsas_alloc_active_slots(mpt, KM_SLEEP)) {
13498                 goto fail;
13499         }
13500         /*
13501          * Allocate request message frames, reply free queue, reply descriptor
13502          * post queue, and reply message frames using latest IOC facts.
13503          */
13504         if (mptsas_alloc_request_frames(mpt) == DDI_FAILURE) {
13505                 mptsas_log(mpt, CE_WARN, "mptsas_alloc_request_frames failed");
13506                 goto fail;
13507         }
13508         if (mptsas_alloc_sense_bufs(mpt) == DDI_FAILURE) {
13509                 mptsas_log(mpt, CE_WARN, "mptsas_alloc_sense_bufs failed");
13510                 goto fail;
13511         }
13512         if (mptsas_alloc_free_queue(mpt) == DDI_FAILURE) {
13513                 mptsas_log(mpt, CE_WARN, "mptsas_alloc_free_queue failed!");
13514                 goto fail;
13515         }
13516         if (mptsas_alloc_post_queue(mpt) == DDI_FAILURE) {
13517                 mptsas_log(mpt, CE_WARN, "mptsas_alloc_post_queue failed!");
13518                 goto fail;
13519         }
13520         if (mptsas_alloc_reply_frames(mpt) == DDI_FAILURE) {
13521                 mptsas_log(mpt, CE_WARN, "mptsas_alloc_reply_frames failed!");
13522                 goto fail;
13523         }
13524 
13525 mur:
13526         /*
13527          * Re-Initialize ioc to operational state
13528          */
13529         if (mptsas_ioc_init(mpt) == DDI_FAILURE) {
13530                 mptsas_log(mpt, CE_WARN, "mptsas_ioc_init failed");
13531                 goto fail;
13532         }
13533 
13534         mptsas_alloc_reply_args(mpt);
13535 
13536         /*






13537          * Initialize the Reply Free Queue with the physical addresses of our
13538          * reply frames.
13539          */
13540         cookie.dmac_address = mpt->m_reply_frame_dma_addr&0xfffffffful;
13541         for (i = 0; i < mpt->m_max_replies; i++) {
13542                 ddi_put32(mpt->m_acc_free_queue_hdl,
13543                     &((uint32_t *)(void *)mpt->m_free_queue)[i],
13544                     cookie.dmac_address);
13545                 cookie.dmac_address += mpt->m_reply_frame_size;
13546         }
13547         (void) ddi_dma_sync(mpt->m_dma_free_queue_hdl, 0, 0,
13548             DDI_DMA_SYNC_FORDEV);
13549 
13550         /*
13551          * Initialize the reply free index to one past the last frame on the
13552          * queue.  This will signify that the queue is empty to start with.
13553          */
13554         mpt->m_free_index = i;
13555         ddi_put32(mpt->m_datap, &mpt->m_reg->ReplyFreeHostIndex, i);
13556 
13557         /*
13558          * Initialize the reply post queue to 0xFFFFFFFF,0xFFFFFFFF's
13559          * and the indexes to 0.
13560          */
13561         rpqp = mpt->m_rep_post_queues;
13562         for (j = 0; j < mpt->m_post_reply_qcount; j++) {
13563                 for (i = 0; i < mpt->m_post_queue_depth; i++) {
13564                         ddi_put64(mpt->m_acc_post_queue_hdl,
13565                             &((uint64_t *)(void *)rpqp->rpq_queue)[i],
13566                             0xFFFFFFFFFFFFFFFF);
13567                 }
13568                 rpqp->rpq_index = 0;
13569                 rpqp++;
13570         }
13571         (void) ddi_dma_sync(mpt->m_dma_post_queue_hdl, 0, 0,
13572             DDI_DMA_SYNC_FORDEV);
13573 
13574         /*
13575          * Initialise all the reply post queue indexes.
13576          */
13577         for (j = 0; j < mpt->m_post_reply_qcount; j++) {
13578                 ddi_put32(mpt->m_datap, &mpt->m_reg->ReplyPostHostIndex,
13579                     j << MPI2_RPHI_MSIX_INDEX_SHIFT);
13580         }
13581 
13582         /*
13583          * Enable ports
13584          */
13585         if (mptsas_ioc_enable_port(mpt) == DDI_FAILURE) {
13586                 mptsas_log(mpt, CE_WARN, "mptsas_ioc_enable_port failed");
13587                 goto fail;
13588         }
13589 
13590         /*
13591          * enable events
13592          */
13593         if (mptsas_ioc_enable_event_notification(mpt)) {
13594                 mptsas_log(mpt, CE_WARN,
13595                     "mptsas_ioc_enable_event_notification failed");
13596                 goto fail;
13597         }
13598 
13599         /*
13600          * We need checks in attach and these.
13601          * chip_init is called in mult. places
13602          */
13603 
13604         if ((mptsas_check_dma_handle(mpt->m_dma_req_frame_hdl) !=
13605             DDI_SUCCESS) ||
13606             (mptsas_check_dma_handle(mpt->m_dma_req_sense_hdl) !=
13607             DDI_SUCCESS) ||
13608             (mptsas_check_dma_handle(mpt->m_dma_reply_frame_hdl) !=
13609             DDI_SUCCESS) ||
13610             (mptsas_check_dma_handle(mpt->m_dma_free_queue_hdl) !=
13611             DDI_SUCCESS) ||
13612             (mptsas_check_dma_handle(mpt->m_dma_post_queue_hdl) !=
13613             DDI_SUCCESS) ||
13614             (mptsas_check_dma_handle(mpt->m_hshk_dma_hdl) !=
13615             DDI_SUCCESS)) {
13616                 ddi_fm_service_impact(mpt->m_dip, DDI_SERVICE_UNAFFECTED);
13617                 goto fail;
13618         }
13619 
13620         /* Check all acc handles */
13621         if ((mptsas_check_acc_handle(mpt->m_datap) != DDI_SUCCESS) ||
13622             (mptsas_check_acc_handle(mpt->m_acc_req_frame_hdl) !=
13623             DDI_SUCCESS) ||
13624             (mptsas_check_acc_handle(mpt->m_acc_req_sense_hdl) !=
13625             DDI_SUCCESS) ||
13626             (mptsas_check_acc_handle(mpt->m_acc_reply_frame_hdl) !=
13627             DDI_SUCCESS) ||
13628             (mptsas_check_acc_handle(mpt->m_acc_free_queue_hdl) !=
13629             DDI_SUCCESS) ||
13630             (mptsas_check_acc_handle(mpt->m_acc_post_queue_hdl) !=
13631             DDI_SUCCESS) ||
13632             (mptsas_check_acc_handle(mpt->m_hshk_acc_hdl) !=
13633             DDI_SUCCESS) ||
13634             (mptsas_check_acc_handle(mpt->m_config_handle) !=
13635             DDI_SUCCESS)) {
13636                 ddi_fm_service_impact(mpt->m_dip, DDI_SERVICE_UNAFFECTED);
13637                 goto fail;
13638         }
13639 
13640         return (DDI_SUCCESS);
13641 
13642 fail:
13643         return (DDI_FAILURE);
13644 }
13645 


13674                 if (++cap_count > 48) {
13675                         mptsas_log(mpt, CE_WARN,
13676                             "too many device capabilities.\n");
13677                         break;
13678                 }
13679                 if (caps_ptr < 64) {
13680                         mptsas_log(mpt, CE_WARN,
13681                             "capabilities pointer 0x%x out of range.\n",
13682                             caps_ptr);
13683                         break;
13684                 }
13685 
13686                 /*
13687                  * Get next capability and check that it is valid.
13688                  * For now, we only support power management.
13689                  */
13690                 cap = pci_config_get8(mpt->m_config_handle, caps_ptr);
13691                 switch (cap) {
13692                         case PCI_CAP_ID_PM:
13693                                 mptsas_log(mpt, CE_NOTE,
13694                                     "?mptsas3%d supports power management.\n",
13695                                     mpt->m_instance);
13696                                 mpt->m_options |= MPTSAS_OPT_PM;
13697 
13698                                 /* Save PMCSR offset */
13699                                 mpt->m_pmcsr_offset = caps_ptr + PCI_PMCSR;
13700                                 break;
13701                         case PCI_CAP_ID_MSI:
13702                                 mptsas_log(mpt, CE_NOTE,
13703                                     "?mptsas3%d supports MSI.\n",
13704                                     mpt->m_instance);
13705                                 mpt->m_options |= MPTSAS_OPT_MSI;
13706                                 break;
13707                         case PCI_CAP_ID_MSI_X:
13708                                 mptsas_log(mpt, CE_NOTE,
13709                                     "?mptsas3%d supports MSI-X.\n",
13710                                     mpt->m_instance);
13711                                 mpt->m_options |= MPTSAS_OPT_MSI_X;
13712                                 break;
13713                         /*
13714                          * The following capabilities are valid.  Any others
13715                          * will cause a message to be logged.
13716                          */
13717                         case PCI_CAP_ID_VPD:

13718                         case PCI_CAP_ID_PCIX:
13719                         case PCI_CAP_ID_PCI_E:

13720                                 break;
13721                         default:
13722                                 mptsas_log(mpt, CE_NOTE,
13723                                     "?mptsas3%d unrecognized capability "
13724                                     "0x%x.\n", mpt->m_instance, cap);
13725                                 break;
13726                 }
13727 
13728                 /*
13729                  * Get next capabilities pointer and clear bits 0,1.
13730                  */
13731                 caps_ptr = P2ALIGN(pci_config_get8(mpt->m_config_handle,
13732                     (caps_ptr + PCI_CAP_NEXT_PTR)), 4);
13733         }
13734         return (TRUE);
13735 }
13736 
13737 static int
13738 mptsas_init_pm(mptsas_t *mpt)
13739 {
13740         char            pmc_name[16];
13741         char            *pmc[] = {
13742                                 NULL,
13743                                 "0=Off (PCI D3 State)",
13744                                 "3=On (PCI D0 State)",
13745                                 NULL
13746                         };
13747         uint16_t        pmcsr_stat;
13748 



13749         /*
13750          * If PCI's capability does not support PM, then don't need
13751          * to registe the pm-components
13752          */
13753         if (!(mpt->m_options & MPTSAS_OPT_PM))
13754                 return (DDI_SUCCESS);
13755         /*
13756          * If power management is supported by this chip, create
13757          * pm-components property for the power management framework
13758          */
13759         (void) sprintf(pmc_name, "NAME=mptsas3%d", mpt->m_instance);
13760         pmc[0] = pmc_name;
13761         if (ddi_prop_update_string_array(DDI_DEV_T_NONE, mpt->m_dip,
13762             "pm-components", pmc, 3) != DDI_PROP_SUCCESS) {
13763                 mpt->m_options &= ~MPTSAS_OPT_PM;
13764                 mptsas_log(mpt, CE_WARN,
13765                     "mptsas3%d: pm-component property creation failed.",
13766                     mpt->m_instance);
13767                 return (DDI_FAILURE);
13768         }
13769 
13770         /*
13771          * Power on device.
13772          */
13773         (void) pm_busy_component(mpt->m_dip, 0);
13774         pmcsr_stat = pci_config_get16(mpt->m_config_handle,
13775             mpt->m_pmcsr_offset);
13776         if ((pmcsr_stat & PCI_PMCSR_STATE_MASK) != PCI_PMCSR_D0) {
13777                 mptsas_log(mpt, CE_WARN, "mptsas3%d: Power up the device",
13778                     mpt->m_instance);
13779                 pci_config_put16(mpt->m_config_handle, mpt->m_pmcsr_offset,
13780                     PCI_PMCSR_D0);
13781         }
13782         if (pm_power_has_changed(mpt->m_dip, 0, PM_LEVEL_D0) != DDI_SUCCESS) {
13783                 mptsas_log(mpt, CE_WARN, "pm_power_has_changed failed");
13784                 return (DDI_FAILURE);
13785         }
13786         mpt->m_power_level = PM_LEVEL_D0;
13787         /*
13788          * Set pm idle delay.
13789          */
13790         mpt->m_pm_idle_delay = ddi_prop_get_int(DDI_DEV_T_ANY,
13791             mpt->m_dip, 0, "mptsas-pm-idle-delay", MPTSAS_PM_IDLE_TIMEOUT);
13792 
13793         return (DDI_SUCCESS);
13794 }
13795 
13796 static int
13797 mptsas_register_intrs(mptsas_t *mpt)
13798 {
13799         dev_info_t *dip;
13800         int intr_types;
13801 
13802         dip = mpt->m_dip;
13803 
13804         /* Get supported interrupt types */
13805         if (ddi_intr_get_supported_types(dip, &intr_types) != DDI_SUCCESS) {
13806                 mptsas_log(mpt, CE_WARN, "ddi_intr_get_supported_types "
13807                     "failed\n");
13808                 return (FALSE);
13809         }
13810 
13811         NDBG6(("ddi_intr_get_supported_types() returned: 0x%x", intr_types));
13812 
13813         /*
13814          * Try MSIX first.
13815          */
13816         if (mptsas_enable_msix && (intr_types & DDI_INTR_TYPE_MSIX)) {
13817                 if (mptsas_add_intrs(mpt, DDI_INTR_TYPE_MSIX) == DDI_SUCCESS) {
13818                         NDBG6(("Using MSI-X interrupt type"));
13819                         mpt->m_intr_type = DDI_INTR_TYPE_MSIX;
13820                         return (TRUE);
13821                 }
13822         }
13823 
13824         /*
13825          * Try MSI, but fall back to FIXED
13826          */
13827         if (mptsas_enable_msi && (intr_types & DDI_INTR_TYPE_MSI)) {
13828                 if (mptsas_add_intrs(mpt, DDI_INTR_TYPE_MSI) == DDI_SUCCESS) {
13829                         NDBG6(("Using MSI interrupt type"));
13830                         mpt->m_intr_type = DDI_INTR_TYPE_MSI;
13831                         return (TRUE);
13832                 }
13833         }
13834         if (intr_types & DDI_INTR_TYPE_FIXED) {
13835                 if (mptsas_add_intrs(mpt, DDI_INTR_TYPE_FIXED) == DDI_SUCCESS) {
13836                         NDBG6(("Using FIXED interrupt type"));
13837                         mpt->m_intr_type = DDI_INTR_TYPE_FIXED;
13838                         return (TRUE);
13839                 } else {
13840                         NDBG6(("FIXED interrupt registration failed"));
13841                         return (FALSE);
13842                 }
13843         }
13844 
13845         return (FALSE);
13846 }
13847 
13848 static void
13849 mptsas_unregister_intrs(mptsas_t *mpt)
13850 {
13851         mptsas_rem_intrs(mpt);
13852 }
13853 
13854 /*
13855  * mptsas_add_intrs:
13856  *
13857  * Register FIXED or MSI interrupts.
13858  */
13859 static int
13860 mptsas_add_intrs(mptsas_t *mpt, int intr_type)
13861 {
13862         dev_info_t      *dip = mpt->m_dip;
13863         int             avail, actual, count = 0;
13864         int             i, flag, ret;
13865 
13866         NDBG6(("mptsas_add_intrs:interrupt type 0x%x", intr_type));
13867 
13868         /* Get number of interrupts */
13869         ret = ddi_intr_get_nintrs(dip, intr_type, &count);
13870         if ((ret != DDI_SUCCESS) || (count <= 0)) {
13871                 mptsas_log(mpt, CE_WARN, "ddi_intr_get_nintrs() failed, "
13872                     "ret %d count %d\n", ret, count);
13873 
13874                 return (DDI_FAILURE);
13875         }
13876 
13877         /* Get number of interrupts available to this device */
13878         ret = ddi_intr_get_navail(dip, intr_type, &avail);
13879         if ((ret != DDI_SUCCESS) || (avail == 0)) {
13880                 mptsas_log(mpt, CE_WARN, "ddi_intr_get_navail() failed, "
13881                     "ret %d avail %d\n", ret, avail);
13882 
13883                 return (DDI_FAILURE);
13884         }
13885 
13886         if (count < avail) {
13887                 mptsas_log(mpt, CE_NOTE, "ddi_intr_get_nvail returned %d, "
13888                     "navail() returned %d", count, avail);
13889         }
13890 
13891         NDBG6(("mptsas_add_intrs:count %d, avail %d", count, avail));
13892 
13893         if (intr_type == DDI_INTR_TYPE_MSIX) {
13894                 if (!mptsas3_max_msix_intrs) {
13895                         return (DDI_FAILURE);
13896                 }
13897 
13898                 /*
13899                  * Restrict the number of interrupts, firstly by
13900                  * the number returned from the IOCInfo, then by
13901                  * overall restriction.
13902                  */
13903                 if (avail > mpt->m_max_msix_vectors) {
13904                         avail = mpt->m_max_msix_vectors?
13905                             mpt->m_max_msix_vectors:1;
13906                         NDBG6(("mptsas_add_intrs: mmmv avail %d", avail));
13907                 }
13908                 if (avail > mptsas3_max_msix_intrs) {
13909                         avail = mptsas3_max_msix_intrs;
13910                         NDBG6(("mptsas_add_intrs: m3mmi avail %d", avail));
13911                 }
13912         }
13913         if (intr_type == DDI_INTR_TYPE_MSI) {
13914                 NDBG6(("mptsas_add_intrs: MSI avail %d", avail));
13915                 avail = 1;
13916         }
13917 
13918         /* Allocate an array of interrupt handles */
13919         mpt->m_intr_size = avail * sizeof (ddi_intr_handle_t);
13920         mpt->m_htable = kmem_alloc(mpt->m_intr_size, KM_SLEEP);
13921 
13922         flag = DDI_INTR_ALLOC_NORMAL;
13923 
13924         /* call ddi_intr_alloc() */
13925         ret = ddi_intr_alloc(dip, mpt->m_htable, intr_type, 0,
13926             avail, &actual, flag);
13927 
13928         if ((ret != DDI_SUCCESS) || (actual == 0)) {
13929                 mptsas_log(mpt, CE_WARN, "ddi_intr_alloc() failed, ret %d\n",
13930                     ret);
13931                 kmem_free(mpt->m_htable, mpt->m_intr_size);
13932                 return (DDI_FAILURE);
13933         }
13934 
13935         NDBG6(("mptsas_add_intrs: actual %d, avail %d", actual, avail));
13936         /* use interrupt count returned or abort? */
13937         if (actual < avail) {
13938                 mptsas_log(mpt, CE_NOTE,
13939                     "Interrupts requested: %d, received: %d\n",
13940                     avail, actual);
13941         }
13942 


13943         /*
13944          * Get priority for first msi, assume remaining are all the same
13945          */
13946         if ((ret = ddi_intr_get_pri(mpt->m_htable[0],
13947             &mpt->m_intr_pri)) != DDI_SUCCESS) {
13948                 mptsas_log(mpt, CE_WARN, "ddi_intr_get_pri() failed %d\n", ret);
13949 
13950                 /* Free already allocated intr */
13951                 for (i = 0; i < actual; i++) {
13952                         (void) ddi_intr_free(mpt->m_htable[i]);
13953                 }
13954 
13955                 kmem_free(mpt->m_htable, mpt->m_intr_size);
13956                 return (DDI_FAILURE);
13957         }
13958 
13959         /* Test for high level mutex */
13960         if (mpt->m_intr_pri >= ddi_intr_get_hilevel_pri()) {
13961                 mptsas_log(mpt, CE_WARN, "mptsas_add_intrs: "
13962                     "Hi level interrupt not supported\n");


13983                         }
13984 
13985                         kmem_free(mpt->m_htable, mpt->m_intr_size);
13986                         return (DDI_FAILURE);
13987                 }
13988         }
13989 
13990         if ((ret = ddi_intr_get_cap(mpt->m_htable[0], &mpt->m_intr_cap))
13991             != DDI_SUCCESS) {
13992                 mptsas_log(mpt, CE_WARN, "ddi_intr_get_cap() failed %d\n", ret);
13993 
13994                 /* Free already allocated intr */
13995                 for (i = 0; i < actual; i++) {
13996                         (void) ddi_intr_free(mpt->m_htable[i]);
13997                 }
13998 
13999                 kmem_free(mpt->m_htable, mpt->m_intr_size);
14000                 return (DDI_FAILURE);
14001         }
14002 
14003         mpt->m_intr_cnt = actual;
14004 
14005         /*
14006          * Enable interrupts
14007          */
14008         if (mpt->m_intr_cap & DDI_INTR_FLAG_BLOCK) {
14009                 /* Call ddi_intr_block_enable() for MSI interrupts */
14010                 (void) ddi_intr_block_enable(mpt->m_htable, mpt->m_intr_cnt);
14011         } else {
14012                 /* Call ddi_intr_enable for MSI or FIXED interrupts */
14013                 for (i = 0; i < mpt->m_intr_cnt; i++) {
14014                         (void) ddi_intr_enable(mpt->m_htable[i]);
14015                 }
14016         }
14017 
14018         switch (intr_type) {
14019         case DDI_INTR_TYPE_MSIX:
14020                 mptsas_log(mpt, CE_NOTE, "?Using %d MSI-X interrupt(s) "
14021                     "(Available sys %d, mpt %d, Requested %d)\n",
14022                     actual, count, mpt->m_max_msix_vectors, avail);
14023                 break;
14024         case DDI_INTR_TYPE_MSI:
14025                 mptsas_log(mpt, CE_NOTE, "Using single MSI interrupt\n");
14026                 break;
14027         case DDI_INTR_TYPE_FIXED:
14028         default:
14029                 mptsas_log(mpt, CE_NOTE, "Using single fixed interrupt\n");
14030                 break;
14031         }
14032 
14033         return (DDI_SUCCESS);
14034 }
14035 
14036 /*
14037  * mptsas_rem_intrs:
14038  *
14039  * Unregister FIXED or MSI interrupts
14040  */
14041 static void
14042 mptsas_rem_intrs(mptsas_t *mpt)
14043 {
14044         int     i;
14045 
14046         NDBG6(("mptsas_rem_intrs"));
14047 
14048         /* Disable all interrupts */
14049         if (mpt->m_intr_cap & DDI_INTR_FLAG_BLOCK) {
14050                 /* Call ddi_intr_block_disable() */
14051                 (void) ddi_intr_block_disable(mpt->m_htable, mpt->m_intr_cnt);
14052         } else {
14053                 for (i = 0; i < mpt->m_intr_cnt; i++) {
14054                         (void) ddi_intr_disable(mpt->m_htable[i]);
14055                 }
14056         }
14057 
14058         /* Call ddi_intr_remove_handler() */
14059         for (i = 0; i < mpt->m_intr_cnt; i++) {
14060                 (void) ddi_intr_remove_handler(mpt->m_htable[i]);
14061                 (void) ddi_intr_free(mpt->m_htable[i]);
14062         }

14063         kmem_free(mpt->m_htable, mpt->m_intr_size);
14064         mpt->m_intr_cnt = 0;
14065 }
14066 
14067 /*
14068  * The IO fault service error handling callback function
14069  */
14070 /*ARGSUSED*/
14071 static int
14072 mptsas_fm_error_cb(dev_info_t *dip, ddi_fm_error_t *err, const void *impl_data)
14073 {
14074         /*
14075          * as the driver can always deal with an error in any dma or
14076          * access handle, we can just return the fme_status value.
14077          */
14078         pci_ereport_post(dip, err, NULL);
14079         return (err->fme_status);
14080 }
14081 
14082 /*
14083  * mptsas_fm_init - initialize fma capabilities and register with IO
14084  *               fault services.


14194         (void) snprintf(buf, FM_MAX_CLASS, "%s.%s", DDI_FM_DEVICE, detail);
14195         ena = fm_ena_generate(0, FM_ENA_FMT1);
14196         if (DDI_FM_EREPORT_CAP(mpt->m_fm_capabilities)) {
14197                 ddi_fm_ereport_post(mpt->m_dip, buf, ena, DDI_NOSLEEP,
14198                     FM_VERSION, DATA_TYPE_UINT8, FM_EREPORT_VERS0, NULL);
14199         }
14200 }
14201 
14202 static int
14203 mptsas_get_target_device_info(mptsas_t *mpt, uint32_t page_address,
14204     uint16_t *dev_handle, mptsas_target_t **pptgt)
14205 {
14206         int             rval;
14207         uint32_t        dev_info;
14208         uint64_t        sas_wwn;
14209         mptsas_phymask_t phymask;
14210         uint8_t         physport, phynum, config, disk;
14211         uint64_t        devicename;
14212         uint16_t        pdev_hdl;
14213         mptsas_target_t *tmp_tgt = NULL;
14214         uint16_t        bay_num, enclosure, io_flags;
14215 
14216         ASSERT(*pptgt == NULL);
14217 
14218         rval = mptsas_get_sas_device_page0(mpt, page_address, dev_handle,
14219             &sas_wwn, &dev_info, &physport, &phynum, &pdev_hdl,
14220             &bay_num, &enclosure, &io_flags);
14221         if (rval != DDI_SUCCESS) {
14222                 rval = DEV_INFO_FAIL_PAGE0;
14223                 return (rval);
14224         }
14225 
14226         if ((dev_info & (MPI2_SAS_DEVICE_INFO_SSP_TARGET |
14227             MPI2_SAS_DEVICE_INFO_SATA_DEVICE |
14228             MPI2_SAS_DEVICE_INFO_ATAPI_DEVICE)) == NULL) {
14229                 rval = DEV_INFO_WRONG_DEVICE_TYPE;
14230                 return (rval);
14231         }
14232 
14233         /*
14234          * Check if the dev handle is for a Phys Disk. If so, set return value
14235          * and exit.  Don't add Phys Disks to hash.
14236          */
14237         for (config = 0; config < mpt->m_num_raid_configs; config++) {
14238                 for (disk = 0; disk < MPTSAS_MAX_DISKS_IN_CONFIG; disk++) {
14239                         if (*dev_handle == mpt->m_raidconfig[config].
14240                             m_physdisk_devhdl[disk]) {


14245         }
14246 
14247         /*
14248          * Get SATA Device Name from SAS device page0 for
14249          * sata device, if device name doesn't exist, set mta_wwn to
14250          * 0 for direct attached SATA. For the device behind the expander
14251          * we still can use STP address assigned by expander.
14252          */
14253         if (dev_info & (MPI2_SAS_DEVICE_INFO_SATA_DEVICE |
14254             MPI2_SAS_DEVICE_INFO_ATAPI_DEVICE)) {
14255                 mutex_exit(&mpt->m_mutex);
14256                 /* alloc a tmp_tgt to send the cmd */
14257                 tmp_tgt = kmem_zalloc(sizeof (struct mptsas_target),
14258                     KM_SLEEP);
14259                 tmp_tgt->m_devhdl = *dev_handle;
14260                 tmp_tgt->m_deviceinfo = dev_info;
14261                 tmp_tgt->m_qfull_retries = QFULL_RETRIES;
14262                 tmp_tgt->m_qfull_retry_interval =
14263                     drv_usectohz(QFULL_RETRY_INTERVAL * 1000);
14264                 tmp_tgt->m_t_throttle = MAX_THROTTLE;
14265                 mutex_init(&tmp_tgt->m_t_mutex, NULL, MUTEX_DRIVER, NULL);
14266                 devicename = mptsas_get_sata_guid(mpt, tmp_tgt, 0);
14267                 mutex_destroy(&tmp_tgt->m_t_mutex);
14268                 kmem_free(tmp_tgt, sizeof (struct mptsas_target));
14269                 mutex_enter(&mpt->m_mutex);
14270                 if (devicename != 0 && (((devicename >> 56) & 0xf0) == 0x50)) {
14271                         sas_wwn = devicename;
14272                 } else if (dev_info & MPI2_SAS_DEVICE_INFO_DIRECT_ATTACH) {
14273                         sas_wwn = 0;
14274                 }
14275         }
14276 
14277         phymask = mptsas_physport_to_phymask(mpt, physport);
14278         *pptgt = mptsas_tgt_alloc(mpt, *dev_handle, sas_wwn,
14279             dev_info, phymask, phynum);
14280         if (*pptgt == NULL) {
14281                 mptsas_log(mpt, CE_WARN, "Failed to allocated target"
14282                     "structure!");
14283                 rval = DEV_INFO_FAIL_ALLOC;
14284                 return (rval);
14285         }
14286         (*pptgt)->m_io_flags = io_flags;
14287         (*pptgt)->m_enclosure = enclosure;
14288         (*pptgt)->m_slot_num = bay_num;
14289         return (DEV_INFO_SUCCESS);
14290 }
14291 
14292 uint64_t
14293 mptsas_get_sata_guid(mptsas_t *mpt, mptsas_target_t *ptgt, int lun)
14294 {
14295         uint64_t        sata_guid = 0, *pwwn = NULL;
14296         int             target = ptgt->m_devhdl;
14297         uchar_t         *inq83 = NULL;
14298         int             inq83_len = 0xFF;
14299         uchar_t         *dblk = NULL;
14300         int             inq83_retry = 3;
14301         int             rval = DDI_FAILURE;
14302 
14303         inq83   = kmem_zalloc(inq83_len, KM_SLEEP);
14304 
14305 inq83_retry:
14306         rval = mptsas_inquiry(mpt, ptgt, lun, 0x83, inq83,


14404         bcopy((caddr_t)mpt->m_tran,
14405             (caddr_t)tran_clone, sizeof (scsi_hba_tran_t));
14406         tgt_private = kmem_alloc(
14407             sizeof (mptsas_tgt_private_t), KM_SLEEP);
14408         if (tgt_private == NULL) {
14409                 goto out;
14410         }
14411         tgt_private->t_lun = ap->a_lun;
14412         tgt_private->t_private = ptgt;
14413         tran_clone->tran_tgt_private = tgt_private;
14414         ap->a_hba_tran = tran_clone;
14415 
14416         pktp = scsi_init_pkt(ap, (struct scsi_pkt *)NULL,
14417             data_bp, cdblen, sizeof (struct scsi_arq_status),
14418             0, PKT_CONSISTENT, NULL, NULL);
14419         if (pktp == NULL) {
14420                 goto out;
14421         }
14422         bcopy(cdb, pktp->pkt_cdbp, cdblen);
14423         pktp->pkt_flags = FLAG_NOPARITY;
14424         pktp->pkt_time = mptsas_scsi_pkt_time;
14425         if (scsi_poll(pktp) < 0) {
14426                 goto out;
14427         }
14428         if (((struct scsi_status *)pktp->pkt_scbp)->sts_chk) {
14429                 goto out;
14430         }
14431         if (resid != NULL) {
14432                 *resid = pktp->pkt_resid;
14433         }
14434 
14435         ret = DDI_SUCCESS;
14436 out:
14437         if (pktp) {
14438                 scsi_destroy_pkt(pktp);
14439         }
14440         if (tran_clone) {
14441                 kmem_free(tran_clone, sizeof (scsi_hba_tran_t));
14442         }
14443         if (tgt_private) {
14444                 kmem_free(tgt_private, sizeof (mptsas_tgt_private_t));


15253         dev_info_t      *tdip;
15254 
15255         rval = mptsas_config_luns(pdip, ptgt);
15256         if (rval != DDI_SUCCESS) {
15257                 /*
15258                  * The return value means the SCMD_REPORT_LUNS
15259                  * did not execute successfully. The target maybe
15260                  * doesn't support such command.
15261                  */
15262                 rval = mptsas_probe_lun(pdip, 0, &tdip, ptgt);
15263         }
15264         return (rval);
15265 }
15266 
15267 /*
15268  * Return fail if not all the childs/paths are freed.
15269  * if there is any path under the HBA, the return value will be always fail
15270  * because we didn't call mdi_pi_free for path
15271  */
15272 static int
15273 mptsas_offline_targetdev(dev_info_t *pdip, char *name)
15274 {
15275         dev_info_t              *child = NULL, *prechild = NULL;
15276         mdi_pathinfo_t          *pip = NULL, *savepip = NULL;
15277         int                     tmp_rval, rval = DDI_SUCCESS;
15278         char                    *addr, *cp;
15279         size_t                  s;
15280         mptsas_t                *mpt = DIP2MPT(pdip);
15281 
15282         child = ddi_get_child(pdip);
15283         while (child) {
15284                 addr = ddi_get_name_addr(child);
15285                 prechild = child;
15286                 child = ddi_get_next_sibling(child);
15287 
15288                 if (addr == NULL) {
15289                         continue;
15290                 }
15291                 if ((cp = strchr(addr, ',')) == NULL) {
15292                         continue;
15293                 }
15294 
15295                 s = (uintptr_t)cp - (uintptr_t)addr;
15296 
15297                 if (strncmp(addr, name, s) != 0) {
15298                         continue;
15299                 }
15300 
15301                 tmp_rval = mptsas_offline_lun(pdip, prechild, NULL,
15302                     NDI_DEVI_REMOVE);
15303                 if (tmp_rval != DDI_SUCCESS) {
15304                         rval = DDI_FAILURE;
15305                         if (ndi_prop_create_boolean(DDI_DEV_T_NONE,
15306                             prechild, MPTSAS_DEV_GONE) !=
15307                             DDI_PROP_SUCCESS) {
15308                                 mptsas_log(mpt, CE_WARN,
15309                                     "unable to create property for "
15310                                     "SAS %s (MPTSAS_DEV_GONE)", addr);
15311                         }
15312                 }
15313         }
15314 
15315         pip = mdi_get_next_client_path(pdip, NULL);
15316         while (pip) {
15317                 addr = MDI_PI(pip)->pi_addr;
15318                 savepip = pip;
15319                 pip = mdi_get_next_client_path(pdip, pip);
15320                 if (addr == NULL) {
15321                         continue;
15322                 }
15323 
15324                 if ((cp = strchr(addr, ',')) == NULL) {
15325                         continue;
15326                 }
15327 
15328                 s = (uintptr_t)cp - (uintptr_t)addr;


15665                 ddi_devid_free_guid(guid);
15666         }
15667         if (inq83 != NULL)
15668                 kmem_free(inq83, inq83_len1);
15669         return (rval);
15670 }
15671 
15672 static int
15673 mptsas_create_virt_lun(dev_info_t *pdip, struct scsi_inquiry *inq, char *guid,
15674     dev_info_t **lun_dip, mdi_pathinfo_t **pip, mptsas_target_t *ptgt, int lun)
15675 {
15676         int                     target;
15677         char                    *nodename = NULL;
15678         char                    **compatible = NULL;
15679         int                     ncompatible     = 0;
15680         int                     mdi_rtn = MDI_FAILURE;
15681         int                     rval = DDI_FAILURE;
15682         char                    *old_guid = NULL;
15683         mptsas_t                *mpt = DIP2MPT(pdip);
15684         char                    *lun_addr = NULL;
15685         char                    wwn_str[MPTSAS_WWN_STRLEN];

15686         char                    *component = NULL;
15687         uint8_t                 phy = 0xFF;
15688         uint64_t                sas_wwn;
15689         int64_t                 lun64 = 0;
15690         uint32_t                devinfo;
15691         uint16_t                dev_hdl;
15692         uint16_t                pdev_hdl;
15693         uint64_t                dev_sas_wwn;
15694         uint64_t                pdev_sas_wwn;
15695         uint32_t                pdev_info;
15696         uint8_t                 physport;
15697         uint8_t                 phy_id;
15698         uint32_t                page_address;
15699         uint16_t                bay_num, enclosure, io_flags;
15700         char                    pdev_wwn_str[MPTSAS_WWN_STRLEN];
15701         uint32_t                dev_info;
15702 
15703         mutex_enter(&mpt->m_mutex);
15704         target = ptgt->m_devhdl;
15705         sas_wwn = ptgt->m_addr.mta_wwn;
15706         devinfo = ptgt->m_deviceinfo;
15707         phy = ptgt->m_phynum;
15708         mutex_exit(&mpt->m_mutex);
15709 
15710         if (sas_wwn) {
15711                 *pip = mptsas_find_path_addr(pdip, sas_wwn, lun);
15712         } else {
15713                 *pip = mptsas_find_path_phy(pdip, phy);
15714         }
15715 
15716         if (*pip != NULL) {
15717                 *lun_dip = MDI_PI(*pip)->pi_client->ct_dip;
15718                 ASSERT(*lun_dip != NULL);
15719                 if (ddi_prop_lookup_string(DDI_DEV_T_ANY, *lun_dip,


15773                                         *pip = NULL;
15774                                         *lun_dip = NULL;
15775                                         return (DDI_FAILURE);
15776                                 }
15777                         }
15778                 } else {
15779                         mptsas_log(mpt, CE_WARN, "Can't get client-guid "
15780                             "property for path:target:%x, lun:%x", target, lun);
15781                         *pip = NULL;
15782                         *lun_dip = NULL;
15783                         return (DDI_FAILURE);
15784                 }
15785         }
15786         scsi_hba_nodename_compatible_get(inq, NULL,
15787             inq->inq_dtype, NULL, &nodename, &compatible, &ncompatible);
15788 
15789         /*
15790          * if nodename can't be determined then print a message and skip it
15791          */
15792         if (nodename == NULL) {
15793                 mptsas_log(mpt, CE_WARN, "found no compatible "
15794                     "driver for target%d lun %d dtype:0x%02x", target, lun,
15795                     inq->inq_dtype);
15796                 return (DDI_FAILURE);
15797         }
15798 

15799         /* The property is needed by MPAPI */
15800         (void) sprintf(wwn_str, "%016"PRIx64, sas_wwn);
15801 
15802         lun_addr = kmem_zalloc(SCSI_MAXNAMELEN, KM_SLEEP);
15803         if (guid) {
15804                 (void) sprintf(lun_addr, "w%s,%x", wwn_str, lun);
15805                 (void) sprintf(wwn_str, "w%016"PRIx64, sas_wwn);
15806         } else {
15807                 (void) sprintf(lun_addr, "p%x,%x", phy, lun);
15808                 (void) sprintf(wwn_str, "p%x", phy);
15809         }
15810 
15811         mdi_rtn = mdi_pi_alloc_compatible(pdip, nodename,
15812             guid, lun_addr, compatible, ncompatible,
15813             0, pip);
15814         if (mdi_rtn == MDI_SUCCESS) {
15815 
15816                 if (mdi_prop_update_string(*pip, MDI_GUID,
15817                     guid) != DDI_SUCCESS) {
15818                         mptsas_log(mpt, CE_WARN, "unable to "
15819                             "create prop for target %d lun %d (MDI_GUID)",
15820                             target, lun);
15821                         mdi_rtn = MDI_FAILURE;
15822                         goto virt_create_done;
15823                 }
15824 
15825                 if (mdi_prop_update_int(*pip, LUN_PROP,
15826                     lun) != DDI_SUCCESS) {
15827                         mptsas_log(mpt, CE_WARN, "unable to "
15828                             "create prop for target %d lun %d (LUN_PROP)",
15829                             target, lun);
15830                         mdi_rtn = MDI_FAILURE;
15831                         goto virt_create_done;
15832                 }
15833                 lun64 = (int64_t)lun;
15834                 if (mdi_prop_update_int64(*pip, LUN64_PROP,
15835                     lun64) != DDI_SUCCESS) {
15836                         mptsas_log(mpt, CE_WARN, "unable to "
15837                             "create prop for target %d (LUN64_PROP)",
15838                             target);
15839                         mdi_rtn = MDI_FAILURE;
15840                         goto virt_create_done;
15841                 }
15842                 if (mdi_prop_update_string_array(*pip, "compatible",
15843                     compatible, ncompatible) !=
15844                     DDI_PROP_SUCCESS) {
15845                         mptsas_log(mpt, CE_WARN, "unable to "
15846                             "create prop for target %d lun %d (COMPATIBLE)",
15847                             target, lun);
15848                         mdi_rtn = MDI_FAILURE;
15849                         goto virt_create_done;
15850                 }
15851                 if (sas_wwn && (mdi_prop_update_string(*pip,
15852                     SCSI_ADDR_PROP_TARGET_PORT, wwn_str) != DDI_PROP_SUCCESS)) {
15853                         mptsas_log(mpt, CE_WARN, "unable to "
15854                             "create prop for target %d lun %d "
15855                             "(target-port)", target, lun);
15856                         mdi_rtn = MDI_FAILURE;
15857                         goto virt_create_done;
15858                 } else if ((sas_wwn == 0) && (mdi_prop_update_int(*pip,
15859                     "sata-phy", phy) != DDI_PROP_SUCCESS)) {
15860                         /*
15861                          * Direct attached SATA device without DeviceName
15862                          */
15863                         mptsas_log(mpt, CE_WARN, "unable to "
15864                             "create prop for SAS target %d lun %d "
15865                             "(sata-phy)", target, lun);
15866                         mdi_rtn = MDI_FAILURE;
15867                         goto virt_create_done;
15868                 }
15869                 mutex_enter(&mpt->m_mutex);
15870 
15871                 page_address = (MPI2_SAS_DEVICE_PGAD_FORM_HANDLE &
15872                     MPI2_SAS_DEVICE_PGAD_FORM_MASK) |
15873                     (uint32_t)ptgt->m_devhdl;
15874                 rval = mptsas_get_sas_device_page0(mpt, page_address,
15875                     &dev_hdl, &dev_sas_wwn, &dev_info, &physport,
15876                     &phy_id, &pdev_hdl, &bay_num, &enclosure, &io_flags);
15877                 if (rval != DDI_SUCCESS) {
15878                         mutex_exit(&mpt->m_mutex);
15879                         mptsas_log(mpt, CE_WARN, "mptsas unable to get "
15880                             "parent device for handle %d", page_address);
15881                         mdi_rtn = MDI_FAILURE;
15882                         goto virt_create_done;
15883                 }
15884 
15885                 page_address = (MPI2_SAS_DEVICE_PGAD_FORM_HANDLE &
15886                     MPI2_SAS_DEVICE_PGAD_FORM_MASK) | (uint32_t)pdev_hdl;
15887                 rval = mptsas_get_sas_device_page0(mpt, page_address,
15888                     &dev_hdl, &pdev_sas_wwn, &pdev_info, &physport,
15889                     &phy_id, &pdev_hdl, &bay_num, &enclosure, &io_flags);
15890                 if (rval != DDI_SUCCESS) {
15891                         mutex_exit(&mpt->m_mutex);
15892                         mptsas_log(mpt, CE_WARN, "mptsas unable to get"
15893                             "device info for handle %d", page_address);
15894                         mdi_rtn = MDI_FAILURE;
15895                         goto virt_create_done;
15896                 }
15897 
15898                 mutex_exit(&mpt->m_mutex);
15899 
15900                 /*
15901                  * If this device direct attached to the controller
15902                  * set the attached-port to the base wwid
15903                  */
15904                 if ((ptgt->m_deviceinfo & DEVINFO_DIRECT_ATTACHED)
15905                     != DEVINFO_DIRECT_ATTACHED) {
15906                         (void) sprintf(pdev_wwn_str, "w%016"PRIx64,
15907                             pdev_sas_wwn);
15908                 } else {
15909                         /*


15916                         }
15917                         if (ddi_prop_update_string(DDI_DEV_T_NONE,
15918                             pdip, SCSI_ADDR_PROP_ATTACHED_PORT, wwn_str) !=
15919                             DDI_PROP_SUCCESS) {
15920                                 mptsas_log(mpt, CE_WARN,
15921                                     "mptsas unable to create "
15922                                     "property for iport target-port"
15923                                     " %s (sas_wwn)",
15924                                     wwn_str);
15925                                 mdi_rtn = MDI_FAILURE;
15926                                 goto virt_create_done;
15927                         }
15928 
15929                         (void) sprintf(pdev_wwn_str, "w%016"PRIx64,
15930                             mpt->un.m_base_wwid);
15931                 }
15932 
15933                 if (mdi_prop_update_string(*pip,
15934                     SCSI_ADDR_PROP_ATTACHED_PORT, pdev_wwn_str) !=
15935                     DDI_PROP_SUCCESS) {
15936                         mptsas_log(mpt, CE_WARN, "unable to create "
15937                             "property for iport attached-port %s (sas_wwn)",
15938                             pdev_wwn_str);
15939                         mdi_rtn = MDI_FAILURE;
15940                         goto virt_create_done;
15941                 }
15942 
15943 
15944                 if (inq->inq_dtype == 0) {
15945                         component = kmem_zalloc(MAXPATHLEN, KM_SLEEP);
15946                         /*
15947                          * set obp path for pathinfo
15948                          */
15949                         (void) snprintf(component, MAXPATHLEN,
15950                             "disk@%s", lun_addr);
15951 
15952                         if (mdi_pi_pathname_obp_set(*pip, component) !=
15953                             DDI_SUCCESS) {
15954                                 mptsas_log(mpt, CE_WARN,
15955                                     "unable to set obp-path for object %s",
15956                                     component);
15957                                 mdi_rtn = MDI_FAILURE;
15958                                 goto virt_create_done;
15959                         }
15960                 }
15961 
15962                 *lun_dip = MDI_PI(*pip)->pi_client->ct_dip;
15963                 if (devinfo & (MPI2_SAS_DEVICE_INFO_SATA_DEVICE |
15964                     MPI2_SAS_DEVICE_INFO_ATAPI_DEVICE)) {
15965                         if ((ndi_prop_update_int(DDI_DEV_T_NONE, *lun_dip,
15966                             "pm-capable", 1)) !=
15967                             DDI_PROP_SUCCESS) {
15968                                 mptsas_log(mpt, CE_WARN,
15969                                     "failed to create pm-capable "
15970                                     "property, target %d", target);
15971                                 mdi_rtn = MDI_FAILURE;
15972                                 goto virt_create_done;
15973                         }
15974                 }
15975                 /*
15976                  * Create the phy-num property
15977                  */
15978                 if (mdi_prop_update_int(*pip, "phy-num",
15979                     ptgt->m_phynum) != DDI_SUCCESS) {
15980                         mptsas_log(mpt, CE_WARN, "unable to "
15981                             "create phy-num property for target %d lun %d",
15982                             target, lun);
15983                         mdi_rtn = MDI_FAILURE;
15984                         goto virt_create_done;
15985                 }
15986                 NDBG20(("new path:%s onlining,", MDI_PI(*pip)->pi_addr));
15987                 mdi_rtn = mdi_pi_online(*pip, 0);
15988                 if (mdi_rtn == MDI_SUCCESS) {
15989                         mutex_enter(&mpt->m_mutex);
15990                         ptgt->m_led_status = 0;
15991                         (void) mptsas_flush_led_status(mpt, ptgt);
15992                         mutex_exit(&mpt->m_mutex);
15993                 }
15994                 if (mdi_rtn == MDI_NOT_SUPPORTED) {
15995                         mdi_rtn = MDI_FAILURE;
15996                 }
15997 virt_create_done:
15998                 if (*pip && mdi_rtn != MDI_SUCCESS) {
15999                         (void) mdi_pi_free(*pip, 0);
16000                         *pip = NULL;
16001                         *lun_dip = NULL;
16002                 }
16003         }
16004 
16005         scsi_hba_nodename_compatible_free(nodename, compatible);
16006         if (lun_addr != NULL) {
16007                 kmem_free(lun_addr, SCSI_MAXNAMELEN);
16008         }



16009         if (component != NULL) {
16010                 kmem_free(component, MAXPATHLEN);
16011         }
16012 
16013         return ((mdi_rtn == MDI_SUCCESS) ? DDI_SUCCESS : DDI_FAILURE);
16014 }
16015 
16016 static int
16017 mptsas_create_phys_lun(dev_info_t *pdip, struct scsi_inquiry *inq,
16018     char *guid, dev_info_t **lun_dip, mptsas_target_t *ptgt, int lun)
16019 {
16020         int                     target;
16021         int                     rval;
16022         int                     ndi_rtn = NDI_FAILURE;
16023         uint64_t                be_sas_wwn;
16024         char                    *nodename = NULL;
16025         char                    **compatible = NULL;
16026         int                     ncompatible = 0;
16027         int                     instance = 0;
16028         mptsas_t                *mpt = DIP2MPT(pdip);
16029         char                    wwn_str[MPTSAS_WWN_STRLEN];
16030         char                    component[MAXPATHLEN];

16031         uint8_t                 phy = 0xFF;
16032         uint64_t                sas_wwn;
16033         uint32_t                devinfo;
16034         uint16_t                dev_hdl;
16035         uint16_t                pdev_hdl;
16036         uint64_t                pdev_sas_wwn;
16037         uint64_t                dev_sas_wwn;
16038         uint32_t                pdev_info;
16039         uint8_t                 physport;
16040         uint8_t                 phy_id;
16041         uint32_t                page_address;
16042         uint16_t                bay_num, enclosure, io_flags;
16043         char                    pdev_wwn_str[MPTSAS_WWN_STRLEN];
16044         uint32_t                dev_info;
16045         int64_t                 lun64 = 0;
16046 
16047         mutex_enter(&mpt->m_mutex);
16048         target = ptgt->m_devhdl;
16049         sas_wwn = ptgt->m_addr.mta_wwn;
16050         devinfo = ptgt->m_deviceinfo;
16051         phy = ptgt->m_phynum;
16052         mutex_exit(&mpt->m_mutex);
16053 
16054         /*
16055          * generate compatible property with binding-set "mpt"
16056          */
16057         scsi_hba_nodename_compatible_get(inq, NULL, inq->inq_dtype, NULL,
16058             &nodename, &compatible, &ncompatible);
16059 
16060         /*
16061          * if nodename can't be determined then print a message and skip it
16062          */


16093                             target, lun);
16094                         ndi_rtn = NDI_FAILURE;
16095                         goto phys_create_done;
16096                 }
16097                 if (ndi_prop_update_string_array(DDI_DEV_T_NONE,
16098                     *lun_dip, "compatible", compatible, ncompatible)
16099                     != DDI_PROP_SUCCESS) {
16100                         mptsas_log(mpt, CE_WARN, "mptsas unable to create "
16101                             "property for target %d lun %d (COMPATIBLE)",
16102                             target, lun);
16103                         ndi_rtn = NDI_FAILURE;
16104                         goto phys_create_done;
16105                 }
16106 
16107                 /*
16108                  * We need the SAS WWN for non-multipath devices, so
16109                  * we'll use the same property as that multipathing
16110                  * devices need to present for MPAPI. If we don't have
16111                  * a WWN (e.g. parallel SCSI), don't create the prop.
16112                  */

16113                 (void) sprintf(wwn_str, "w%016"PRIx64, sas_wwn);
16114                 if (sas_wwn && ndi_prop_update_string(DDI_DEV_T_NONE,
16115                     *lun_dip, SCSI_ADDR_PROP_TARGET_PORT, wwn_str)
16116                     != DDI_PROP_SUCCESS) {
16117                         mptsas_log(mpt, CE_WARN, "mptsas unable to "
16118                             "create property for SAS target %d lun %d "
16119                             "(target-port)", target, lun);
16120                         ndi_rtn = NDI_FAILURE;
16121                         goto phys_create_done;
16122                 }
16123 
16124                 be_sas_wwn = BE_64(sas_wwn);
16125                 if (sas_wwn && ndi_prop_update_byte_array(
16126                     DDI_DEV_T_NONE, *lun_dip, "port-wwn",
16127                     (uchar_t *)&be_sas_wwn, 8) != DDI_PROP_SUCCESS) {
16128                         mptsas_log(mpt, CE_WARN, "mptsas unable to "
16129                             "create property for SAS target %d lun %d "
16130                             "(port-wwn)", target, lun);
16131                         ndi_rtn = NDI_FAILURE;
16132                         goto phys_create_done;


16158                             "lun %d", target, lun);
16159                         ndi_rtn = NDI_FAILURE;
16160                         goto phys_create_done;
16161                 }
16162 
16163                 /*
16164                  * The following code is to set properties for SM-HBA support,
16165                  * it doesn't apply to RAID volumes
16166                  */
16167                 if (ptgt->m_addr.mta_phymask == 0)
16168                         goto phys_raid_lun;
16169 
16170                 mutex_enter(&mpt->m_mutex);
16171 
16172                 page_address = (MPI2_SAS_DEVICE_PGAD_FORM_HANDLE &
16173                     MPI2_SAS_DEVICE_PGAD_FORM_MASK) |
16174                     (uint32_t)ptgt->m_devhdl;
16175                 rval = mptsas_get_sas_device_page0(mpt, page_address,
16176                     &dev_hdl, &dev_sas_wwn, &dev_info,
16177                     &physport, &phy_id, &pdev_hdl,
16178                     &bay_num, &enclosure, &io_flags);
16179                 if (rval != DDI_SUCCESS) {
16180                         mutex_exit(&mpt->m_mutex);
16181                         mptsas_log(mpt, CE_WARN, "mptsas unable to get"
16182                             "parent device for handle %d.", page_address);
16183                         ndi_rtn = NDI_FAILURE;
16184                         goto phys_create_done;
16185                 }
16186 
16187                 page_address = (MPI2_SAS_DEVICE_PGAD_FORM_HANDLE &
16188                     MPI2_SAS_DEVICE_PGAD_FORM_MASK) | (uint32_t)pdev_hdl;
16189                 rval = mptsas_get_sas_device_page0(mpt, page_address,
16190                     &dev_hdl, &pdev_sas_wwn, &pdev_info, &physport,
16191                     &phy_id, &pdev_hdl, &bay_num, &enclosure, &io_flags);
16192                 if (rval != DDI_SUCCESS) {
16193                         mutex_exit(&mpt->m_mutex);
16194                         mptsas_log(mpt, CE_WARN, "mptsas unable to create "
16195                             "device for handle %d.", page_address);
16196                         ndi_rtn = NDI_FAILURE;
16197                         goto phys_create_done;
16198                 }
16199 
16200                 mutex_exit(&mpt->m_mutex);
16201 
16202                 /*
16203                  * If this device direct attached to the controller
16204                  * set the attached-port to the base wwid
16205                  */
16206                 if ((ptgt->m_deviceinfo & DEVINFO_DIRECT_ATTACHED)
16207                     != DEVINFO_DIRECT_ATTACHED) {
16208                         (void) sprintf(pdev_wwn_str, "w%016"PRIx64,
16209                             pdev_sas_wwn);
16210                 } else {
16211                         /*


16221                             DDI_PROP_SUCCESS) {
16222                                 mptsas_log(mpt, CE_WARN,
16223                                     "mptsas unable to create "
16224                                     "property for iport target-port"
16225                                     " %s (sas_wwn)",
16226                                     wwn_str);
16227                                 ndi_rtn = NDI_FAILURE;
16228                                 goto phys_create_done;
16229                         }
16230 
16231                         (void) sprintf(pdev_wwn_str, "w%016"PRIx64,
16232                             mpt->un.m_base_wwid);
16233                 }
16234 
16235                 if (ndi_prop_update_string(DDI_DEV_T_NONE,
16236                     *lun_dip, SCSI_ADDR_PROP_ATTACHED_PORT, pdev_wwn_str) !=
16237                     DDI_PROP_SUCCESS) {
16238                         mptsas_log(mpt, CE_WARN,
16239                             "mptsas unable to create "
16240                             "property for iport attached-port %s (sas_wwn)",
16241                             pdev_wwn_str);
16242                         ndi_rtn = NDI_FAILURE;
16243                         goto phys_create_done;
16244                 }
16245 
16246                 if (IS_SATA_DEVICE(dev_info)) {
16247                         if (ndi_prop_update_string(DDI_DEV_T_NONE,
16248                             *lun_dip, MPTSAS_VARIANT, "sata") !=
16249                             DDI_PROP_SUCCESS) {
16250                                 mptsas_log(mpt, CE_WARN,
16251                                     "mptsas unable to create "
16252                                     "property for device variant ");
16253                                 ndi_rtn = NDI_FAILURE;
16254                                 goto phys_create_done;
16255                         }
16256                 }
16257 
16258                 if (IS_ATAPI_DEVICE(dev_info)) {
16259                         if (ndi_prop_update_string(DDI_DEV_T_NONE,
16260                             *lun_dip, MPTSAS_VARIANT, "atapi") !=
16261                             DDI_PROP_SUCCESS) {
16262                                 mptsas_log(mpt, CE_WARN,
16263                                     "mptsas unable to create "
16264                                     "property for device variant ");
16265                                 ndi_rtn = NDI_FAILURE;
16266                                 goto phys_create_done;
16267                         }
16268                 }
16269 
16270 phys_raid_lun:
16271                 /*
16272                  * if this is a SAS controller, and the target is a SATA
16273                  * drive, set the 'pm-capable' property for sd and if on
16274                  * an OPL platform, also check if this is an ATAPI
16275                  * device.
16276                  */
16277                 instance = ddi_get_instance(mpt->m_dip);
16278                 if (devinfo & (MPI2_SAS_DEVICE_INFO_SATA_DEVICE |
16279                     MPI2_SAS_DEVICE_INFO_ATAPI_DEVICE)) {
16280                         NDBG2(("mptsas3%d: creating pm-capable property, "
16281                             "target %d", instance, target));
16282 
16283                         if ((ndi_prop_update_int(DDI_DEV_T_NONE,
16284                             *lun_dip, "pm-capable", 1)) !=
16285                             DDI_PROP_SUCCESS) {
16286                                 mptsas_log(mpt, CE_WARN, "mptsas "
16287                                     "failed to create pm-capable "
16288                                     "property, target %d", target);
16289                                 ndi_rtn = NDI_FAILURE;
16290                                 goto phys_create_done;
16291                         }
16292 
16293                 }
16294 
16295                 if ((inq->inq_dtype == 0) || (inq->inq_dtype == 5)) {
16296                         /*
16297                          * add 'obp-path' properties for devinfo
16298                          */
16299                         bzero(wwn_str, sizeof (wwn_str));
16300                         (void) sprintf(wwn_str, "%016"PRIx64, sas_wwn);

16301                         if (guid) {
16302                                 (void) snprintf(component, MAXPATHLEN,
16303                                     "disk@w%s,%x", wwn_str, lun);
16304                         } else {
16305                                 (void) snprintf(component, MAXPATHLEN,
16306                                     "disk@p%x,%x", phy, lun);
16307                         }
16308                         if (ddi_pathname_obp_set(*lun_dip, component)
16309                             != DDI_SUCCESS) {
16310                                 mptsas_log(mpt, CE_WARN, "mpt_sas driver "
16311                                     "unable to set obp-path for SAS "
16312                                     "object %s", component);
16313                                 ndi_rtn = NDI_FAILURE;
16314                                 goto phys_create_done;
16315                         }
16316                 }
16317                 /*
16318                  * Create the phy-num property for non-raid disk
16319                  */
16320                 if (ptgt->m_addr.mta_phymask != 0) {
16321                         if (ndi_prop_update_int(DDI_DEV_T_NONE,
16322                             *lun_dip, "phy-num", ptgt->m_phynum) !=
16323                             DDI_PROP_SUCCESS) {
16324                                 mptsas_log(mpt, CE_WARN,
16325                                     "failed to create phy-num property for "
16326                                     "target %d", target);
16327                                 ndi_rtn = NDI_FAILURE;
16328                                 goto phys_create_done;
16329                         }
16330                 }
16331 phys_create_done:
16332                 /*
16333                  * If props were setup ok, online the lun
16334                  */
16335                 if (ndi_rtn == NDI_SUCCESS) {
16336                         /*
16337                          * Try to online the new node
16338                          */
16339                         ndi_rtn = ndi_devi_online(*lun_dip, NDI_ONLINE_ATTACH);
16340                 }
16341                 if (ndi_rtn == NDI_SUCCESS) {
16342                         mutex_enter(&mpt->m_mutex);
16343                         ptgt->m_led_status = 0;
16344                         (void) mptsas_flush_led_status(mpt, ptgt);
16345                         mutex_exit(&mpt->m_mutex);
16346                 }
16347 
16348                 /*
16349                  * If success set rtn flag, else unwire alloc'd lun
16350                  */
16351                 if (ndi_rtn != NDI_SUCCESS) {
16352                         NDBG12(("unable to online "
16353                             "target %d lun %d", target, lun));
16354                         ndi_prop_remove_all(*lun_dip);
16355                         (void) ndi_devi_free(*lun_dip);
16356                         *lun_dip = NULL;
16357                 }
16358         }
16359 
16360         scsi_hba_nodename_compatible_free(nodename, compatible);
16361 








16362         return ((ndi_rtn == NDI_SUCCESS) ? DDI_SUCCESS : DDI_FAILURE);
16363 }
16364 
16365 static int
16366 mptsas_probe_smp(dev_info_t *pdip, uint64_t wwn)
16367 {
16368         mptsas_t        *mpt = DIP2MPT(pdip);
16369         struct smp_device smp_sd;
16370 
16371         /* XXX An HBA driver should not be allocating an smp_device. */
16372         bzero(&smp_sd, sizeof (struct smp_device));
16373         smp_sd.smp_sd_address.smp_a_hba_tran = mpt->m_smptran;
16374         bcopy(&wwn, smp_sd.smp_sd_address.smp_a_wwn, SAS_WWN_BYTE_SIZE);
16375 
16376         if (smp_probe(&smp_sd) != DDI_PROBE_SUCCESS)
16377                 return (NDI_FAILURE);
16378         return (NDI_SUCCESS);
16379 }
16380 
16381 static int


16412 {
16413         char            wwn_str[MPTSAS_WWN_STRLEN];
16414         char            attached_wwn_str[MPTSAS_WWN_STRLEN];
16415         int             ndi_rtn = NDI_FAILURE;
16416         int             rval = 0;
16417         mptsas_smp_t    dev_info;
16418         uint32_t        page_address;
16419         mptsas_t        *mpt = DIP2MPT(pdip);
16420         uint16_t        dev_hdl;
16421         uint64_t        sas_wwn;
16422         uint64_t        smp_sas_wwn;
16423         uint8_t         physport;
16424         uint8_t         phy_id;
16425         uint16_t        pdev_hdl;
16426         uint8_t         numphys = 0;
16427         uint16_t        i = 0;
16428         char            phymask[MPTSAS_MAX_PHYS];
16429         char            *iport = NULL;
16430         mptsas_phymask_t        phy_mask = 0;
16431         uint16_t        attached_devhdl;
16432         uint16_t        bay_num, enclosure, io_flags;
16433 
16434         (void) sprintf(wwn_str, "%"PRIx64, smp_node->m_addr.mta_wwn);
16435 
16436         /*
16437          * Probe smp device, prevent the node of removed device from being
16438          * configured succesfully
16439          */
16440         if (mptsas_probe_smp(pdip, smp_node->m_addr.mta_wwn) != NDI_SUCCESS) {
16441                 return (DDI_FAILURE);
16442         }
16443 
16444         if ((*smp_dip = mptsas_find_smp_child(pdip, wwn_str)) != NULL) {
16445                 return (DDI_SUCCESS);
16446         }
16447 
16448         ndi_rtn = ndi_devi_alloc(pdip, "smp", DEVI_SID_NODEID, smp_dip);
16449 
16450         /*
16451          * if lun alloc success, set props
16452          */


16479                 mutex_enter(&mpt->m_mutex);
16480 
16481                 page_address = (MPI2_SAS_EXPAND_PGAD_FORM_HNDL &
16482                     MPI2_SAS_EXPAND_PGAD_FORM_MASK) | smp_node->m_devhdl;
16483                 rval = mptsas_get_sas_expander_page0(mpt, page_address,
16484                     &dev_info);
16485                 if (rval != DDI_SUCCESS) {
16486                         mutex_exit(&mpt->m_mutex);
16487                         mptsas_log(mpt, CE_WARN,
16488                             "mptsas unable to get expander "
16489                             "parent device info for %x", page_address);
16490                         ndi_rtn = NDI_FAILURE;
16491                         goto smp_create_done;
16492                 }
16493 
16494                 smp_node->m_pdevhdl = dev_info.m_pdevhdl;
16495                 page_address = (MPI2_SAS_DEVICE_PGAD_FORM_HANDLE &
16496                     MPI2_SAS_DEVICE_PGAD_FORM_MASK) |
16497                     (uint32_t)dev_info.m_pdevhdl;
16498                 rval = mptsas_get_sas_device_page0(mpt, page_address,
16499                     &dev_hdl, &sas_wwn, &smp_node->m_pdevinfo, &physport,
16500                     &phy_id, &pdev_hdl, &bay_num, &enclosure, &io_flags);
16501                 if (rval != DDI_SUCCESS) {
16502                         mutex_exit(&mpt->m_mutex);
16503                         mptsas_log(mpt, CE_WARN, "mptsas unable to get "
16504                             "device info for %x", page_address);
16505                         ndi_rtn = NDI_FAILURE;
16506                         goto smp_create_done;
16507                 }
16508 
16509                 page_address = (MPI2_SAS_DEVICE_PGAD_FORM_HANDLE &
16510                     MPI2_SAS_DEVICE_PGAD_FORM_MASK) |
16511                     (uint32_t)dev_info.m_devhdl;
16512                 rval = mptsas_get_sas_device_page0(mpt, page_address,
16513                     &dev_hdl, &smp_sas_wwn, &smp_node->m_deviceinfo,
16514                     &physport, &phy_id, &pdev_hdl, &bay_num, &enclosure,
16515                     &io_flags);
16516                 if (rval != DDI_SUCCESS) {
16517                         mutex_exit(&mpt->m_mutex);
16518                         mptsas_log(mpt, CE_WARN, "mptsas unable to get "
16519                             "device info for %x", page_address);
16520                         ndi_rtn = NDI_FAILURE;
16521                         goto smp_create_done;
16522                 }
16523                 mutex_exit(&mpt->m_mutex);
16524 
16525                 /*
16526                  * If this smp direct attached to the controller
16527                  * set the attached-port to the base wwid
16528                  */
16529                 if ((smp_node->m_deviceinfo & DEVINFO_DIRECT_ATTACHED)
16530                     != DEVINFO_DIRECT_ATTACHED) {
16531                         (void) sprintf(attached_wwn_str, "w%016"PRIx64,
16532                             sas_wwn);
16533                 } else {
16534                         (void) sprintf(attached_wwn_str, "w%016"PRIx64,
16535                             mpt->un.m_base_wwid);


16649                 /*
16650                  * If success set rtn flag, else unwire alloc'd lun
16651                  */
16652                 if (ndi_rtn != NDI_SUCCESS) {
16653                         NDBG12(("mptsas unable to online "
16654                             "SMP target %s", wwn_str));
16655                         ndi_prop_remove_all(*smp_dip);
16656                         (void) ndi_devi_free(*smp_dip);
16657                 }
16658         }
16659 
16660         return ((ndi_rtn == NDI_SUCCESS) ? DDI_SUCCESS : DDI_FAILURE);
16661 }
16662 
16663 /* smp transport routine */
16664 static int mptsas_smp_start(struct smp_pkt *smp_pkt)
16665 {
16666         uint64_t                        wwn;
16667         Mpi2SmpPassthroughRequest_t     req;
16668         Mpi2SmpPassthroughReply_t       rep;
16669         uint8_t                         direction = 0;
16670         mptsas_t                        *mpt;
16671         int                             ret;
16672         uint64_t                        tmp64;
16673 
16674         mpt = (mptsas_t *)smp_pkt->smp_pkt_address->
16675             smp_a_hba_tran->smp_tran_hba_private;
16676 
16677         bcopy(smp_pkt->smp_pkt_address->smp_a_wwn, &wwn, SAS_WWN_BYTE_SIZE);
16678         /*
16679          * Need to compose a SMP request message
16680          * and call mptsas_do_passthru() function
16681          */
16682         bzero(&req, sizeof (req));
16683         bzero(&rep, sizeof (rep));
16684         req.PassthroughFlags = 0;
16685         req.PhysicalPort = 0xff;
16686         req.ChainOffset = 0;
16687         req.Function = MPI2_FUNCTION_SMP_PASSTHROUGH;
16688 
16689         if ((smp_pkt->smp_pkt_reqsize & 0xffff0000ul) != 0) {


16953                 NDBG20(("Hash item already exist"));
16954                 tmp_tgt->m_deviceinfo = devinfo;
16955                 tmp_tgt->m_devhdl = devhdl;  /* XXX - duplicate? */
16956                 return (tmp_tgt);
16957         }
16958         tmp_tgt = kmem_zalloc(sizeof (struct mptsas_target), KM_SLEEP);
16959         if (tmp_tgt == NULL) {
16960                 cmn_err(CE_WARN, "Fatal, allocated tgt failed");
16961                 return (NULL);
16962         }
16963         tmp_tgt->m_devhdl = devhdl;
16964         tmp_tgt->m_addr.mta_wwn = wwid;
16965         tmp_tgt->m_deviceinfo = devinfo;
16966         tmp_tgt->m_addr.mta_phymask = phymask;
16967         tmp_tgt->m_phynum = phynum;
16968         /* Initialized the tgt structure */
16969         tmp_tgt->m_qfull_retries = QFULL_RETRIES;
16970         tmp_tgt->m_qfull_retry_interval =
16971             drv_usectohz(QFULL_RETRY_INTERVAL * 1000);
16972         tmp_tgt->m_t_throttle = MAX_THROTTLE;
16973         mutex_init(&tmp_tgt->m_t_mutex, NULL, MUTEX_DRIVER, NULL);
16974         TAILQ_INIT(&tmp_tgt->m_active_cmdq);
16975 
16976         refhash_insert(mpt->m_targets, tmp_tgt);
16977 
16978         return (tmp_tgt);
16979 }
16980 
16981 static void
16982 mptsas_smp_target_copy(mptsas_smp_t *src, mptsas_smp_t *dst)
16983 {
16984         dst->m_devhdl = src->m_devhdl;
16985         dst->m_deviceinfo = src->m_deviceinfo;
16986         dst->m_pdevhdl = src->m_pdevhdl;
16987         dst->m_pdevinfo = src->m_pdevinfo;
16988 }
16989 
16990 static mptsas_smp_t *
16991 mptsas_smp_alloc(mptsas_t *mpt, mptsas_smp_t *data)
16992 {
16993         mptsas_target_addr_t addr;
16994         mptsas_smp_t *ret_data;
16995 
16996         addr.mta_wwn = data->m_addr.mta_wwn;
16997         addr.mta_phymask = data->m_addr.mta_phymask;
16998         ret_data = refhash_lookup(mpt->m_smp_targets, &addr);
16999         /*
17000          * If there's already a matching SMP target, update its fields
17001          * in place.  Since the address is not changing, it's safe to do
17002          * this.  We cannot just bcopy() here because the structure we've
17003          * been given has invalid hash links.
17004          */
17005         if (ret_data != NULL) {
17006                 mptsas_smp_target_copy(data, ret_data);
17007                 return (ret_data);
17008         }
17009 
17010         ret_data = kmem_alloc(sizeof (mptsas_smp_t), KM_SLEEP);
17011         bcopy(data, ret_data, sizeof (mptsas_smp_t));
17012         refhash_insert(mpt->m_smp_targets, ret_data);
17013         return (ret_data);
17014 }
17015 
17016 /*
17017  * Functions for SGPIO LED support
17018  */
17019 static dev_info_t *
17020 mptsas_get_dip_from_dev(dev_t dev, mptsas_phymask_t *phymask)
17021 {
17022         dev_info_t      *dip;
17023         int             prop;
17024         dip = e_ddi_hold_devi_by_dev(dev, 0);
17025         if (dip == NULL)
17026                 return (dip);


17150                 *status = LE_32(rep.SlotStatus);
17151         }
17152 
17153         return (0);
17154 }
17155 
17156 int
17157 mptsas_dma_addr_create(mptsas_t *mpt, ddi_dma_attr_t dma_attr,
17158     ddi_dma_handle_t *dma_hdp, ddi_acc_handle_t *acc_hdp, caddr_t *dma_memp,
17159     uint32_t alloc_size, ddi_dma_cookie_t *cookiep)
17160 {
17161         ddi_dma_cookie_t        new_cookie;
17162         size_t                  alloc_len;
17163         uint_t                  ncookie;
17164 
17165         if (cookiep == NULL)
17166                 cookiep = &new_cookie;
17167 
17168         if (ddi_dma_alloc_handle(mpt->m_dip, &dma_attr, DDI_DMA_SLEEP,
17169             NULL, dma_hdp) != DDI_SUCCESS) {

17170                 return (FALSE);
17171         }
17172 
17173         if (ddi_dma_mem_alloc(*dma_hdp, alloc_size, &mpt->m_dev_acc_attr,
17174             DDI_DMA_CONSISTENT, DDI_DMA_SLEEP, NULL, dma_memp, &alloc_len,
17175             acc_hdp) != DDI_SUCCESS) {
17176                 ddi_dma_free_handle(dma_hdp);

17177                 return (FALSE);
17178         }
17179 
17180         if (ddi_dma_addr_bind_handle(*dma_hdp, NULL, *dma_memp, alloc_len,
17181             (DDI_DMA_RDWR | DDI_DMA_CONSISTENT), DDI_DMA_SLEEP, NULL,
17182             cookiep, &ncookie) != DDI_DMA_MAPPED) {
17183                 (void) ddi_dma_mem_free(acc_hdp);
17184                 ddi_dma_free_handle(dma_hdp);

17185                 return (FALSE);
17186         }
17187 
17188         return (TRUE);
17189 }
17190 
17191 void
17192 mptsas_dma_addr_destroy(ddi_dma_handle_t *dma_hdp, ddi_acc_handle_t *acc_hdp)
17193 {
17194         if (*dma_hdp == NULL)
17195                 return;
17196 
17197         (void) ddi_dma_unbind_handle(*dma_hdp);
17198         (void) ddi_dma_mem_free(acc_hdp);
17199         ddi_dma_free_handle(dma_hdp);

17200 }