ciss.c revision 195534
1263320Sdim/*-
2263320Sdim * Copyright (c) 2001 Michael Smith
3263320Sdim * Copyright (c) 2004 Paul Saab
4263320Sdim * All rights reserved.
5263320Sdim *
6263320Sdim * Redistribution and use in source and binary forms, with or without
7263320Sdim * modification, are permitted provided that the following conditions
8263320Sdim * are met:
9263320Sdim * 1. Redistributions of source code must retain the above copyright
10263320Sdim *    notice, this list of conditions and the following disclaimer.
11263320Sdim * 2. Redistributions in binary form must reproduce the above copyright
12263320Sdim *    notice, this list of conditions and the following disclaimer in the
13263320Sdim *    documentation and/or other materials provided with the distribution.
14263320Sdim *
15263320Sdim * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16263320Sdim * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17263320Sdim * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18263320Sdim * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19263320Sdim * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20263320Sdim * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21263320Sdim * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22263320Sdim * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23263320Sdim * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24263320Sdim * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25263320Sdim * SUCH DAMAGE.
26263320Sdim *
27263320Sdim *	$FreeBSD: head/sys/dev/ciss/ciss.c 195534 2009-07-10 08:18:08Z scottl $
28263320Sdim */
29263320Sdim
30263320Sdim/*
31263320Sdim * Common Interface for SCSI-3 Support driver.
32263320Sdim *
33263320Sdim * CISS claims to provide a common interface between a generic SCSI
34263320Sdim * transport and an intelligent host adapter.
35263320Sdim *
36263320Sdim * This driver supports CISS as defined in the document "CISS Command
37263320Sdim * Interface for SCSI-3 Support Open Specification", Version 1.04,
38263320Sdim * Valence Number 1, dated 20001127, produced by Compaq Computer
39263320Sdim * Corporation.  This document appears to be a hastily and somewhat
40263320Sdim * arbitrarlily cut-down version of a larger (and probably even more
41263320Sdim * chaotic and inconsistent) Compaq internal document.  Various
42263320Sdim * details were also gleaned from Compaq's "cciss" driver for Linux.
43263320Sdim *
44263320Sdim * We provide a shim layer between the CISS interface and CAM,
45263320Sdim * offloading most of the queueing and being-a-disk chores onto CAM.
46263320Sdim * Entry to the driver is via the PCI bus attachment (ciss_probe,
47263320Sdim * ciss_attach, etc) and via the CAM interface (ciss_cam_action,
48263320Sdim * ciss_cam_poll).  The Compaq CISS adapters are, however, poor SCSI
49263320Sdim * citizens and we have to fake up some responses to get reasonable
50263320Sdim * behaviour out of them.  In addition, the CISS command set is by no
51263320Sdim * means adequate to support the functionality of a RAID controller,
52263320Sdim * and thus the supported Compaq adapters utilise portions of the
53263320Sdim * control protocol from earlier Compaq adapter families.
54263320Sdim *
55263320Sdim * Note that we only support the "simple" transport layer over PCI.
56263320Sdim * This interface (ab)uses the I2O register set (specifically the post
57263320Sdim * queues) to exchange commands with the adapter.  Other interfaces
58263320Sdim * are available, but we aren't supposed to know about them, and it is
59263320Sdim * dubious whether they would provide major performance improvements
60263320Sdim * except under extreme load.
61263320Sdim *
62263320Sdim * Currently the only supported CISS adapters are the Compaq Smart
63 * Array 5* series (5300, 5i, 532).  Even with only three adapters,
64 * Compaq still manage to have interface variations.
65 *
66 *
67 * Thanks must go to Fred Harris and Darryl DeVinney at Compaq, as
68 * well as Paul Saab at Yahoo! for their assistance in making this
69 * driver happen.
70 *
71 * More thanks must go to John Cagle at HP for the countless hours
72 * spent making this driver "work" with the MSA* series storage
73 * enclosures.  Without his help (and nagging), this driver could not
74 * be used with these enclosures.
75 */
76
77#include <sys/param.h>
78#include <sys/systm.h>
79#include <sys/malloc.h>
80#include <sys/kernel.h>
81#include <sys/bus.h>
82#include <sys/conf.h>
83#include <sys/stat.h>
84#include <sys/kthread.h>
85#include <sys/queue.h>
86#include <sys/sysctl.h>
87
88#include <cam/cam.h>
89#include <cam/cam_ccb.h>
90#include <cam/cam_periph.h>
91#include <cam/cam_sim.h>
92#include <cam/cam_xpt_sim.h>
93#include <cam/scsi/scsi_all.h>
94#include <cam/scsi/scsi_message.h>
95
96#include <machine/bus.h>
97#include <machine/endian.h>
98#include <machine/resource.h>
99#include <sys/rman.h>
100
101#include <dev/pci/pcireg.h>
102#include <dev/pci/pcivar.h>
103
104#include <dev/ciss/cissreg.h>
105#include <dev/ciss/cissio.h>
106#include <dev/ciss/cissvar.h>
107
108MALLOC_DEFINE(CISS_MALLOC_CLASS, "ciss_data", "ciss internal data buffers");
109
110/* pci interface */
111static int	ciss_lookup(device_t dev);
112static int	ciss_probe(device_t dev);
113static int	ciss_attach(device_t dev);
114static int	ciss_detach(device_t dev);
115static int	ciss_shutdown(device_t dev);
116
117/* (de)initialisation functions, control wrappers */
118static int	ciss_init_pci(struct ciss_softc *sc);
119static int	ciss_setup_msix(struct ciss_softc *sc);
120static int	ciss_init_perf(struct ciss_softc *sc);
121static int	ciss_wait_adapter(struct ciss_softc *sc);
122static int	ciss_flush_adapter(struct ciss_softc *sc);
123static int	ciss_init_requests(struct ciss_softc *sc);
124static void	ciss_command_map_helper(void *arg, bus_dma_segment_t *segs,
125					int nseg, int error);
126static int	ciss_identify_adapter(struct ciss_softc *sc);
127static int	ciss_init_logical(struct ciss_softc *sc);
128static int	ciss_init_physical(struct ciss_softc *sc);
129static int	ciss_filter_physical(struct ciss_softc *sc, struct ciss_lun_report *cll);
130static int	ciss_identify_logical(struct ciss_softc *sc, struct ciss_ldrive *ld);
131static int	ciss_get_ldrive_status(struct ciss_softc *sc,  struct ciss_ldrive *ld);
132static int	ciss_update_config(struct ciss_softc *sc);
133static int	ciss_accept_media(struct ciss_softc *sc, struct ciss_ldrive *ld);
134static void	ciss_init_sysctl(struct ciss_softc *sc);
135static void	ciss_soft_reset(struct ciss_softc *sc);
136static void	ciss_free(struct ciss_softc *sc);
137static void	ciss_spawn_notify_thread(struct ciss_softc *sc);
138static void	ciss_kill_notify_thread(struct ciss_softc *sc);
139
140/* request submission/completion */
141static int	ciss_start(struct ciss_request *cr);
142static void	ciss_done(struct ciss_softc *sc, cr_qhead_t *qh);
143static void	ciss_perf_done(struct ciss_softc *sc, cr_qhead_t *qh);
144static void	ciss_intr(void *arg);
145static void	ciss_perf_intr(void *arg);
146static void	ciss_perf_msi_intr(void *arg);
147static void	ciss_complete(struct ciss_softc *sc, cr_qhead_t *qh);
148static int	_ciss_report_request(struct ciss_request *cr, int *command_status, int *scsi_status, const char *func);
149static int	ciss_synch_request(struct ciss_request *cr, int timeout);
150static int	ciss_poll_request(struct ciss_request *cr, int timeout);
151static int	ciss_wait_request(struct ciss_request *cr, int timeout);
152#if 0
153static int	ciss_abort_request(struct ciss_request *cr);
154#endif
155
156/* request queueing */
157static int	ciss_get_request(struct ciss_softc *sc, struct ciss_request **crp);
158static void	ciss_preen_command(struct ciss_request *cr);
159static void 	ciss_release_request(struct ciss_request *cr);
160
161/* request helpers */
162static int	ciss_get_bmic_request(struct ciss_softc *sc, struct ciss_request **crp,
163				      int opcode, void **bufp, size_t bufsize);
164static int	ciss_user_command(struct ciss_softc *sc, IOCTL_Command_struct *ioc);
165
166/* DMA map/unmap */
167static int	ciss_map_request(struct ciss_request *cr);
168static void	ciss_request_map_helper(void *arg, bus_dma_segment_t *segs,
169					int nseg, int error);
170static void	ciss_unmap_request(struct ciss_request *cr);
171
172/* CAM interface */
173static int	ciss_cam_init(struct ciss_softc *sc);
174static void	ciss_cam_rescan_target(struct ciss_softc *sc,
175				       int bus, int target);
176static void	ciss_cam_rescan_all(struct ciss_softc *sc);
177static void	ciss_cam_rescan_callback(struct cam_periph *periph, union ccb *ccb);
178static void	ciss_cam_action(struct cam_sim *sim, union ccb *ccb);
179static int	ciss_cam_action_io(struct cam_sim *sim, struct ccb_scsiio *csio);
180static int	ciss_cam_emulate(struct ciss_softc *sc, struct ccb_scsiio *csio);
181static void	ciss_cam_poll(struct cam_sim *sim);
182static void	ciss_cam_complete(struct ciss_request *cr);
183static void	ciss_cam_complete_fixup(struct ciss_softc *sc, struct ccb_scsiio *csio);
184static struct cam_periph *ciss_find_periph(struct ciss_softc *sc,
185					   int bus, int target);
186static int	ciss_name_device(struct ciss_softc *sc, int bus, int target);
187
188/* periodic status monitoring */
189static void	ciss_periodic(void *arg);
190static void	ciss_nop_complete(struct ciss_request *cr);
191static void	ciss_disable_adapter(struct ciss_softc *sc);
192static void	ciss_notify_event(struct ciss_softc *sc);
193static void	ciss_notify_complete(struct ciss_request *cr);
194static int	ciss_notify_abort(struct ciss_softc *sc);
195static int	ciss_notify_abort_bmic(struct ciss_softc *sc);
196static void	ciss_notify_hotplug(struct ciss_softc *sc, struct ciss_notify *cn);
197static void	ciss_notify_logical(struct ciss_softc *sc, struct ciss_notify *cn);
198static void	ciss_notify_physical(struct ciss_softc *sc, struct ciss_notify *cn);
199
200/* debugging output */
201static void	ciss_print_request(struct ciss_request *cr);
202static void	ciss_print_ldrive(struct ciss_softc *sc, struct ciss_ldrive *ld);
203static const char *ciss_name_ldrive_status(int status);
204static int	ciss_decode_ldrive_status(int status);
205static const char *ciss_name_ldrive_org(int org);
206static const char *ciss_name_command_status(int status);
207
208/*
209 * PCI bus interface.
210 */
211static device_method_t ciss_methods[] = {
212    /* Device interface */
213    DEVMETHOD(device_probe,	ciss_probe),
214    DEVMETHOD(device_attach,	ciss_attach),
215    DEVMETHOD(device_detach,	ciss_detach),
216    DEVMETHOD(device_shutdown,	ciss_shutdown),
217    { 0, 0 }
218};
219
220static driver_t ciss_pci_driver = {
221    "ciss",
222    ciss_methods,
223    sizeof(struct ciss_softc)
224};
225
226static devclass_t	ciss_devclass;
227DRIVER_MODULE(ciss, pci, ciss_pci_driver, ciss_devclass, 0, 0);
228MODULE_DEPEND(ciss, cam, 1, 1, 1);
229MODULE_DEPEND(ciss, pci, 1, 1, 1);
230
231/*
232 * Control device interface.
233 */
234static d_open_t		ciss_open;
235static d_close_t	ciss_close;
236static d_ioctl_t	ciss_ioctl;
237
238static struct cdevsw ciss_cdevsw = {
239	.d_version =	D_VERSION,
240	.d_flags =	0,
241	.d_open =	ciss_open,
242	.d_close =	ciss_close,
243	.d_ioctl =	ciss_ioctl,
244	.d_name =	"ciss",
245};
246
247/*
248 * This tunable can be set at boot time and controls whether physical devices
249 * that are marked hidden by the firmware should be exposed anyways.
250 */
251static unsigned int ciss_expose_hidden_physical = 0;
252TUNABLE_INT("hw.ciss.expose_hidden_physical", &ciss_expose_hidden_physical);
253
254static unsigned int ciss_nop_message_heartbeat = 0;
255TUNABLE_INT("hw.ciss.nop_message_heartbeat", &ciss_nop_message_heartbeat);
256
257/*
258 * This tunable can force a particular transport to be used:
259 * <= 0 : use default
260 *    1 : force simple
261 *    2 : force performant
262 */
263static int ciss_force_transport = 0;
264TUNABLE_INT("hw.ciss.force_transport", &ciss_force_transport);
265
266/*
267 * This tunable can force a particular interrupt delivery method to be used:
268 * <= 0 : use default
269 *    1 : force INTx
270 *    2 : force MSIX
271 */
272static int ciss_force_interrupt = 0;
273TUNABLE_INT("hw.ciss.force_interrupt", &ciss_force_interrupt);
274
275/************************************************************************
276 * CISS adapters amazingly don't have a defined programming interface
277 * value.  (One could say some very despairing things about PCI and
278 * people just not getting the general idea.)  So we are forced to
279 * stick with matching against subvendor/subdevice, and thus have to
280 * be updated for every new CISS adapter that appears.
281 */
282#define CISS_BOARD_SA5	(1<<0)
283#define CISS_BOARD_SA5B	(1<<1)
284
285static struct
286{
287    u_int16_t	subvendor;
288    u_int16_t	subdevice;
289    int		flags;
290    char	*desc;
291} ciss_vendor_data[] = {
292    { 0x0e11, 0x4070, CISS_BOARD_SA5,	"Compaq Smart Array 5300" },
293    { 0x0e11, 0x4080, CISS_BOARD_SA5B,	"Compaq Smart Array 5i" },
294    { 0x0e11, 0x4082, CISS_BOARD_SA5B,	"Compaq Smart Array 532" },
295    { 0x0e11, 0x4083, CISS_BOARD_SA5B,	"HP Smart Array 5312" },
296    { 0x0e11, 0x4091, CISS_BOARD_SA5,	"HP Smart Array 6i" },
297    { 0x0e11, 0x409A, CISS_BOARD_SA5,	"HP Smart Array 641" },
298    { 0x0e11, 0x409B, CISS_BOARD_SA5,	"HP Smart Array 642" },
299    { 0x0e11, 0x409C, CISS_BOARD_SA5,	"HP Smart Array 6400" },
300    { 0x0e11, 0x409D, CISS_BOARD_SA5,	"HP Smart Array 6400 EM" },
301    { 0x103C, 0x3211, CISS_BOARD_SA5,	"HP Smart Array E200i" },
302    { 0x103C, 0x3212, CISS_BOARD_SA5,	"HP Smart Array E200" },
303    { 0x103C, 0x3213, CISS_BOARD_SA5,	"HP Smart Array E200i" },
304    { 0x103C, 0x3214, CISS_BOARD_SA5,	"HP Smart Array E200i" },
305    { 0x103C, 0x3215, CISS_BOARD_SA5,	"HP Smart Array E200i" },
306    { 0x103C, 0x3220, CISS_BOARD_SA5,	"HP Smart Array" },
307    { 0x103C, 0x3222, CISS_BOARD_SA5,	"HP Smart Array" },
308    { 0x103C, 0x3223, CISS_BOARD_SA5,	"HP Smart Array P800" },
309    { 0x103C, 0x3225, CISS_BOARD_SA5,	"HP Smart Array P600" },
310    { 0x103C, 0x3230, CISS_BOARD_SA5,	"HP Smart Array" },
311    { 0x103C, 0x3231, CISS_BOARD_SA5,	"HP Smart Array" },
312    { 0x103C, 0x3232, CISS_BOARD_SA5,	"HP Smart Array" },
313    { 0x103C, 0x3233, CISS_BOARD_SA5,	"HP Smart Array" },
314    { 0x103C, 0x3234, CISS_BOARD_SA5,	"HP Smart Array P400" },
315    { 0x103C, 0x3235, CISS_BOARD_SA5,	"HP Smart Array P400i" },
316    { 0x103C, 0x3236, CISS_BOARD_SA5,	"HP Smart Array" },
317    { 0x103C, 0x3237, CISS_BOARD_SA5,	"HP Smart Array E500" },
318    { 0x103C, 0x3238, CISS_BOARD_SA5,	"HP Smart Array" },
319    { 0x103C, 0x3239, CISS_BOARD_SA5,	"HP Smart Array" },
320    { 0x103C, 0x323A, CISS_BOARD_SA5,	"HP Smart Array" },
321    { 0x103C, 0x323B, CISS_BOARD_SA5,	"HP Smart Array" },
322    { 0x103C, 0x323C, CISS_BOARD_SA5,	"HP Smart Array" },
323    { 0x103C, 0x323D, CISS_BOARD_SA5,	"HP Smart Array P700m" },
324    { 0x103C, 0x3241, CISS_BOARD_SA5,	"HP Smart Array P212" },
325    { 0x103C, 0x3243, CISS_BOARD_SA5,	"HP Smart Array P410" },
326    { 0x103C, 0x3245, CISS_BOARD_SA5,	"HP Smart Array P410i" },
327    { 0x103C, 0x3247, CISS_BOARD_SA5,	"HP Smart Array P411" },
328    { 0x103C, 0x3249, CISS_BOARD_SA5,	"HP Smart Array P812" },
329    { 0x103C, 0x324A, CISS_BOARD_SA5,	"HP Smart Array P712m" },
330    { 0x103C, 0x324B, CISS_BOARD_SA5,	"HP Smart Array" },
331    { 0, 0, 0, NULL }
332};
333
334/************************************************************************
335 * Find a match for the device in our list of known adapters.
336 */
337static int
338ciss_lookup(device_t dev)
339{
340    int 	i;
341
342    for (i = 0; ciss_vendor_data[i].desc != NULL; i++)
343	if ((pci_get_subvendor(dev) == ciss_vendor_data[i].subvendor) &&
344	    (pci_get_subdevice(dev) == ciss_vendor_data[i].subdevice)) {
345	    return(i);
346	}
347    return(-1);
348}
349
350/************************************************************************
351 * Match a known CISS adapter.
352 */
353static int
354ciss_probe(device_t dev)
355{
356    int		i;
357
358    i = ciss_lookup(dev);
359    if (i != -1) {
360	device_set_desc(dev, ciss_vendor_data[i].desc);
361	return(BUS_PROBE_DEFAULT);
362    }
363    return(ENOENT);
364}
365
366/************************************************************************
367 * Attach the driver to this adapter.
368 */
369static int
370ciss_attach(device_t dev)
371{
372    struct ciss_softc	*sc;
373    int			error;
374
375    debug_called(1);
376
377#ifdef CISS_DEBUG
378    /* print structure/union sizes */
379    debug_struct(ciss_command);
380    debug_struct(ciss_header);
381    debug_union(ciss_device_address);
382    debug_struct(ciss_cdb);
383    debug_struct(ciss_report_cdb);
384    debug_struct(ciss_notify_cdb);
385    debug_struct(ciss_notify);
386    debug_struct(ciss_message_cdb);
387    debug_struct(ciss_error_info_pointer);
388    debug_struct(ciss_error_info);
389    debug_struct(ciss_sg_entry);
390    debug_struct(ciss_config_table);
391    debug_struct(ciss_bmic_cdb);
392    debug_struct(ciss_bmic_id_ldrive);
393    debug_struct(ciss_bmic_id_lstatus);
394    debug_struct(ciss_bmic_id_table);
395    debug_struct(ciss_bmic_id_pdrive);
396    debug_struct(ciss_bmic_blink_pdrive);
397    debug_struct(ciss_bmic_flush_cache);
398    debug_const(CISS_MAX_REQUESTS);
399    debug_const(CISS_MAX_LOGICAL);
400    debug_const(CISS_INTERRUPT_COALESCE_DELAY);
401    debug_const(CISS_INTERRUPT_COALESCE_COUNT);
402    debug_const(CISS_COMMAND_ALLOC_SIZE);
403    debug_const(CISS_COMMAND_SG_LENGTH);
404
405    debug_type(cciss_pci_info_struct);
406    debug_type(cciss_coalint_struct);
407    debug_type(cciss_coalint_struct);
408    debug_type(NodeName_type);
409    debug_type(NodeName_type);
410    debug_type(Heartbeat_type);
411    debug_type(BusTypes_type);
412    debug_type(FirmwareVer_type);
413    debug_type(DriverVer_type);
414    debug_type(IOCTL_Command_struct);
415#endif
416
417    sc = device_get_softc(dev);
418    sc->ciss_dev = dev;
419
420    /*
421     * Do PCI-specific init.
422     */
423    if ((error = ciss_init_pci(sc)) != 0)
424	goto out;
425
426    /*
427     * Initialise driver queues.
428     */
429    ciss_initq_free(sc);
430    ciss_initq_notify(sc);
431    mtx_init(&sc->ciss_mtx, "cissmtx", NULL, MTX_DEF);
432    callout_init_mtx(&sc->ciss_periodic, &sc->ciss_mtx, 0);
433
434    /*
435     * Initalize device sysctls.
436     */
437    ciss_init_sysctl(sc);
438
439    /*
440     * Initialise command/request pool.
441     */
442    if ((error = ciss_init_requests(sc)) != 0)
443	goto out;
444
445    /*
446     * Get adapter information.
447     */
448    if ((error = ciss_identify_adapter(sc)) != 0)
449	goto out;
450
451    /*
452     * Find all the physical devices.
453     */
454    if ((error = ciss_init_physical(sc)) != 0)
455	goto out;
456
457    /*
458     * Build our private table of logical devices.
459     */
460    if ((error = ciss_init_logical(sc)) != 0)
461	goto out;
462
463    /*
464     * Enable interrupts so that the CAM scan can complete.
465     */
466    CISS_TL_SIMPLE_ENABLE_INTERRUPTS(sc);
467
468    /*
469     * Initialise the CAM interface.
470     */
471    if ((error = ciss_cam_init(sc)) != 0)
472	goto out;
473
474    /*
475     * Start the heartbeat routine and event chain.
476     */
477    ciss_periodic(sc);
478
479   /*
480     * Create the control device.
481     */
482    sc->ciss_dev_t = make_dev(&ciss_cdevsw, device_get_unit(sc->ciss_dev),
483			      UID_ROOT, GID_OPERATOR, S_IRUSR | S_IWUSR,
484			      "ciss%d", device_get_unit(sc->ciss_dev));
485    sc->ciss_dev_t->si_drv1 = sc;
486
487    /*
488     * The adapter is running; synchronous commands can now sleep
489     * waiting for an interrupt to signal completion.
490     */
491    sc->ciss_flags |= CISS_FLAG_RUNNING;
492
493    ciss_spawn_notify_thread(sc);
494
495    error = 0;
496 out:
497    if (error != 0)
498	ciss_free(sc);
499    return(error);
500}
501
502/************************************************************************
503 * Detach the driver from this adapter.
504 */
505static int
506ciss_detach(device_t dev)
507{
508    struct ciss_softc	*sc = device_get_softc(dev);
509
510    debug_called(1);
511
512    mtx_lock(&sc->ciss_mtx);
513    if (sc->ciss_flags & CISS_FLAG_CONTROL_OPEN) {
514	mtx_unlock(&sc->ciss_mtx);
515	return (EBUSY);
516    }
517
518    /* flush adapter cache */
519    ciss_flush_adapter(sc);
520
521    /* release all resources.  The mutex is released and freed here too. */
522    ciss_free(sc);
523
524    return(0);
525}
526
527/************************************************************************
528 * Prepare adapter for system shutdown.
529 */
530static int
531ciss_shutdown(device_t dev)
532{
533    struct ciss_softc	*sc = device_get_softc(dev);
534
535    debug_called(1);
536
537    mtx_lock(&sc->ciss_mtx);
538    /* flush adapter cache */
539    ciss_flush_adapter(sc);
540
541    if (sc->ciss_soft_reset)
542	ciss_soft_reset(sc);
543    mtx_unlock(&sc->ciss_mtx);
544
545    return(0);
546}
547
548static void
549ciss_init_sysctl(struct ciss_softc *sc)
550{
551
552    SYSCTL_ADD_INT(device_get_sysctl_ctx(sc->ciss_dev),
553	SYSCTL_CHILDREN(device_get_sysctl_tree(sc->ciss_dev)),
554	OID_AUTO, "soft_reset", CTLFLAG_RW, &sc->ciss_soft_reset, 0, "");
555}
556
557/************************************************************************
558 * Perform PCI-specific attachment actions.
559 */
560static int
561ciss_init_pci(struct ciss_softc *sc)
562{
563    uintptr_t		cbase, csize, cofs;
564    uint32_t		method, supported_methods;
565    int			error, sqmask, i;
566    void		*intr;
567
568    debug_called(1);
569
570    /*
571     * Work out adapter type.
572     */
573    i = ciss_lookup(sc->ciss_dev);
574    if (i < 0) {
575	ciss_printf(sc, "unknown adapter type\n");
576	return (ENXIO);
577    }
578
579    if (ciss_vendor_data[i].flags & CISS_BOARD_SA5) {
580	sqmask = CISS_TL_SIMPLE_INTR_OPQ_SA5;
581    } else if (ciss_vendor_data[i].flags & CISS_BOARD_SA5B) {
582	sqmask = CISS_TL_SIMPLE_INTR_OPQ_SA5B;
583    } else {
584	/*
585	 * XXX Big hammer, masks/unmasks all possible interrupts.  This should
586	 * work on all hardware variants.  Need to add code to handle the
587	 * "controller crashed" interupt bit that this unmasks.
588	 */
589	sqmask = ~0;
590    }
591
592    /*
593     * Allocate register window first (we need this to find the config
594     * struct).
595     */
596    error = ENXIO;
597    sc->ciss_regs_rid = CISS_TL_SIMPLE_BAR_REGS;
598    if ((sc->ciss_regs_resource =
599	 bus_alloc_resource_any(sc->ciss_dev, SYS_RES_MEMORY,
600				&sc->ciss_regs_rid, RF_ACTIVE)) == NULL) {
601	ciss_printf(sc, "can't allocate register window\n");
602	return(ENXIO);
603    }
604    sc->ciss_regs_bhandle = rman_get_bushandle(sc->ciss_regs_resource);
605    sc->ciss_regs_btag = rman_get_bustag(sc->ciss_regs_resource);
606
607    /*
608     * Find the BAR holding the config structure.  If it's not the one
609     * we already mapped for registers, map it too.
610     */
611    sc->ciss_cfg_rid = CISS_TL_SIMPLE_READ(sc, CISS_TL_SIMPLE_CFG_BAR) & 0xffff;
612    if (sc->ciss_cfg_rid != sc->ciss_regs_rid) {
613	if ((sc->ciss_cfg_resource =
614	     bus_alloc_resource_any(sc->ciss_dev, SYS_RES_MEMORY,
615				    &sc->ciss_cfg_rid, RF_ACTIVE)) == NULL) {
616	    ciss_printf(sc, "can't allocate config window\n");
617	    return(ENXIO);
618	}
619	cbase = (uintptr_t)rman_get_virtual(sc->ciss_cfg_resource);
620	csize = rman_get_end(sc->ciss_cfg_resource) -
621	    rman_get_start(sc->ciss_cfg_resource) + 1;
622    } else {
623	cbase = (uintptr_t)rman_get_virtual(sc->ciss_regs_resource);
624	csize = rman_get_end(sc->ciss_regs_resource) -
625	    rman_get_start(sc->ciss_regs_resource) + 1;
626    }
627    cofs = CISS_TL_SIMPLE_READ(sc, CISS_TL_SIMPLE_CFG_OFF);
628
629    /*
630     * Use the base/size/offset values we just calculated to
631     * sanity-check the config structure.  If it's OK, point to it.
632     */
633    if ((cofs + sizeof(struct ciss_config_table)) > csize) {
634	ciss_printf(sc, "config table outside window\n");
635	return(ENXIO);
636    }
637    sc->ciss_cfg = (struct ciss_config_table *)(cbase + cofs);
638    debug(1, "config struct at %p", sc->ciss_cfg);
639
640    /*
641     * Calculate the number of request structures/commands we are
642     * going to provide for this adapter.
643     */
644    sc->ciss_max_requests = min(CISS_MAX_REQUESTS, sc->ciss_cfg->max_outstanding_commands);
645
646    /*
647     * Validate the config structure.  If we supported other transport
648     * methods, we could select amongst them at this point in time.
649     */
650    if (strncmp(sc->ciss_cfg->signature, "CISS", 4)) {
651	ciss_printf(sc, "config signature mismatch (got '%c%c%c%c')\n",
652		    sc->ciss_cfg->signature[0], sc->ciss_cfg->signature[1],
653		    sc->ciss_cfg->signature[2], sc->ciss_cfg->signature[3]);
654	return(ENXIO);
655    }
656
657    /*
658     * Select the mode of operation, prefer Performant.
659     */
660    if (!(sc->ciss_cfg->supported_methods &
661	(CISS_TRANSPORT_METHOD_SIMPLE | CISS_TRANSPORT_METHOD_PERF))) {
662	ciss_printf(sc, "No supported transport layers: 0x%x\n",
663	    sc->ciss_cfg->supported_methods);
664	return(ENXIO);
665    }
666
667    switch (ciss_force_transport) {
668    case 1:
669	supported_methods = CISS_TRANSPORT_METHOD_SIMPLE;
670	break;
671    case 2:
672	supported_methods = CISS_TRANSPORT_METHOD_PERF;
673	break;
674    default:
675	supported_methods = sc->ciss_cfg->supported_methods;
676	break;
677    }
678
679setup:
680    if (supported_methods & CISS_TRANSPORT_METHOD_PERF) {
681	method = CISS_TRANSPORT_METHOD_PERF;
682	sc->ciss_perf = (struct ciss_perf_config *)(cbase + cofs +
683	    sc->ciss_cfg->transport_offset);
684	if (ciss_init_perf(sc)) {
685	    supported_methods &= ~method;
686	    goto setup;
687	}
688    } else if (supported_methods & CISS_TRANSPORT_METHOD_SIMPLE) {
689	method = CISS_TRANSPORT_METHOD_SIMPLE;
690    } else {
691	ciss_printf(sc, "No supported transport methods: 0x%x\n",
692	    sc->ciss_cfg->supported_methods);
693	return(ENXIO);
694    }
695
696    /*
697     * Tell it we're using the low 4GB of RAM.  Set the default interrupt
698     * coalescing options.
699     */
700    sc->ciss_cfg->requested_method = method;
701    sc->ciss_cfg->command_physlimit = 0;
702    sc->ciss_cfg->interrupt_coalesce_delay = CISS_INTERRUPT_COALESCE_DELAY;
703    sc->ciss_cfg->interrupt_coalesce_count = CISS_INTERRUPT_COALESCE_COUNT;
704
705#ifdef __i386__
706    sc->ciss_cfg->host_driver |= CISS_DRIVER_SCSI_PREFETCH;
707#endif
708
709    if (ciss_update_config(sc)) {
710	ciss_printf(sc, "adapter refuses to accept config update (IDBR 0x%x)\n",
711		    CISS_TL_SIMPLE_READ(sc, CISS_TL_SIMPLE_IDBR));
712	return(ENXIO);
713    }
714    if ((sc->ciss_cfg->active_method & method) == 0) {
715	supported_methods &= ~method;
716	if (supported_methods == 0) {
717	    ciss_printf(sc, "adapter refuses to go into available transports "
718		"mode (0x%x, 0x%x)\n", supported_methods,
719		sc->ciss_cfg->active_method);
720	    return(ENXIO);
721	} else
722	    goto setup;
723    }
724
725    /*
726     * Wait for the adapter to come ready.
727     */
728    if ((error = ciss_wait_adapter(sc)) != 0)
729	return(error);
730
731    /* Prepare to possibly use MSIX and/or PERFORMANT interrupts.  Normal
732     * interrupts have a rid of 0, this will be overridden if MSIX is used.
733     */
734    sc->ciss_irq_rid[0] = 0;
735    if (method == CISS_TRANSPORT_METHOD_PERF) {
736	ciss_printf(sc, "PERFORMANT Transport\n");
737	if ((ciss_force_interrupt != 1) && (ciss_setup_msix(sc) == 0)) {
738	    intr = ciss_perf_msi_intr;
739	    sc->ciss_interrupt_mask = CISS_TL_PERF_INTR_MSI;
740	} else {
741	    intr = ciss_perf_intr;
742	    sc->ciss_interrupt_mask = CISS_TL_PERF_INTR_OPQ;
743	}
744    } else {
745	ciss_printf(sc, "SIMPLE Transport\n");
746	/* MSIX doesn't seem to work in SIMPLE mode, only enable if it forced */
747	if (ciss_force_interrupt == 2)
748	    /* If this fails, we automatically revert to INTx */
749	    ciss_setup_msix(sc);
750	sc->ciss_perf = NULL;
751	intr = ciss_intr;
752	sc->ciss_interrupt_mask = sqmask;
753    }
754
755    /*
756     * Turn off interrupts before we go routing anything.
757     */
758    CISS_TL_SIMPLE_DISABLE_INTERRUPTS(sc);
759
760    /*
761     * Allocate and set up our interrupt.
762     */
763    if ((sc->ciss_irq_resource =
764	 bus_alloc_resource_any(sc->ciss_dev, SYS_RES_IRQ, &sc->ciss_irq_rid[0],
765				RF_ACTIVE | RF_SHAREABLE)) == NULL) {
766	ciss_printf(sc, "can't allocate interrupt\n");
767	return(ENXIO);
768    }
769
770    if (bus_setup_intr(sc->ciss_dev, sc->ciss_irq_resource,
771		       INTR_TYPE_CAM|INTR_MPSAFE, NULL, intr, sc,
772		       &sc->ciss_intr)) {
773	ciss_printf(sc, "can't set up interrupt\n");
774	return(ENXIO);
775    }
776
777    /*
778     * Allocate the parent bus DMA tag appropriate for our PCI
779     * interface.
780     *
781     * Note that "simple" adapters can only address within a 32-bit
782     * span.
783     */
784    if (bus_dma_tag_create(NULL, 			/* parent */
785			   1, 0, 			/* alignment, boundary */
786			   BUS_SPACE_MAXADDR,		/* lowaddr */
787			   BUS_SPACE_MAXADDR, 		/* highaddr */
788			   NULL, NULL, 			/* filter, filterarg */
789			   BUS_SPACE_MAXSIZE_32BIT,	/* maxsize */
790			   CISS_COMMAND_SG_LENGTH,	/* nsegments */
791			   BUS_SPACE_MAXSIZE_32BIT,	/* maxsegsize */
792			   0,				/* flags */
793			   NULL, NULL,			/* lockfunc, lockarg */
794			   &sc->ciss_parent_dmat)) {
795	ciss_printf(sc, "can't allocate parent DMA tag\n");
796	return(ENOMEM);
797    }
798
799    /*
800     * Create DMA tag for mapping buffers into adapter-addressable
801     * space.
802     */
803    if (bus_dma_tag_create(sc->ciss_parent_dmat, 	/* parent */
804			   1, 0, 			/* alignment, boundary */
805			   BUS_SPACE_MAXADDR,		/* lowaddr */
806			   BUS_SPACE_MAXADDR, 		/* highaddr */
807			   NULL, NULL, 			/* filter, filterarg */
808			   MAXBSIZE, CISS_COMMAND_SG_LENGTH,	/* maxsize, nsegments */
809			   BUS_SPACE_MAXSIZE_32BIT,	/* maxsegsize */
810			   BUS_DMA_ALLOCNOW,		/* flags */
811			   busdma_lock_mutex, &sc->ciss_mtx,	/* lockfunc, lockarg */
812			   &sc->ciss_buffer_dmat)) {
813	ciss_printf(sc, "can't allocate buffer DMA tag\n");
814	return(ENOMEM);
815    }
816    return(0);
817}
818
819/************************************************************************
820 * Setup MSI/MSIX operation (Performant only)
821 * Four interrupts are available, but we only use 1 right now.
822 */
823static int
824ciss_setup_msix(struct ciss_softc *sc)
825{
826    uint32_t id;
827    int val, i;
828
829    /* Weed out devices that don't actually support MSI */
830    id = (pci_get_subvendor(sc->ciss_dev) << 16) |
831	pci_get_subdevice(sc->ciss_dev);
832    if ((id == 0x0e114070) || (id == 0x0e114080) || (id == 0x0e114082) ||
833	(id == 0x0e114083))
834	return (EINVAL);
835
836    val = pci_msix_count(sc->ciss_dev);
837    if ((val != CISS_MSI_COUNT) || (pci_alloc_msix(sc->ciss_dev, &val) != 0))
838	return (EINVAL);
839
840    sc->ciss_msi = val;
841    ciss_printf(sc, "Using MSIX interrupt\n");
842
843    for (i = 0; i < CISS_MSI_COUNT; i++)
844	sc->ciss_irq_rid[i] = i + 1;
845
846    return (0);
847
848}
849
850/************************************************************************
851 * Setup the Performant structures.
852 */
853static int
854ciss_init_perf(struct ciss_softc *sc)
855{
856    struct ciss_perf_config *pc = sc->ciss_perf;
857    int reply_size;
858
859    /*
860     * Create the DMA tag for the reply queue.
861     */
862    reply_size = sizeof(uint64_t) * sc->ciss_max_requests;
863    if (bus_dma_tag_create(sc->ciss_parent_dmat,	/* parent */
864			   1, 0, 			/* alignment, boundary */
865			   BUS_SPACE_MAXADDR_32BIT,	/* lowaddr */
866			   BUS_SPACE_MAXADDR, 		/* highaddr */
867			   NULL, NULL, 			/* filter, filterarg */
868			   reply_size, 1,		/* maxsize, nsegments */
869			   BUS_SPACE_MAXSIZE_32BIT,	/* maxsegsize */
870			   0,				/* flags */
871			   NULL, NULL,			/* lockfunc, lockarg */
872			   &sc->ciss_reply_dmat)) {
873	ciss_printf(sc, "can't allocate reply DMA tag\n");
874	return(ENOMEM);
875    }
876    /*
877     * Allocate memory and make it available for DMA.
878     */
879    if (bus_dmamem_alloc(sc->ciss_reply_dmat, (void **)&sc->ciss_reply,
880			 BUS_DMA_NOWAIT, &sc->ciss_reply_map)) {
881	ciss_printf(sc, "can't allocate reply memory\n");
882	return(ENOMEM);
883    }
884    bus_dmamap_load(sc->ciss_reply_dmat, sc->ciss_reply_map, sc->ciss_reply,
885		    reply_size, ciss_command_map_helper, &sc->ciss_reply_phys, 0);
886    bzero(sc->ciss_reply, reply_size);
887
888    sc->ciss_cycle = 0x1;
889    sc->ciss_rqidx = 0;
890
891    /*
892     * Preload the fetch table with common command sizes.  This allows the
893     * hardware to not waste bus cycles for typical i/o commands, but also not
894     * tax the driver to be too exact in choosing sizes.  The table is optimized
895     * for page-aligned i/o's, but since most i/o comes from the various pagers,
896     * it's a reasonable assumption to make.
897     */
898    pc->fetch_count[CISS_SG_FETCH_NONE] = (sizeof(struct ciss_command) + 15) / 16;
899    pc->fetch_count[CISS_SG_FETCH_1] =
900	(sizeof(struct ciss_command) + sizeof(struct ciss_sg_entry) * 1 + 15) / 16;
901    pc->fetch_count[CISS_SG_FETCH_2] =
902	(sizeof(struct ciss_command) + sizeof(struct ciss_sg_entry) * 2 + 15) / 16;
903    pc->fetch_count[CISS_SG_FETCH_4] =
904	(sizeof(struct ciss_command) + sizeof(struct ciss_sg_entry) * 4 + 15) / 16;
905    pc->fetch_count[CISS_SG_FETCH_8] =
906	(sizeof(struct ciss_command) + sizeof(struct ciss_sg_entry) * 8 + 15) / 16;
907    pc->fetch_count[CISS_SG_FETCH_16] =
908	(sizeof(struct ciss_command) + sizeof(struct ciss_sg_entry) * 16 + 15) / 16;
909    pc->fetch_count[CISS_SG_FETCH_32] =
910	(sizeof(struct ciss_command) + sizeof(struct ciss_sg_entry) * 32 + 15) / 16;
911    pc->fetch_count[CISS_SG_FETCH_MAX] = (CISS_COMMAND_ALLOC_SIZE + 15) / 16;
912
913    pc->rq_size = sc->ciss_max_requests; /* XXX less than the card supports? */
914    pc->rq_count = 1;	/* XXX Hardcode for a single queue */
915    pc->rq_bank_hi = 0;
916    pc->rq_bank_lo = 0;
917    pc->rq[0].rq_addr_hi = 0x0;
918    pc->rq[0].rq_addr_lo = sc->ciss_reply_phys;
919
920    return(0);
921}
922
923/************************************************************************
924 * Wait for the adapter to come ready.
925 */
926static int
927ciss_wait_adapter(struct ciss_softc *sc)
928{
929    int		i;
930
931    debug_called(1);
932
933    /*
934     * Wait for the adapter to come ready.
935     */
936    if (!(sc->ciss_cfg->active_method & CISS_TRANSPORT_METHOD_READY)) {
937	ciss_printf(sc, "waiting for adapter to come ready...\n");
938	for (i = 0; !(sc->ciss_cfg->active_method & CISS_TRANSPORT_METHOD_READY); i++) {
939	    DELAY(1000000);	/* one second */
940	    if (i > 30) {
941		ciss_printf(sc, "timed out waiting for adapter to come ready\n");
942		return(EIO);
943	    }
944	}
945    }
946    return(0);
947}
948
949/************************************************************************
950 * Flush the adapter cache.
951 */
952static int
953ciss_flush_adapter(struct ciss_softc *sc)
954{
955    struct ciss_request			*cr;
956    struct ciss_bmic_flush_cache	*cbfc;
957    int					error, command_status;
958
959    debug_called(1);
960
961    cr = NULL;
962    cbfc = NULL;
963
964    /*
965     * Build a BMIC request to flush the cache.  We don't disable
966     * it, as we may be going to do more I/O (eg. we are emulating
967     * the Synchronise Cache command).
968     */
969    if ((cbfc = malloc(sizeof(*cbfc), CISS_MALLOC_CLASS, M_NOWAIT | M_ZERO)) == NULL) {
970	error = ENOMEM;
971	goto out;
972    }
973    if ((error = ciss_get_bmic_request(sc, &cr, CISS_BMIC_FLUSH_CACHE,
974				       (void **)&cbfc, sizeof(*cbfc))) != 0)
975	goto out;
976
977    /*
978     * Submit the request and wait for it to complete.
979     */
980    if ((error = ciss_synch_request(cr, 60 * 1000)) != 0) {
981	ciss_printf(sc, "error sending BMIC FLUSH_CACHE command (%d)\n", error);
982	goto out;
983    }
984
985    /*
986     * Check response.
987     */
988    ciss_report_request(cr, &command_status, NULL);
989    switch(command_status) {
990    case CISS_CMD_STATUS_SUCCESS:
991	break;
992    default:
993	ciss_printf(sc, "error flushing cache (%s)\n",
994		    ciss_name_command_status(command_status));
995	error = EIO;
996	goto out;
997    }
998
999out:
1000    if (cbfc != NULL)
1001	free(cbfc, CISS_MALLOC_CLASS);
1002    if (cr != NULL)
1003	ciss_release_request(cr);
1004    return(error);
1005}
1006
1007static void
1008ciss_soft_reset(struct ciss_softc *sc)
1009{
1010    struct ciss_request		*cr = NULL;
1011    struct ciss_command		*cc;
1012    int				i, error = 0;
1013
1014    for (i = 0; i < sc->ciss_max_logical_bus; i++) {
1015	/* only reset proxy controllers */
1016	if (sc->ciss_controllers[i].physical.bus == 0)
1017	    continue;
1018
1019	if ((error = ciss_get_request(sc, &cr)) != 0)
1020	    break;
1021
1022	if ((error = ciss_get_bmic_request(sc, &cr, CISS_BMIC_SOFT_RESET,
1023					   NULL, 0)) != 0)
1024	    break;
1025
1026	cc = CISS_FIND_COMMAND(cr);
1027	cc->header.address = sc->ciss_controllers[i];
1028
1029	if ((error = ciss_synch_request(cr, 60 * 1000)) != 0)
1030	    break;
1031
1032	ciss_release_request(cr);
1033    }
1034
1035    if (error)
1036	ciss_printf(sc, "error resetting controller (%d)\n", error);
1037
1038    if (cr != NULL)
1039	ciss_release_request(cr);
1040}
1041
1042/************************************************************************
1043 * Allocate memory for the adapter command structures, initialise
1044 * the request structures.
1045 *
1046 * Note that the entire set of commands are allocated in a single
1047 * contiguous slab.
1048 */
1049static int
1050ciss_init_requests(struct ciss_softc *sc)
1051{
1052    struct ciss_request	*cr;
1053    int			i;
1054
1055    debug_called(1);
1056
1057    if (bootverbose)
1058	ciss_printf(sc, "using %d of %d available commands\n",
1059		    sc->ciss_max_requests, sc->ciss_cfg->max_outstanding_commands);
1060
1061    /*
1062     * Create the DMA tag for commands.
1063     */
1064    if (bus_dma_tag_create(sc->ciss_parent_dmat,	/* parent */
1065			   32, 0, 			/* alignment, boundary */
1066			   BUS_SPACE_MAXADDR_32BIT,	/* lowaddr */
1067			   BUS_SPACE_MAXADDR, 		/* highaddr */
1068			   NULL, NULL, 			/* filter, filterarg */
1069			   CISS_COMMAND_ALLOC_SIZE *
1070			   sc->ciss_max_requests, 1,	/* maxsize, nsegments */
1071			   BUS_SPACE_MAXSIZE_32BIT,	/* maxsegsize */
1072			   0,				/* flags */
1073			   NULL, NULL,			/* lockfunc, lockarg */
1074			   &sc->ciss_command_dmat)) {
1075	ciss_printf(sc, "can't allocate command DMA tag\n");
1076	return(ENOMEM);
1077    }
1078    /*
1079     * Allocate memory and make it available for DMA.
1080     */
1081    if (bus_dmamem_alloc(sc->ciss_command_dmat, (void **)&sc->ciss_command,
1082			 BUS_DMA_NOWAIT, &sc->ciss_command_map)) {
1083	ciss_printf(sc, "can't allocate command memory\n");
1084	return(ENOMEM);
1085    }
1086    bus_dmamap_load(sc->ciss_command_dmat, sc->ciss_command_map,sc->ciss_command,
1087		    CISS_COMMAND_ALLOC_SIZE * sc->ciss_max_requests,
1088		    ciss_command_map_helper, &sc->ciss_command_phys, 0);
1089    bzero(sc->ciss_command, CISS_COMMAND_ALLOC_SIZE * sc->ciss_max_requests);
1090
1091    /*
1092     * Set up the request and command structures, push requests onto
1093     * the free queue.
1094     */
1095    for (i = 1; i < sc->ciss_max_requests; i++) {
1096	cr = &sc->ciss_request[i];
1097	cr->cr_sc = sc;
1098	cr->cr_tag = i;
1099	bus_dmamap_create(sc->ciss_buffer_dmat, 0, &cr->cr_datamap);
1100	ciss_enqueue_free(cr);
1101    }
1102    return(0);
1103}
1104
1105static void
1106ciss_command_map_helper(void *arg, bus_dma_segment_t *segs, int nseg, int error)
1107{
1108    uint32_t *addr;
1109
1110    addr = arg;
1111    *addr = segs[0].ds_addr;
1112}
1113
1114/************************************************************************
1115 * Identify the adapter, print some information about it.
1116 */
1117static int
1118ciss_identify_adapter(struct ciss_softc *sc)
1119{
1120    struct ciss_request	*cr;
1121    int			error, command_status;
1122
1123    debug_called(1);
1124
1125    cr = NULL;
1126
1127    /*
1128     * Get a request, allocate storage for the adapter data.
1129     */
1130    if ((error = ciss_get_bmic_request(sc, &cr, CISS_BMIC_ID_CTLR,
1131				       (void **)&sc->ciss_id,
1132				       sizeof(*sc->ciss_id))) != 0)
1133	goto out;
1134
1135    /*
1136     * Submit the request and wait for it to complete.
1137     */
1138    if ((error = ciss_synch_request(cr, 60 * 1000)) != 0) {
1139	ciss_printf(sc, "error sending BMIC ID_CTLR command (%d)\n", error);
1140	goto out;
1141    }
1142
1143    /*
1144     * Check response.
1145     */
1146    ciss_report_request(cr, &command_status, NULL);
1147    switch(command_status) {
1148    case CISS_CMD_STATUS_SUCCESS:		/* buffer right size */
1149	break;
1150    case CISS_CMD_STATUS_DATA_UNDERRUN:
1151    case CISS_CMD_STATUS_DATA_OVERRUN:
1152	ciss_printf(sc, "data over/underrun reading adapter information\n");
1153    default:
1154	ciss_printf(sc, "error reading adapter information (%s)\n",
1155		    ciss_name_command_status(command_status));
1156	error = EIO;
1157	goto out;
1158    }
1159
1160    /* sanity-check reply */
1161    if (!sc->ciss_id->big_map_supported) {
1162	ciss_printf(sc, "adapter does not support BIG_MAP\n");
1163	error = ENXIO;
1164	goto out;
1165    }
1166
1167#if 0
1168    /* XXX later revisions may not need this */
1169    sc->ciss_flags |= CISS_FLAG_FAKE_SYNCH;
1170#endif
1171
1172    /* XXX only really required for old 5300 adapters? */
1173    sc->ciss_flags |= CISS_FLAG_BMIC_ABORT;
1174
1175    /* print information */
1176    if (bootverbose) {
1177#if 0	/* XXX proxy volumes??? */
1178	ciss_printf(sc, "  %d logical drive%s configured\n",
1179		    sc->ciss_id->configured_logical_drives,
1180		    (sc->ciss_id->configured_logical_drives == 1) ? "" : "s");
1181#endif
1182	ciss_printf(sc, "  firmware %4.4s\n", sc->ciss_id->running_firmware_revision);
1183	ciss_printf(sc, "  %d SCSI channels\n", sc->ciss_id->scsi_bus_count);
1184
1185	ciss_printf(sc, "  signature '%.4s'\n", sc->ciss_cfg->signature);
1186	ciss_printf(sc, "  valence %d\n", sc->ciss_cfg->valence);
1187	ciss_printf(sc, "  supported I/O methods 0x%b\n",
1188		    sc->ciss_cfg->supported_methods,
1189		    "\20\1READY\2simple\3performant\4MEMQ\n");
1190	ciss_printf(sc, "  active I/O method 0x%b\n",
1191		    sc->ciss_cfg->active_method, "\20\2simple\3performant\4MEMQ\n");
1192	ciss_printf(sc, "  4G page base 0x%08x\n",
1193		    sc->ciss_cfg->command_physlimit);
1194	ciss_printf(sc, "  interrupt coalesce delay %dus\n",
1195		    sc->ciss_cfg->interrupt_coalesce_delay);
1196	ciss_printf(sc, "  interrupt coalesce count %d\n",
1197		    sc->ciss_cfg->interrupt_coalesce_count);
1198	ciss_printf(sc, "  max outstanding commands %d\n",
1199		    sc->ciss_cfg->max_outstanding_commands);
1200	ciss_printf(sc, "  bus types 0x%b\n", sc->ciss_cfg->bus_types,
1201		    "\20\1ultra2\2ultra3\10fibre1\11fibre2\n");
1202	ciss_printf(sc, "  server name '%.16s'\n", sc->ciss_cfg->server_name);
1203	ciss_printf(sc, "  heartbeat 0x%x\n", sc->ciss_cfg->heartbeat);
1204    }
1205
1206out:
1207    if (error) {
1208	if (sc->ciss_id != NULL) {
1209	    free(sc->ciss_id, CISS_MALLOC_CLASS);
1210	    sc->ciss_id = NULL;
1211	}
1212    }
1213    if (cr != NULL)
1214	ciss_release_request(cr);
1215    return(error);
1216}
1217
1218/************************************************************************
1219 * Helper routine for generating a list of logical and physical luns.
1220 */
1221static struct ciss_lun_report *
1222ciss_report_luns(struct ciss_softc *sc, int opcode, int nunits)
1223{
1224    struct ciss_request		*cr;
1225    struct ciss_command		*cc;
1226    struct ciss_report_cdb	*crc;
1227    struct ciss_lun_report	*cll;
1228    int				command_status;
1229    int				report_size;
1230    int				error = 0;
1231
1232    debug_called(1);
1233
1234    cr = NULL;
1235    cll = NULL;
1236
1237    /*
1238     * Get a request, allocate storage for the address list.
1239     */
1240    if ((error = ciss_get_request(sc, &cr)) != 0)
1241	goto out;
1242    report_size = sizeof(*cll) + nunits * sizeof(union ciss_device_address);
1243    if ((cll = malloc(report_size, CISS_MALLOC_CLASS, M_NOWAIT | M_ZERO)) == NULL) {
1244	ciss_printf(sc, "can't allocate memory for lun report\n");
1245	error = ENOMEM;
1246	goto out;
1247    }
1248
1249    /*
1250     * Build the Report Logical/Physical LUNs command.
1251     */
1252    cc = CISS_FIND_COMMAND(cr);
1253    cr->cr_data = cll;
1254    cr->cr_length = report_size;
1255    cr->cr_flags = CISS_REQ_DATAIN;
1256
1257    cc->header.address.physical.mode = CISS_HDR_ADDRESS_MODE_PERIPHERAL;
1258    cc->header.address.physical.bus = 0;
1259    cc->header.address.physical.target = 0;
1260    cc->cdb.cdb_length = sizeof(*crc);
1261    cc->cdb.type = CISS_CDB_TYPE_COMMAND;
1262    cc->cdb.attribute = CISS_CDB_ATTRIBUTE_SIMPLE;
1263    cc->cdb.direction = CISS_CDB_DIRECTION_READ;
1264    cc->cdb.timeout = 30;	/* XXX better suggestions? */
1265
1266    crc = (struct ciss_report_cdb *)&(cc->cdb.cdb[0]);
1267    bzero(crc, sizeof(*crc));
1268    crc->opcode = opcode;
1269    crc->length = htonl(report_size);			/* big-endian field */
1270    cll->list_size = htonl(report_size - sizeof(*cll));	/* big-endian field */
1271
1272    /*
1273     * Submit the request and wait for it to complete.  (timeout
1274     * here should be much greater than above)
1275     */
1276    if ((error = ciss_synch_request(cr, 60 * 1000)) != 0) {
1277	ciss_printf(sc, "error sending %d LUN command (%d)\n", opcode, error);
1278	goto out;
1279    }
1280
1281    /*
1282     * Check response.  Note that data over/underrun is OK.
1283     */
1284    ciss_report_request(cr, &command_status, NULL);
1285    switch(command_status) {
1286    case CISS_CMD_STATUS_SUCCESS:	/* buffer right size */
1287    case CISS_CMD_STATUS_DATA_UNDERRUN:	/* buffer too large, not bad */
1288	break;
1289    case CISS_CMD_STATUS_DATA_OVERRUN:
1290	ciss_printf(sc, "WARNING: more units than driver limit (%d)\n",
1291		    CISS_MAX_LOGICAL);
1292	break;
1293    default:
1294	ciss_printf(sc, "error detecting logical drive configuration (%s)\n",
1295		    ciss_name_command_status(command_status));
1296	error = EIO;
1297	goto out;
1298    }
1299    ciss_release_request(cr);
1300    cr = NULL;
1301
1302out:
1303    if (cr != NULL)
1304	ciss_release_request(cr);
1305    if (error && cll != NULL) {
1306	free(cll, CISS_MALLOC_CLASS);
1307	cll = NULL;
1308    }
1309    return(cll);
1310}
1311
1312/************************************************************************
1313 * Find logical drives on the adapter.
1314 */
1315static int
1316ciss_init_logical(struct ciss_softc *sc)
1317{
1318    struct ciss_lun_report	*cll;
1319    int				error = 0, i, j;
1320    int				ndrives;
1321
1322    debug_called(1);
1323
1324    cll = ciss_report_luns(sc, CISS_OPCODE_REPORT_LOGICAL_LUNS,
1325			   CISS_MAX_LOGICAL);
1326    if (cll == NULL) {
1327	error = ENXIO;
1328	goto out;
1329    }
1330
1331    /* sanity-check reply */
1332    ndrives = (ntohl(cll->list_size) / sizeof(union ciss_device_address));
1333    if ((ndrives < 0) || (ndrives >= CISS_MAX_LOGICAL)) {
1334	ciss_printf(sc, "adapter claims to report absurd number of logical drives (%d > %d)\n",
1335		    ndrives, CISS_MAX_LOGICAL);
1336	error = ENXIO;
1337	goto out;
1338    }
1339
1340    /*
1341     * Save logical drive information.
1342     */
1343    if (bootverbose) {
1344	ciss_printf(sc, "%d logical drive%s\n",
1345	    ndrives, (ndrives > 1 || ndrives == 0) ? "s" : "");
1346    }
1347
1348    sc->ciss_logical =
1349	malloc(sc->ciss_max_logical_bus * sizeof(struct ciss_ldrive *),
1350	       CISS_MALLOC_CLASS, M_NOWAIT | M_ZERO);
1351    if (sc->ciss_logical == NULL) {
1352	error = ENXIO;
1353	goto out;
1354    }
1355
1356    for (i = 0; i <= sc->ciss_max_logical_bus; i++) {
1357	sc->ciss_logical[i] =
1358	    malloc(CISS_MAX_LOGICAL * sizeof(struct ciss_ldrive),
1359		   CISS_MALLOC_CLASS, M_NOWAIT | M_ZERO);
1360	if (sc->ciss_logical[i] == NULL) {
1361	    error = ENXIO;
1362	    goto out;
1363	}
1364
1365	for (j = 0; j < CISS_MAX_LOGICAL; j++)
1366	    sc->ciss_logical[i][j].cl_status = CISS_LD_NONEXISTENT;
1367    }
1368
1369
1370    for (i = 0; i < CISS_MAX_LOGICAL; i++) {
1371	if (i < ndrives) {
1372	    struct ciss_ldrive	*ld;
1373	    int			bus, target;
1374
1375	    bus		= CISS_LUN_TO_BUS(cll->lun[i].logical.lun);
1376	    target	= CISS_LUN_TO_TARGET(cll->lun[i].logical.lun);
1377	    ld		= &sc->ciss_logical[bus][target];
1378
1379	    ld->cl_address	= cll->lun[i];
1380	    ld->cl_controller	= &sc->ciss_controllers[bus];
1381	    if (ciss_identify_logical(sc, ld) != 0)
1382		continue;
1383	    /*
1384	     * If the drive has had media exchanged, we should bring it online.
1385	     */
1386	    if (ld->cl_lstatus->media_exchanged)
1387		ciss_accept_media(sc, ld);
1388
1389	}
1390    }
1391
1392 out:
1393    if (cll != NULL)
1394	free(cll, CISS_MALLOC_CLASS);
1395    return(error);
1396}
1397
1398static int
1399ciss_init_physical(struct ciss_softc *sc)
1400{
1401    struct ciss_lun_report	*cll;
1402    int				error = 0, i;
1403    int				nphys;
1404    int				bus, target;
1405
1406    debug_called(1);
1407
1408    bus = 0;
1409    target = 0;
1410
1411    cll = ciss_report_luns(sc, CISS_OPCODE_REPORT_PHYSICAL_LUNS,
1412			   CISS_MAX_PHYSICAL);
1413    if (cll == NULL) {
1414	error = ENXIO;
1415	goto out;
1416    }
1417
1418    nphys = (ntohl(cll->list_size) / sizeof(union ciss_device_address));
1419
1420    if (bootverbose) {
1421	ciss_printf(sc, "%d physical device%s\n",
1422	    nphys, (nphys > 1 || nphys == 0) ? "s" : "");
1423    }
1424
1425    /*
1426     * Figure out the bus mapping.
1427     * Logical buses include both the local logical bus for local arrays and
1428     * proxy buses for remote arrays.  Physical buses are numbered by the
1429     * controller and represent physical buses that hold physical devices.
1430     * We shift these bus numbers so that everything fits into a single flat
1431     * numbering space for CAM.  Logical buses occupy the first 32 CAM bus
1432     * numbers, and the physical bus numbers are shifted to be above that.
1433     * This results in the various driver arrays being indexed as follows:
1434     *
1435     * ciss_controllers[] - indexed by logical bus
1436     * ciss_cam_sim[]     - indexed by both logical and physical, with physical
1437     *                      being shifted by 32.
1438     * ciss_logical[][]   - indexed by logical bus
1439     * ciss_physical[][]  - indexed by physical bus
1440     *
1441     * XXX This is getting more and more hackish.  CISS really doesn't play
1442     *     well with a standard SCSI model; devices are addressed via magic
1443     *     cookies, not via b/t/l addresses.  Since there is no way to store
1444     *     the cookie in the CAM device object, we have to keep these lookup
1445     *     tables handy so that the devices can be found quickly at the cost
1446     *     of wasting memory and having a convoluted lookup scheme.  This
1447     *     driver should probably be converted to block interface.
1448     */
1449    /*
1450     * If the L2 and L3 SCSI addresses are 0, this signifies a proxy
1451     * controller. A proxy controller is another physical controller
1452     * behind the primary PCI controller. We need to know about this
1453     * so that BMIC commands can be properly targeted.  There can be
1454     * proxy controllers attached to a single PCI controller, so
1455     * find the highest numbered one so the array can be properly
1456     * sized.
1457     */
1458    sc->ciss_max_logical_bus = 1;
1459    for (i = 0; i < nphys; i++) {
1460	if (cll->lun[i].physical.extra_address == 0) {
1461	    bus = cll->lun[i].physical.bus;
1462	    sc->ciss_max_logical_bus = max(sc->ciss_max_logical_bus, bus) + 1;
1463	} else {
1464	    bus = CISS_EXTRA_BUS2(cll->lun[i].physical.extra_address);
1465	    sc->ciss_max_physical_bus = max(sc->ciss_max_physical_bus, bus);
1466	}
1467    }
1468
1469    sc->ciss_controllers =
1470	malloc(sc->ciss_max_logical_bus * sizeof (union ciss_device_address),
1471	       CISS_MALLOC_CLASS, M_NOWAIT | M_ZERO);
1472
1473    if (sc->ciss_controllers == NULL) {
1474	ciss_printf(sc, "Could not allocate memory for controller map\n");
1475	error = ENOMEM;
1476	goto out;
1477    }
1478
1479    /* setup a map of controller addresses */
1480    for (i = 0; i < nphys; i++) {
1481	if (cll->lun[i].physical.extra_address == 0) {
1482	    sc->ciss_controllers[cll->lun[i].physical.bus] = cll->lun[i];
1483	}
1484    }
1485
1486    sc->ciss_physical =
1487	malloc(sc->ciss_max_physical_bus * sizeof(struct ciss_pdrive *),
1488	       CISS_MALLOC_CLASS, M_NOWAIT | M_ZERO);
1489    if (sc->ciss_physical == NULL) {
1490	ciss_printf(sc, "Could not allocate memory for physical device map\n");
1491	error = ENOMEM;
1492	goto out;
1493    }
1494
1495    for (i = 0; i < sc->ciss_max_physical_bus; i++) {
1496	sc->ciss_physical[i] =
1497	    malloc(sizeof(struct ciss_pdrive) * CISS_MAX_PHYSTGT,
1498		   CISS_MALLOC_CLASS, M_NOWAIT | M_ZERO);
1499	if (sc->ciss_physical[i] == NULL) {
1500	    ciss_printf(sc, "Could not allocate memory for target map\n");
1501	    error = ENOMEM;
1502	    goto out;
1503	}
1504    }
1505
1506    ciss_filter_physical(sc, cll);
1507
1508out:
1509    if (cll != NULL)
1510	free(cll, CISS_MALLOC_CLASS);
1511
1512    return(error);
1513}
1514
1515static int
1516ciss_filter_physical(struct ciss_softc *sc, struct ciss_lun_report *cll)
1517{
1518    u_int32_t ea;
1519    int i, nphys;
1520    int	bus, target;
1521
1522    nphys = (ntohl(cll->list_size) / sizeof(union ciss_device_address));
1523    for (i = 0; i < nphys; i++) {
1524	if (cll->lun[i].physical.extra_address == 0)
1525	    continue;
1526
1527	/*
1528	 * Filter out devices that we don't want.  Level 3 LUNs could
1529	 * probably be supported, but the docs don't give enough of a
1530	 * hint to know how.
1531	 *
1532	 * The mode field of the physical address is likely set to have
1533	 * hard disks masked out.  Honor it unless the user has overridden
1534	 * us with the tunable.  We also munge the inquiry data for these
1535	 * disks so that they only show up as passthrough devices.  Keeping
1536	 * them visible in this fashion is useful for doing things like
1537	 * flashing firmware.
1538	 */
1539	ea = cll->lun[i].physical.extra_address;
1540	if ((CISS_EXTRA_BUS3(ea) != 0) || (CISS_EXTRA_TARGET3(ea) != 0) ||
1541	    (CISS_EXTRA_MODE2(ea) == 0x3))
1542	    continue;
1543	if ((ciss_expose_hidden_physical == 0) &&
1544	   (cll->lun[i].physical.mode == CISS_HDR_ADDRESS_MODE_MASK_PERIPHERAL))
1545	    continue;
1546
1547	/*
1548	 * Note: CISS firmware numbers physical busses starting at '1', not
1549	 *       '0'.  This numbering is internal to the firmware and is only
1550	 *       used as a hint here.
1551	 */
1552	bus = CISS_EXTRA_BUS2(ea) - 1;
1553	target = CISS_EXTRA_TARGET2(ea);
1554	sc->ciss_physical[bus][target].cp_address = cll->lun[i];
1555	sc->ciss_physical[bus][target].cp_online = 1;
1556    }
1557
1558    return (0);
1559}
1560
1561static int
1562ciss_inquiry_logical(struct ciss_softc *sc, struct ciss_ldrive *ld)
1563{
1564    struct ciss_request			*cr;
1565    struct ciss_command			*cc;
1566    struct scsi_inquiry			*inq;
1567    int					error;
1568    int					command_status;
1569
1570    cr = NULL;
1571
1572    bzero(&ld->cl_geometry, sizeof(ld->cl_geometry));
1573
1574    if ((error = ciss_get_request(sc, &cr)) != 0)
1575	goto out;
1576
1577    cc = CISS_FIND_COMMAND(cr);
1578    cr->cr_data = &ld->cl_geometry;
1579    cr->cr_length = sizeof(ld->cl_geometry);
1580    cr->cr_flags = CISS_REQ_DATAIN;
1581
1582    cc->header.address = ld->cl_address;
1583    cc->cdb.cdb_length = 6;
1584    cc->cdb.type = CISS_CDB_TYPE_COMMAND;
1585    cc->cdb.attribute = CISS_CDB_ATTRIBUTE_SIMPLE;
1586    cc->cdb.direction = CISS_CDB_DIRECTION_READ;
1587    cc->cdb.timeout = 30;
1588
1589    inq = (struct scsi_inquiry *)&(cc->cdb.cdb[0]);
1590    inq->opcode = INQUIRY;
1591    inq->byte2 = SI_EVPD;
1592    inq->page_code = CISS_VPD_LOGICAL_DRIVE_GEOMETRY;
1593    inq->length = sizeof(ld->cl_geometry);
1594
1595    if ((error = ciss_synch_request(cr, 60 * 1000)) != 0) {
1596	ciss_printf(sc, "error getting geometry (%d)\n", error);
1597	goto out;
1598    }
1599
1600    ciss_report_request(cr, &command_status, NULL);
1601    switch(command_status) {
1602    case CISS_CMD_STATUS_SUCCESS:
1603    case CISS_CMD_STATUS_DATA_UNDERRUN:
1604	break;
1605    case CISS_CMD_STATUS_DATA_OVERRUN:
1606	ciss_printf(sc, "WARNING: Data overrun\n");
1607	break;
1608    default:
1609	ciss_printf(sc, "Error detecting logical drive geometry (%s)\n",
1610		    ciss_name_command_status(command_status));
1611	break;
1612    }
1613
1614out:
1615    if (cr != NULL)
1616	ciss_release_request(cr);
1617    return(error);
1618}
1619/************************************************************************
1620 * Identify a logical drive, initialise state related to it.
1621 */
1622static int
1623ciss_identify_logical(struct ciss_softc *sc, struct ciss_ldrive *ld)
1624{
1625    struct ciss_request		*cr;
1626    struct ciss_command		*cc;
1627    struct ciss_bmic_cdb	*cbc;
1628    int				error, command_status;
1629
1630    debug_called(1);
1631
1632    cr = NULL;
1633
1634    /*
1635     * Build a BMIC request to fetch the drive ID.
1636     */
1637    if ((error = ciss_get_bmic_request(sc, &cr, CISS_BMIC_ID_LDRIVE,
1638				       (void **)&ld->cl_ldrive,
1639				       sizeof(*ld->cl_ldrive))) != 0)
1640	goto out;
1641    cc = CISS_FIND_COMMAND(cr);
1642    cc->header.address = *ld->cl_controller;	/* target controller */
1643    cbc = (struct ciss_bmic_cdb *)&(cc->cdb.cdb[0]);
1644    cbc->log_drive = CISS_LUN_TO_TARGET(ld->cl_address.logical.lun);
1645
1646    /*
1647     * Submit the request and wait for it to complete.
1648     */
1649    if ((error = ciss_synch_request(cr, 60 * 1000)) != 0) {
1650	ciss_printf(sc, "error sending BMIC LDRIVE command (%d)\n", error);
1651	goto out;
1652    }
1653
1654    /*
1655     * Check response.
1656     */
1657    ciss_report_request(cr, &command_status, NULL);
1658    switch(command_status) {
1659    case CISS_CMD_STATUS_SUCCESS:		/* buffer right size */
1660	break;
1661    case CISS_CMD_STATUS_DATA_UNDERRUN:
1662    case CISS_CMD_STATUS_DATA_OVERRUN:
1663	ciss_printf(sc, "data over/underrun reading logical drive ID\n");
1664    default:
1665	ciss_printf(sc, "error reading logical drive ID (%s)\n",
1666		    ciss_name_command_status(command_status));
1667	error = EIO;
1668	goto out;
1669    }
1670    ciss_release_request(cr);
1671    cr = NULL;
1672
1673    /*
1674     * Build a CISS BMIC command to get the logical drive status.
1675     */
1676    if ((error = ciss_get_ldrive_status(sc, ld)) != 0)
1677	goto out;
1678
1679    /*
1680     * Get the logical drive geometry.
1681     */
1682    if ((error = ciss_inquiry_logical(sc, ld)) != 0)
1683	goto out;
1684
1685    /*
1686     * Print the drive's basic characteristics.
1687     */
1688    if (bootverbose) {
1689	ciss_printf(sc, "logical drive (b%dt%d): %s, %dMB ",
1690		    CISS_LUN_TO_BUS(ld->cl_address.logical.lun),
1691		    CISS_LUN_TO_TARGET(ld->cl_address.logical.lun),
1692		    ciss_name_ldrive_org(ld->cl_ldrive->fault_tolerance),
1693		    ((ld->cl_ldrive->blocks_available / (1024 * 1024)) *
1694		     ld->cl_ldrive->block_size));
1695
1696	ciss_print_ldrive(sc, ld);
1697    }
1698out:
1699    if (error != 0) {
1700	/* make the drive not-exist */
1701	ld->cl_status = CISS_LD_NONEXISTENT;
1702	if (ld->cl_ldrive != NULL) {
1703	    free(ld->cl_ldrive, CISS_MALLOC_CLASS);
1704	    ld->cl_ldrive = NULL;
1705	}
1706	if (ld->cl_lstatus != NULL) {
1707	    free(ld->cl_lstatus, CISS_MALLOC_CLASS);
1708	    ld->cl_lstatus = NULL;
1709	}
1710    }
1711    if (cr != NULL)
1712	ciss_release_request(cr);
1713
1714    return(error);
1715}
1716
1717/************************************************************************
1718 * Get status for a logical drive.
1719 *
1720 * XXX should we also do this in response to Test Unit Ready?
1721 */
1722static int
1723ciss_get_ldrive_status(struct ciss_softc *sc,  struct ciss_ldrive *ld)
1724{
1725    struct ciss_request		*cr;
1726    struct ciss_command		*cc;
1727    struct ciss_bmic_cdb	*cbc;
1728    int				error, command_status;
1729
1730    /*
1731     * Build a CISS BMIC command to get the logical drive status.
1732     */
1733    if ((error = ciss_get_bmic_request(sc, &cr, CISS_BMIC_ID_LSTATUS,
1734				       (void **)&ld->cl_lstatus,
1735				       sizeof(*ld->cl_lstatus))) != 0)
1736	goto out;
1737    cc = CISS_FIND_COMMAND(cr);
1738    cc->header.address = *ld->cl_controller;	/* target controller */
1739    cbc = (struct ciss_bmic_cdb *)&(cc->cdb.cdb[0]);
1740    cbc->log_drive = CISS_LUN_TO_TARGET(ld->cl_address.logical.lun);
1741
1742    /*
1743     * Submit the request and wait for it to complete.
1744     */
1745    if ((error = ciss_synch_request(cr, 60 * 1000)) != 0) {
1746	ciss_printf(sc, "error sending BMIC LSTATUS command (%d)\n", error);
1747	goto out;
1748    }
1749
1750    /*
1751     * Check response.
1752     */
1753    ciss_report_request(cr, &command_status, NULL);
1754    switch(command_status) {
1755    case CISS_CMD_STATUS_SUCCESS:		/* buffer right size */
1756	break;
1757    case CISS_CMD_STATUS_DATA_UNDERRUN:
1758    case CISS_CMD_STATUS_DATA_OVERRUN:
1759	ciss_printf(sc, "data over/underrun reading logical drive status\n");
1760    default:
1761	ciss_printf(sc, "error reading logical drive status (%s)\n",
1762		    ciss_name_command_status(command_status));
1763	error = EIO;
1764	goto out;
1765    }
1766
1767    /*
1768     * Set the drive's summary status based on the returned status.
1769     *
1770     * XXX testing shows that a failed JBOD drive comes back at next
1771     * boot in "queued for expansion" mode.  WTF?
1772     */
1773    ld->cl_status = ciss_decode_ldrive_status(ld->cl_lstatus->status);
1774
1775out:
1776    if (cr != NULL)
1777	ciss_release_request(cr);
1778    return(error);
1779}
1780
1781/************************************************************************
1782 * Notify the adapter of a config update.
1783 */
1784static int
1785ciss_update_config(struct ciss_softc *sc)
1786{
1787    int		i;
1788
1789    debug_called(1);
1790
1791    CISS_TL_SIMPLE_WRITE(sc, CISS_TL_SIMPLE_IDBR, CISS_TL_SIMPLE_IDBR_CFG_TABLE);
1792    for (i = 0; i < 1000; i++) {
1793	if (!(CISS_TL_SIMPLE_READ(sc, CISS_TL_SIMPLE_IDBR) &
1794	      CISS_TL_SIMPLE_IDBR_CFG_TABLE)) {
1795	    return(0);
1796	}
1797	DELAY(1000);
1798    }
1799    return(1);
1800}
1801
1802/************************************************************************
1803 * Accept new media into a logical drive.
1804 *
1805 * XXX The drive has previously been offline; it would be good if we
1806 *     could make sure it's not open right now.
1807 */
1808static int
1809ciss_accept_media(struct ciss_softc *sc, struct ciss_ldrive *ld)
1810{
1811    struct ciss_request		*cr;
1812    struct ciss_command		*cc;
1813    struct ciss_bmic_cdb	*cbc;
1814    int				command_status;
1815    int				error = 0, ldrive;
1816
1817    ldrive = CISS_LUN_TO_TARGET(ld->cl_address.logical.lun);
1818
1819    debug(0, "bringing logical drive %d back online");
1820
1821    /*
1822     * Build a CISS BMIC command to bring the drive back online.
1823     */
1824    if ((error = ciss_get_bmic_request(sc, &cr, CISS_BMIC_ACCEPT_MEDIA,
1825				       NULL, 0)) != 0)
1826	goto out;
1827    cc = CISS_FIND_COMMAND(cr);
1828    cc->header.address = *ld->cl_controller;	/* target controller */
1829    cbc = (struct ciss_bmic_cdb *)&(cc->cdb.cdb[0]);
1830    cbc->log_drive = ldrive;
1831
1832    /*
1833     * Submit the request and wait for it to complete.
1834     */
1835    if ((error = ciss_synch_request(cr, 60 * 1000)) != 0) {
1836	ciss_printf(sc, "error sending BMIC ACCEPT MEDIA command (%d)\n", error);
1837	goto out;
1838    }
1839
1840    /*
1841     * Check response.
1842     */
1843    ciss_report_request(cr, &command_status, NULL);
1844    switch(command_status) {
1845    case CISS_CMD_STATUS_SUCCESS:		/* all OK */
1846	/* we should get a logical drive status changed event here */
1847	break;
1848    default:
1849	ciss_printf(cr->cr_sc, "error accepting media into failed logical drive (%s)\n",
1850		    ciss_name_command_status(command_status));
1851	break;
1852    }
1853
1854out:
1855    if (cr != NULL)
1856	ciss_release_request(cr);
1857    return(error);
1858}
1859
1860/************************************************************************
1861 * Release adapter resources.
1862 */
1863static void
1864ciss_free(struct ciss_softc *sc)
1865{
1866    struct ciss_request *cr;
1867    int			i, j;
1868
1869    debug_called(1);
1870
1871    /* we're going away */
1872    sc->ciss_flags |= CISS_FLAG_ABORTING;
1873
1874    /* terminate the periodic heartbeat routine */
1875    callout_stop(&sc->ciss_periodic);
1876
1877    /* cancel the Event Notify chain */
1878    ciss_notify_abort(sc);
1879
1880    ciss_kill_notify_thread(sc);
1881
1882    /* disconnect from CAM */
1883    if (sc->ciss_cam_sim) {
1884	for (i = 0; i < sc->ciss_max_logical_bus; i++) {
1885	    if (sc->ciss_cam_sim[i]) {
1886		xpt_bus_deregister(cam_sim_path(sc->ciss_cam_sim[i]));
1887		cam_sim_free(sc->ciss_cam_sim[i], 0);
1888	    }
1889	}
1890	for (i = CISS_PHYSICAL_BASE; i < sc->ciss_max_physical_bus +
1891	     CISS_PHYSICAL_BASE; i++) {
1892	    if (sc->ciss_cam_sim[i]) {
1893		xpt_bus_deregister(cam_sim_path(sc->ciss_cam_sim[i]));
1894		cam_sim_free(sc->ciss_cam_sim[i], 0);
1895	    }
1896	}
1897	free(sc->ciss_cam_sim, CISS_MALLOC_CLASS);
1898    }
1899    if (sc->ciss_cam_devq)
1900	cam_simq_free(sc->ciss_cam_devq);
1901
1902    /* remove the control device */
1903    mtx_unlock(&sc->ciss_mtx);
1904    if (sc->ciss_dev_t != NULL)
1905	destroy_dev(sc->ciss_dev_t);
1906
1907    /* Final cleanup of the callout. */
1908    callout_drain(&sc->ciss_periodic);
1909    mtx_destroy(&sc->ciss_mtx);
1910
1911    /* free the controller data */
1912    if (sc->ciss_id != NULL)
1913	free(sc->ciss_id, CISS_MALLOC_CLASS);
1914
1915    /* release I/O resources */
1916    if (sc->ciss_regs_resource != NULL)
1917	bus_release_resource(sc->ciss_dev, SYS_RES_MEMORY,
1918			     sc->ciss_regs_rid, sc->ciss_regs_resource);
1919    if (sc->ciss_cfg_resource != NULL)
1920	bus_release_resource(sc->ciss_dev, SYS_RES_MEMORY,
1921			     sc->ciss_cfg_rid, sc->ciss_cfg_resource);
1922    if (sc->ciss_intr != NULL)
1923	bus_teardown_intr(sc->ciss_dev, sc->ciss_irq_resource, sc->ciss_intr);
1924    if (sc->ciss_irq_resource != NULL)
1925	bus_release_resource(sc->ciss_dev, SYS_RES_IRQ,
1926			     sc->ciss_irq_rid[0], sc->ciss_irq_resource);
1927    if (sc->ciss_msi)
1928	pci_release_msi(sc->ciss_dev);
1929
1930    while ((cr = ciss_dequeue_free(sc)) != NULL)
1931	bus_dmamap_destroy(sc->ciss_buffer_dmat, cr->cr_datamap);
1932    if (sc->ciss_buffer_dmat)
1933	bus_dma_tag_destroy(sc->ciss_buffer_dmat);
1934
1935    /* destroy command memory and DMA tag */
1936    if (sc->ciss_command != NULL) {
1937	bus_dmamap_unload(sc->ciss_command_dmat, sc->ciss_command_map);
1938	bus_dmamem_free(sc->ciss_command_dmat, sc->ciss_command, sc->ciss_command_map);
1939    }
1940    if (sc->ciss_command_dmat)
1941	bus_dma_tag_destroy(sc->ciss_command_dmat);
1942
1943    if (sc->ciss_reply) {
1944	bus_dmamap_unload(sc->ciss_reply_dmat, sc->ciss_reply_map);
1945	bus_dmamem_free(sc->ciss_reply_dmat, sc->ciss_reply, sc->ciss_reply_map);
1946    }
1947    if (sc->ciss_reply_dmat)
1948	bus_dma_tag_destroy(sc->ciss_reply_dmat);
1949
1950    /* destroy DMA tags */
1951    if (sc->ciss_parent_dmat)
1952	bus_dma_tag_destroy(sc->ciss_parent_dmat);
1953    if (sc->ciss_logical) {
1954	for (i = 0; i <= sc->ciss_max_logical_bus; i++) {
1955	    for (j = 0; j < CISS_MAX_LOGICAL; j++) {
1956		if (sc->ciss_logical[i][j].cl_ldrive)
1957		    free(sc->ciss_logical[i][j].cl_ldrive, CISS_MALLOC_CLASS);
1958		if (sc->ciss_logical[i][j].cl_lstatus)
1959		    free(sc->ciss_logical[i][j].cl_lstatus, CISS_MALLOC_CLASS);
1960	    }
1961	    free(sc->ciss_logical[i], CISS_MALLOC_CLASS);
1962	}
1963	free(sc->ciss_logical, CISS_MALLOC_CLASS);
1964    }
1965
1966    if (sc->ciss_physical) {
1967	for (i = 0; i < sc->ciss_max_physical_bus; i++)
1968	    free(sc->ciss_physical[i], CISS_MALLOC_CLASS);
1969	free(sc->ciss_physical, CISS_MALLOC_CLASS);
1970    }
1971
1972    if (sc->ciss_controllers)
1973	free(sc->ciss_controllers, CISS_MALLOC_CLASS);
1974
1975}
1976
1977/************************************************************************
1978 * Give a command to the adapter.
1979 *
1980 * Note that this uses the simple transport layer directly.  If we
1981 * want to add support for other layers, we'll need a switch of some
1982 * sort.
1983 *
1984 * Note that the simple transport layer has no way of refusing a
1985 * command; we only have as many request structures as the adapter
1986 * supports commands, so we don't have to check (this presumes that
1987 * the adapter can handle commands as fast as we throw them at it).
1988 */
1989static int
1990ciss_start(struct ciss_request *cr)
1991{
1992    struct ciss_command	*cc;	/* XXX debugging only */
1993    int			error;
1994
1995    cc = CISS_FIND_COMMAND(cr);
1996    debug(2, "post command %d tag %d ", cr->cr_tag, cc->header.host_tag);
1997
1998    /*
1999     * Map the request's data.
2000     */
2001    if ((error = ciss_map_request(cr)))
2002	return(error);
2003
2004#if 0
2005    ciss_print_request(cr);
2006#endif
2007
2008    return(0);
2009}
2010
2011/************************************************************************
2012 * Fetch completed request(s) from the adapter, queue them for
2013 * completion handling.
2014 *
2015 * Note that this uses the simple transport layer directly.  If we
2016 * want to add support for other layers, we'll need a switch of some
2017 * sort.
2018 *
2019 * Note that the simple transport mechanism does not require any
2020 * reentrancy protection; the OPQ read is atomic.  If there is a
2021 * chance of a race with something else that might move the request
2022 * off the busy list, then we will have to lock against that
2023 * (eg. timeouts, etc.)
2024 */
2025static void
2026ciss_done(struct ciss_softc *sc, cr_qhead_t *qh)
2027{
2028    struct ciss_request	*cr;
2029    struct ciss_command	*cc;
2030    u_int32_t		tag, index;
2031
2032    debug_called(3);
2033
2034    /*
2035     * Loop quickly taking requests from the adapter and moving them
2036     * to the completed queue.
2037     */
2038    for (;;) {
2039
2040	tag = CISS_TL_SIMPLE_FETCH_CMD(sc);
2041	if (tag == CISS_TL_SIMPLE_OPQ_EMPTY)
2042	    break;
2043	index = tag >> 2;
2044	debug(2, "completed command %d%s", index,
2045	      (tag & CISS_HDR_HOST_TAG_ERROR) ? " with error" : "");
2046	if (index >= sc->ciss_max_requests) {
2047	    ciss_printf(sc, "completed invalid request %d (0x%x)\n", index, tag);
2048	    continue;
2049	}
2050	cr = &(sc->ciss_request[index]);
2051	cc = CISS_FIND_COMMAND(cr);
2052	cc->header.host_tag = tag;	/* not updated by adapter */
2053	ciss_enqueue_complete(cr, qh);
2054    }
2055
2056}
2057
2058static void
2059ciss_perf_done(struct ciss_softc *sc, cr_qhead_t *qh)
2060{
2061    struct ciss_request	*cr;
2062    struct ciss_command	*cc;
2063    u_int32_t		tag, index;
2064
2065    debug_called(3);
2066
2067    /*
2068     * Loop quickly taking requests from the adapter and moving them
2069     * to the completed queue.
2070     */
2071    for (;;) {
2072	tag = sc->ciss_reply[sc->ciss_rqidx];
2073	if ((tag & CISS_CYCLE_MASK) != sc->ciss_cycle)
2074	    break;
2075	index = tag >> 2;
2076	debug(2, "completed command %d%s\n", index,
2077	      (tag & CISS_HDR_HOST_TAG_ERROR) ? " with error" : "");
2078	if (index < sc->ciss_max_requests) {
2079	    cr = &(sc->ciss_request[index]);
2080	    cc = CISS_FIND_COMMAND(cr);
2081	    cc->header.host_tag = tag;	/* not updated by adapter */
2082	    ciss_enqueue_complete(cr, qh);
2083	} else {
2084	    ciss_printf(sc, "completed invalid request %d (0x%x)\n", index, tag);
2085	}
2086	if (++sc->ciss_rqidx == sc->ciss_max_requests) {
2087	    sc->ciss_rqidx = 0;
2088	    sc->ciss_cycle ^= 1;
2089	}
2090    }
2091
2092}
2093
2094/************************************************************************
2095 * Take an interrupt from the adapter.
2096 */
2097static void
2098ciss_intr(void *arg)
2099{
2100    cr_qhead_t qh;
2101    struct ciss_softc	*sc = (struct ciss_softc *)arg;
2102
2103    /*
2104     * The only interrupt we recognise indicates that there are
2105     * entries in the outbound post queue.
2106     */
2107    STAILQ_INIT(&qh);
2108    ciss_done(sc, &qh);
2109    mtx_lock(&sc->ciss_mtx);
2110    ciss_complete(sc, &qh);
2111    mtx_unlock(&sc->ciss_mtx);
2112}
2113
2114static void
2115ciss_perf_intr(void *arg)
2116{
2117    struct ciss_softc	*sc = (struct ciss_softc *)arg;
2118
2119    /* Clear the interrupt and flush the bridges.  Docs say that the flush
2120     * needs to be done twice, which doesn't seem right.
2121     */
2122    CISS_TL_PERF_CLEAR_INT(sc);
2123    CISS_TL_PERF_FLUSH_INT(sc);
2124
2125    ciss_perf_msi_intr(sc);
2126}
2127
2128static void
2129ciss_perf_msi_intr(void *arg)
2130{
2131    cr_qhead_t qh;
2132    struct ciss_softc	*sc = (struct ciss_softc *)arg;
2133
2134    STAILQ_INIT(&qh);
2135    ciss_perf_done(sc, &qh);
2136    mtx_lock(&sc->ciss_mtx);
2137    ciss_complete(sc, &qh);
2138    mtx_unlock(&sc->ciss_mtx);
2139}
2140
2141
2142/************************************************************************
2143 * Process completed requests.
2144 *
2145 * Requests can be completed in three fashions:
2146 *
2147 * - by invoking a callback function (cr_complete is non-null)
2148 * - by waking up a sleeper (cr_flags has CISS_REQ_SLEEP set)
2149 * - by clearing the CISS_REQ_POLL flag in interrupt/timeout context
2150 */
2151static void
2152ciss_complete(struct ciss_softc *sc, cr_qhead_t *qh)
2153{
2154    struct ciss_request	*cr;
2155
2156    debug_called(2);
2157
2158    /*
2159     * Loop taking requests off the completed queue and performing
2160     * completion processing on them.
2161     */
2162    for (;;) {
2163	if ((cr = ciss_dequeue_complete(sc, qh)) == NULL)
2164	    break;
2165	ciss_unmap_request(cr);
2166
2167	if ((cr->cr_flags & CISS_REQ_BUSY) == 0)
2168	    ciss_printf(sc, "WARNING: completing non-busy request\n");
2169	cr->cr_flags &= ~CISS_REQ_BUSY;
2170
2171	/*
2172	 * If the request has a callback, invoke it.
2173	 */
2174	if (cr->cr_complete != NULL) {
2175	    cr->cr_complete(cr);
2176	    continue;
2177	}
2178
2179	/*
2180	 * If someone is sleeping on this request, wake them up.
2181	 */
2182	if (cr->cr_flags & CISS_REQ_SLEEP) {
2183	    cr->cr_flags &= ~CISS_REQ_SLEEP;
2184	    wakeup(cr);
2185	    continue;
2186	}
2187
2188	/*
2189	 * If someone is polling this request for completion, signal.
2190	 */
2191	if (cr->cr_flags & CISS_REQ_POLL) {
2192	    cr->cr_flags &= ~CISS_REQ_POLL;
2193	    continue;
2194	}
2195
2196	/*
2197	 * Give up and throw the request back on the free queue.  This
2198	 * should never happen; resources will probably be lost.
2199	 */
2200	ciss_printf(sc, "WARNING: completed command with no submitter\n");
2201	ciss_enqueue_free(cr);
2202    }
2203}
2204
2205/************************************************************************
2206 * Report on the completion status of a request, and pass back SCSI
2207 * and command status values.
2208 */
2209static int
2210_ciss_report_request(struct ciss_request *cr, int *command_status, int *scsi_status, const char *func)
2211{
2212    struct ciss_command		*cc;
2213    struct ciss_error_info	*ce;
2214
2215    debug_called(2);
2216
2217    cc = CISS_FIND_COMMAND(cr);
2218    ce = (struct ciss_error_info *)&(cc->sg[0]);
2219
2220    /*
2221     * We don't consider data under/overrun an error for the Report
2222     * Logical/Physical LUNs commands.
2223     */
2224    if ((cc->header.host_tag & CISS_HDR_HOST_TAG_ERROR) &&
2225	((ce->command_status == CISS_CMD_STATUS_DATA_OVERRUN) ||
2226	 (ce->command_status == CISS_CMD_STATUS_DATA_UNDERRUN)) &&
2227	((cc->cdb.cdb[0] == CISS_OPCODE_REPORT_LOGICAL_LUNS) ||
2228	 (cc->cdb.cdb[0] == CISS_OPCODE_REPORT_PHYSICAL_LUNS) ||
2229	 (cc->cdb.cdb[0] == INQUIRY))) {
2230	cc->header.host_tag &= ~CISS_HDR_HOST_TAG_ERROR;
2231	debug(2, "ignoring irrelevant under/overrun error");
2232    }
2233
2234    /*
2235     * Check the command's error bit, if clear, there's no status and
2236     * everything is OK.
2237     */
2238    if (!(cc->header.host_tag & CISS_HDR_HOST_TAG_ERROR)) {
2239	if (scsi_status != NULL)
2240	    *scsi_status = SCSI_STATUS_OK;
2241	if (command_status != NULL)
2242	    *command_status = CISS_CMD_STATUS_SUCCESS;
2243	return(0);
2244    } else {
2245	if (command_status != NULL)
2246	    *command_status = ce->command_status;
2247	if (scsi_status != NULL) {
2248	    if (ce->command_status == CISS_CMD_STATUS_TARGET_STATUS) {
2249		*scsi_status = ce->scsi_status;
2250	    } else {
2251		*scsi_status = -1;
2252	    }
2253	}
2254	if (bootverbose)
2255	    ciss_printf(cr->cr_sc, "command status 0x%x (%s) scsi status 0x%x\n",
2256			ce->command_status, ciss_name_command_status(ce->command_status),
2257			ce->scsi_status);
2258	if (ce->command_status == CISS_CMD_STATUS_INVALID_COMMAND) {
2259	    ciss_printf(cr->cr_sc, "invalid command, offense size %d at %d, value 0x%x, function %s\n",
2260			ce->additional_error_info.invalid_command.offense_size,
2261			ce->additional_error_info.invalid_command.offense_offset,
2262			ce->additional_error_info.invalid_command.offense_value,
2263			func);
2264	}
2265    }
2266#if 0
2267    ciss_print_request(cr);
2268#endif
2269    return(1);
2270}
2271
2272/************************************************************************
2273 * Issue a request and don't return until it's completed.
2274 *
2275 * Depending on adapter status, we may poll or sleep waiting for
2276 * completion.
2277 */
2278static int
2279ciss_synch_request(struct ciss_request *cr, int timeout)
2280{
2281    if (cr->cr_sc->ciss_flags & CISS_FLAG_RUNNING) {
2282	return(ciss_wait_request(cr, timeout));
2283    } else {
2284	return(ciss_poll_request(cr, timeout));
2285    }
2286}
2287
2288/************************************************************************
2289 * Issue a request and poll for completion.
2290 *
2291 * Timeout in milliseconds.
2292 */
2293static int
2294ciss_poll_request(struct ciss_request *cr, int timeout)
2295{
2296    cr_qhead_t qh;
2297    struct ciss_softc *sc;
2298    int		error;
2299
2300    debug_called(2);
2301
2302    STAILQ_INIT(&qh);
2303    sc = cr->cr_sc;
2304    cr->cr_flags |= CISS_REQ_POLL;
2305    if ((error = ciss_start(cr)) != 0)
2306	return(error);
2307
2308    do {
2309	if (sc->ciss_perf)
2310	    ciss_perf_done(sc, &qh);
2311	else
2312	    ciss_done(sc, &qh);
2313	ciss_complete(sc, &qh);
2314	if (!(cr->cr_flags & CISS_REQ_POLL))
2315	    return(0);
2316	DELAY(1000);
2317    } while (timeout-- >= 0);
2318    return(EWOULDBLOCK);
2319}
2320
2321/************************************************************************
2322 * Issue a request and sleep waiting for completion.
2323 *
2324 * Timeout in milliseconds.  Note that a spurious wakeup will reset
2325 * the timeout.
2326 */
2327static int
2328ciss_wait_request(struct ciss_request *cr, int timeout)
2329{
2330    int		error;
2331
2332    debug_called(2);
2333
2334    cr->cr_flags |= CISS_REQ_SLEEP;
2335    if ((error = ciss_start(cr)) != 0)
2336	return(error);
2337
2338    while ((cr->cr_flags & CISS_REQ_SLEEP) && (error != EWOULDBLOCK)) {
2339	error = msleep(cr, &cr->cr_sc->ciss_mtx, PRIBIO, "cissREQ", (timeout * hz) / 1000);
2340    }
2341    return(error);
2342}
2343
2344#if 0
2345/************************************************************************
2346 * Abort a request.  Note that a potential exists here to race the
2347 * request being completed; the caller must deal with this.
2348 */
2349static int
2350ciss_abort_request(struct ciss_request *ar)
2351{
2352    struct ciss_request		*cr;
2353    struct ciss_command		*cc;
2354    struct ciss_message_cdb	*cmc;
2355    int				error;
2356
2357    debug_called(1);
2358
2359    /* get a request */
2360    if ((error = ciss_get_request(ar->cr_sc, &cr)) != 0)
2361	return(error);
2362
2363    /* build the abort command */
2364    cc = CISS_FIND_COMMAND(cr);
2365    cc->header.address.mode.mode = CISS_HDR_ADDRESS_MODE_PERIPHERAL;	/* addressing? */
2366    cc->header.address.physical.target = 0;
2367    cc->header.address.physical.bus = 0;
2368    cc->cdb.cdb_length = sizeof(*cmc);
2369    cc->cdb.type = CISS_CDB_TYPE_MESSAGE;
2370    cc->cdb.attribute = CISS_CDB_ATTRIBUTE_SIMPLE;
2371    cc->cdb.direction = CISS_CDB_DIRECTION_NONE;
2372    cc->cdb.timeout = 30;
2373
2374    cmc = (struct ciss_message_cdb *)&(cc->cdb.cdb[0]);
2375    cmc->opcode = CISS_OPCODE_MESSAGE_ABORT;
2376    cmc->type = CISS_MESSAGE_ABORT_TASK;
2377    cmc->abort_tag = ar->cr_tag;	/* endianness?? */
2378
2379    /*
2380     * Send the request and wait for a response.  If we believe we
2381     * aborted the request OK, clear the flag that indicates it's
2382     * running.
2383     */
2384    error = ciss_synch_request(cr, 35 * 1000);
2385    if (!error)
2386	error = ciss_report_request(cr, NULL, NULL);
2387    ciss_release_request(cr);
2388
2389    return(error);
2390}
2391#endif
2392
2393
2394/************************************************************************
2395 * Fetch and initialise a request
2396 */
2397static int
2398ciss_get_request(struct ciss_softc *sc, struct ciss_request **crp)
2399{
2400    struct ciss_request *cr;
2401
2402    debug_called(2);
2403
2404    /*
2405     * Get a request and clean it up.
2406     */
2407    if ((cr = ciss_dequeue_free(sc)) == NULL)
2408	return(ENOMEM);
2409
2410    cr->cr_data = NULL;
2411    cr->cr_flags = 0;
2412    cr->cr_complete = NULL;
2413    cr->cr_private = NULL;
2414    cr->cr_sg_tag = CISS_SG_MAX;	/* Backstop to prevent accidents */
2415
2416    ciss_preen_command(cr);
2417    *crp = cr;
2418    return(0);
2419}
2420
2421static void
2422ciss_preen_command(struct ciss_request *cr)
2423{
2424    struct ciss_command	*cc;
2425    u_int32_t		cmdphys;
2426
2427    /*
2428     * Clean up the command structure.
2429     *
2430     * Note that we set up the error_info structure here, since the
2431     * length can be overwritten by any command.
2432     */
2433    cc = CISS_FIND_COMMAND(cr);
2434    cc->header.sg_in_list = 0;		/* kinda inefficient this way */
2435    cc->header.sg_total = 0;
2436    cc->header.host_tag = cr->cr_tag << 2;
2437    cc->header.host_tag_zeroes = 0;
2438    cmdphys = CISS_FIND_COMMANDPHYS(cr);
2439    cc->error_info.error_info_address = cmdphys + sizeof(struct ciss_command);
2440    cc->error_info.error_info_length = CISS_COMMAND_ALLOC_SIZE - sizeof(struct ciss_command);
2441}
2442
2443/************************************************************************
2444 * Release a request to the free list.
2445 */
2446static void
2447ciss_release_request(struct ciss_request *cr)
2448{
2449    struct ciss_softc	*sc;
2450
2451    debug_called(2);
2452
2453    sc = cr->cr_sc;
2454
2455    /* release the request to the free queue */
2456    ciss_requeue_free(cr);
2457}
2458
2459/************************************************************************
2460 * Allocate a request that will be used to send a BMIC command.  Do some
2461 * of the common setup here to avoid duplicating it everywhere else.
2462 */
2463static int
2464ciss_get_bmic_request(struct ciss_softc *sc, struct ciss_request **crp,
2465		      int opcode, void **bufp, size_t bufsize)
2466{
2467    struct ciss_request		*cr;
2468    struct ciss_command		*cc;
2469    struct ciss_bmic_cdb	*cbc;
2470    void			*buf;
2471    int				error;
2472    int				dataout;
2473
2474    debug_called(2);
2475
2476    cr = NULL;
2477    buf = NULL;
2478
2479    /*
2480     * Get a request.
2481     */
2482    if ((error = ciss_get_request(sc, &cr)) != 0)
2483	goto out;
2484
2485    /*
2486     * Allocate data storage if requested, determine the data direction.
2487     */
2488    dataout = 0;
2489    if ((bufsize > 0) && (bufp != NULL)) {
2490	if (*bufp == NULL) {
2491	    if ((buf = malloc(bufsize, CISS_MALLOC_CLASS, M_NOWAIT | M_ZERO)) == NULL) {
2492		error = ENOMEM;
2493		goto out;
2494	    }
2495	} else {
2496	    buf = *bufp;
2497	    dataout = 1;	/* we are given a buffer, so we are writing */
2498	}
2499    }
2500
2501    /*
2502     * Build a CISS BMIC command to get the logical drive ID.
2503     */
2504    cr->cr_data = buf;
2505    cr->cr_length = bufsize;
2506    if (!dataout)
2507	cr->cr_flags = CISS_REQ_DATAIN;
2508
2509    cc = CISS_FIND_COMMAND(cr);
2510    cc->header.address.physical.mode = CISS_HDR_ADDRESS_MODE_PERIPHERAL;
2511    cc->header.address.physical.bus = 0;
2512    cc->header.address.physical.target = 0;
2513    cc->cdb.cdb_length = sizeof(*cbc);
2514    cc->cdb.type = CISS_CDB_TYPE_COMMAND;
2515    cc->cdb.attribute = CISS_CDB_ATTRIBUTE_SIMPLE;
2516    cc->cdb.direction = dataout ? CISS_CDB_DIRECTION_WRITE : CISS_CDB_DIRECTION_READ;
2517    cc->cdb.timeout = 0;
2518
2519    cbc = (struct ciss_bmic_cdb *)&(cc->cdb.cdb[0]);
2520    bzero(cbc, sizeof(*cbc));
2521    cbc->opcode = dataout ? CISS_ARRAY_CONTROLLER_WRITE : CISS_ARRAY_CONTROLLER_READ;
2522    cbc->bmic_opcode = opcode;
2523    cbc->size = htons((u_int16_t)bufsize);
2524
2525out:
2526    if (error) {
2527	if (cr != NULL)
2528	    ciss_release_request(cr);
2529    } else {
2530	*crp = cr;
2531	if ((bufp != NULL) && (*bufp == NULL) && (buf != NULL))
2532	    *bufp = buf;
2533    }
2534    return(error);
2535}
2536
2537/************************************************************************
2538 * Handle a command passed in from userspace.
2539 */
2540static int
2541ciss_user_command(struct ciss_softc *sc, IOCTL_Command_struct *ioc)
2542{
2543    struct ciss_request		*cr;
2544    struct ciss_command		*cc;
2545    struct ciss_error_info	*ce;
2546    int				error = 0;
2547
2548    debug_called(1);
2549
2550    cr = NULL;
2551
2552    /*
2553     * Get a request.
2554     */
2555    while (ciss_get_request(sc, &cr) != 0)
2556	msleep(sc, &sc->ciss_mtx, PPAUSE, "cissREQ", hz);
2557    cc = CISS_FIND_COMMAND(cr);
2558
2559    /*
2560     * Allocate an in-kernel databuffer if required, copy in user data.
2561     */
2562    cr->cr_length = ioc->buf_size;
2563    if (ioc->buf_size > 0) {
2564	if ((cr->cr_data = malloc(ioc->buf_size, CISS_MALLOC_CLASS, M_NOWAIT)) == NULL) {
2565	    error = ENOMEM;
2566	    goto out;
2567	}
2568	if ((error = copyin(ioc->buf, cr->cr_data, ioc->buf_size))) {
2569	    debug(0, "copyin: bad data buffer %p/%d", ioc->buf, ioc->buf_size);
2570	    goto out;
2571	}
2572    }
2573
2574    /*
2575     * Build the request based on the user command.
2576     */
2577    bcopy(&ioc->LUN_info, &cc->header.address, sizeof(cc->header.address));
2578    bcopy(&ioc->Request, &cc->cdb, sizeof(cc->cdb));
2579
2580    /* XXX anything else to populate here? */
2581
2582    /*
2583     * Run the command.
2584     */
2585    if ((error = ciss_synch_request(cr, 60 * 1000))) {
2586	debug(0, "request failed - %d", error);
2587	goto out;
2588    }
2589
2590    /*
2591     * Check to see if the command succeeded.
2592     */
2593    ce = (struct ciss_error_info *)&(cc->sg[0]);
2594    if ((cc->header.host_tag & CISS_HDR_HOST_TAG_ERROR) == 0)
2595	bzero(ce, sizeof(*ce));
2596
2597    /*
2598     * Copy the results back to the user.
2599     */
2600    bcopy(ce, &ioc->error_info, sizeof(*ce));
2601    if ((ioc->buf_size > 0) &&
2602	(error = copyout(cr->cr_data, ioc->buf, ioc->buf_size))) {
2603	debug(0, "copyout: bad data buffer %p/%d", ioc->buf, ioc->buf_size);
2604	goto out;
2605    }
2606
2607    /* done OK */
2608    error = 0;
2609
2610out:
2611    if ((cr != NULL) && (cr->cr_data != NULL))
2612	free(cr->cr_data, CISS_MALLOC_CLASS);
2613    if (cr != NULL)
2614	ciss_release_request(cr);
2615    return(error);
2616}
2617
2618/************************************************************************
2619 * Map a request into bus-visible space, initialise the scatter/gather
2620 * list.
2621 */
2622static int
2623ciss_map_request(struct ciss_request *cr)
2624{
2625    struct ciss_softc	*sc;
2626    int			error = 0;
2627
2628    debug_called(2);
2629
2630    sc = cr->cr_sc;
2631
2632    /* check that mapping is necessary */
2633    if (cr->cr_flags & CISS_REQ_MAPPED)
2634	return(0);
2635
2636    cr->cr_flags |= CISS_REQ_MAPPED;
2637
2638    bus_dmamap_sync(sc->ciss_command_dmat, sc->ciss_command_map,
2639		    BUS_DMASYNC_PREWRITE);
2640
2641    if (cr->cr_data != NULL) {
2642	error = bus_dmamap_load(sc->ciss_buffer_dmat, cr->cr_datamap,
2643				cr->cr_data, cr->cr_length,
2644				ciss_request_map_helper, cr, 0);
2645	if (error != 0)
2646	    return (error);
2647    } else {
2648	/*
2649	 * Post the command to the adapter.
2650	 */
2651	cr->cr_sg_tag = CISS_SG_NONE;
2652	cr->cr_flags |= CISS_REQ_BUSY;
2653	if (sc->ciss_perf)
2654	    CISS_TL_PERF_POST_CMD(sc, cr);
2655	else
2656	    CISS_TL_SIMPLE_POST_CMD(sc, CISS_FIND_COMMANDPHYS(cr));
2657    }
2658
2659    return(0);
2660}
2661
2662static void
2663ciss_request_map_helper(void *arg, bus_dma_segment_t *segs, int nseg, int error)
2664{
2665    struct ciss_command	*cc;
2666    struct ciss_request *cr;
2667    struct ciss_softc	*sc;
2668    int			i;
2669
2670    debug_called(2);
2671
2672    cr = (struct ciss_request *)arg;
2673    sc = cr->cr_sc;
2674    cc = CISS_FIND_COMMAND(cr);
2675
2676    for (i = 0; i < nseg; i++) {
2677	cc->sg[i].address = segs[i].ds_addr;
2678	cc->sg[i].length = segs[i].ds_len;
2679	cc->sg[i].extension = 0;
2680    }
2681    /* we leave the s/g table entirely within the command */
2682    cc->header.sg_in_list = nseg;
2683    cc->header.sg_total = nseg;
2684
2685    if (cr->cr_flags & CISS_REQ_DATAIN)
2686	bus_dmamap_sync(sc->ciss_buffer_dmat, cr->cr_datamap, BUS_DMASYNC_PREREAD);
2687    if (cr->cr_flags & CISS_REQ_DATAOUT)
2688	bus_dmamap_sync(sc->ciss_buffer_dmat, cr->cr_datamap, BUS_DMASYNC_PREWRITE);
2689
2690    if (nseg == 1)
2691	cr->cr_sg_tag = CISS_SG_NONE;
2692    else if (nseg == 1)
2693	cr->cr_sg_tag = CISS_SG_1;
2694    else if (nseg == 2)
2695	cr->cr_sg_tag = CISS_SG_2;
2696    else if (nseg <= 4)
2697	cr->cr_sg_tag = CISS_SG_4;
2698    else if (nseg <= 8)
2699	cr->cr_sg_tag = CISS_SG_8;
2700    else if (nseg <= 16)
2701	cr->cr_sg_tag = CISS_SG_16;
2702    else if (nseg <= 32)
2703	cr->cr_sg_tag = CISS_SG_32;
2704    else
2705	cr->cr_sg_tag = CISS_SG_MAX;
2706
2707    /*
2708     * Post the command to the adapter.
2709     */
2710    cr->cr_flags |= CISS_REQ_BUSY;
2711    if (sc->ciss_perf)
2712	CISS_TL_PERF_POST_CMD(sc, cr);
2713    else
2714	CISS_TL_SIMPLE_POST_CMD(sc, CISS_FIND_COMMANDPHYS(cr));
2715}
2716
2717/************************************************************************
2718 * Unmap a request from bus-visible space.
2719 */
2720static void
2721ciss_unmap_request(struct ciss_request *cr)
2722{
2723    struct ciss_softc	*sc;
2724
2725    debug_called(2);
2726
2727    sc = cr->cr_sc;
2728
2729    /* check that unmapping is necessary */
2730    if ((cr->cr_flags & CISS_REQ_MAPPED) == 0)
2731	return;
2732
2733    bus_dmamap_sync(sc->ciss_command_dmat, sc->ciss_command_map,
2734		    BUS_DMASYNC_POSTWRITE);
2735
2736    if (cr->cr_data == NULL)
2737	goto out;
2738
2739    if (cr->cr_flags & CISS_REQ_DATAIN)
2740	bus_dmamap_sync(sc->ciss_buffer_dmat, cr->cr_datamap, BUS_DMASYNC_POSTREAD);
2741    if (cr->cr_flags & CISS_REQ_DATAOUT)
2742	bus_dmamap_sync(sc->ciss_buffer_dmat, cr->cr_datamap, BUS_DMASYNC_POSTWRITE);
2743
2744    bus_dmamap_unload(sc->ciss_buffer_dmat, cr->cr_datamap);
2745out:
2746    cr->cr_flags &= ~CISS_REQ_MAPPED;
2747}
2748
2749/************************************************************************
2750 * Attach the driver to CAM.
2751 *
2752 * We put all the logical drives on a single SCSI bus.
2753 */
2754static int
2755ciss_cam_init(struct ciss_softc *sc)
2756{
2757    int			i, maxbus;
2758
2759    debug_called(1);
2760
2761    /*
2762     * Allocate a devq.  We can reuse this for the masked physical
2763     * devices if we decide to export these as well.
2764     */
2765    if ((sc->ciss_cam_devq = cam_simq_alloc(sc->ciss_max_requests)) == NULL) {
2766	ciss_printf(sc, "can't allocate CAM SIM queue\n");
2767	return(ENOMEM);
2768    }
2769
2770    /*
2771     * Create a SIM.
2772     *
2773     * This naturally wastes a bit of memory.  The alternative is to allocate
2774     * and register each bus as it is found, and then track them on a linked
2775     * list.  Unfortunately, the driver has a few places where it needs to
2776     * look up the SIM based solely on bus number, and it's unclear whether
2777     * a list traversal would work for these situations.
2778     */
2779    maxbus = max(sc->ciss_max_logical_bus, sc->ciss_max_physical_bus +
2780		 CISS_PHYSICAL_BASE);
2781    sc->ciss_cam_sim = malloc(maxbus * sizeof(struct cam_sim*),
2782			      CISS_MALLOC_CLASS, M_NOWAIT | M_ZERO);
2783    if (sc->ciss_cam_sim == NULL) {
2784	ciss_printf(sc, "can't allocate memory for controller SIM\n");
2785	return(ENOMEM);
2786    }
2787
2788    for (i = 0; i < sc->ciss_max_logical_bus; i++) {
2789	if ((sc->ciss_cam_sim[i] = cam_sim_alloc(ciss_cam_action, ciss_cam_poll,
2790						 "ciss", sc,
2791						 device_get_unit(sc->ciss_dev),
2792						 &sc->ciss_mtx,
2793						 2,
2794						 sc->ciss_max_requests - 2,
2795						 sc->ciss_cam_devq)) == NULL) {
2796	    ciss_printf(sc, "can't allocate CAM SIM for controller %d\n", i);
2797	    return(ENOMEM);
2798	}
2799
2800	/*
2801	 * Register bus with this SIM.
2802	 */
2803	mtx_lock(&sc->ciss_mtx);
2804	if (i == 0 || sc->ciss_controllers[i].physical.bus != 0) {
2805	    if (xpt_bus_register(sc->ciss_cam_sim[i], sc->ciss_dev, i) != 0) {
2806		ciss_printf(sc, "can't register SCSI bus %d\n", i);
2807		mtx_unlock(&sc->ciss_mtx);
2808		return (ENXIO);
2809	    }
2810	}
2811	mtx_unlock(&sc->ciss_mtx);
2812    }
2813
2814    for (i = CISS_PHYSICAL_BASE; i < sc->ciss_max_physical_bus +
2815	 CISS_PHYSICAL_BASE; i++) {
2816	if ((sc->ciss_cam_sim[i] = cam_sim_alloc(ciss_cam_action, ciss_cam_poll,
2817						 "ciss", sc,
2818						 device_get_unit(sc->ciss_dev),
2819						 &sc->ciss_mtx, 1,
2820						 sc->ciss_max_requests - 2,
2821						 sc->ciss_cam_devq)) == NULL) {
2822	    ciss_printf(sc, "can't allocate CAM SIM for controller %d\n", i);
2823	    return (ENOMEM);
2824	}
2825
2826	mtx_lock(&sc->ciss_mtx);
2827	if (xpt_bus_register(sc->ciss_cam_sim[i], sc->ciss_dev, i) != 0) {
2828	    ciss_printf(sc, "can't register SCSI bus %d\n", i);
2829	    mtx_unlock(&sc->ciss_mtx);
2830	    return (ENXIO);
2831	}
2832	mtx_unlock(&sc->ciss_mtx);
2833    }
2834
2835    /*
2836     * Initiate a rescan of the bus.
2837     */
2838    mtx_lock(&sc->ciss_mtx);
2839    ciss_cam_rescan_all(sc);
2840    mtx_unlock(&sc->ciss_mtx);
2841
2842    return(0);
2843}
2844
2845/************************************************************************
2846 * Initiate a rescan of the 'logical devices' SIM
2847 */
2848static void
2849ciss_cam_rescan_target(struct ciss_softc *sc, int bus, int target)
2850{
2851    struct cam_path	*path;
2852    union ccb		*ccb;
2853
2854    debug_called(1);
2855
2856    if ((ccb = malloc(sizeof(union ccb), CISS_MALLOC_CLASS, M_NOWAIT | M_ZERO)) == NULL) {
2857	ciss_printf(sc, "rescan failed (can't allocate CCB)\n");
2858	return;
2859    }
2860
2861    if (xpt_create_path(&path, xpt_periph, cam_sim_path(sc->ciss_cam_sim[bus]),
2862			target, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
2863	ciss_printf(sc, "rescan failed (can't create path)\n");
2864	free(ccb, CISS_MALLOC_CLASS);
2865	return;
2866    }
2867
2868    xpt_setup_ccb(&ccb->ccb_h, path, 5/*priority (low)*/);
2869    ccb->ccb_h.func_code = XPT_SCAN_BUS;
2870    ccb->ccb_h.cbfcnp = ciss_cam_rescan_callback;
2871    ccb->crcn.flags = CAM_FLAG_NONE;
2872    xpt_action(ccb);
2873
2874    /* scan is now in progress */
2875}
2876
2877static void
2878ciss_cam_rescan_all(struct ciss_softc *sc)
2879{
2880    int i;
2881
2882    /* Rescan the logical buses */
2883    for (i = 0; i < sc->ciss_max_logical_bus; i++)
2884	ciss_cam_rescan_target(sc, i, CAM_TARGET_WILDCARD);
2885    /* Rescan the physical buses */
2886    for (i = CISS_PHYSICAL_BASE; i < sc->ciss_max_physical_bus +
2887	 CISS_PHYSICAL_BASE; i++)
2888	ciss_cam_rescan_target(sc, i, CAM_TARGET_WILDCARD);
2889}
2890
2891static void
2892ciss_cam_rescan_callback(struct cam_periph *periph, union ccb *ccb)
2893{
2894    xpt_free_path(ccb->ccb_h.path);
2895    free(ccb, CISS_MALLOC_CLASS);
2896}
2897
2898/************************************************************************
2899 * Handle requests coming from CAM
2900 */
2901static void
2902ciss_cam_action(struct cam_sim *sim, union ccb *ccb)
2903{
2904    struct ciss_softc	*sc;
2905    struct ccb_scsiio	*csio;
2906    int			bus, target;
2907    int			physical;
2908
2909    sc = cam_sim_softc(sim);
2910    bus = cam_sim_bus(sim);
2911    csio = (struct ccb_scsiio *)&ccb->csio;
2912    target = csio->ccb_h.target_id;
2913    physical = CISS_IS_PHYSICAL(bus);
2914
2915    switch (ccb->ccb_h.func_code) {
2916
2917	/* perform SCSI I/O */
2918    case XPT_SCSI_IO:
2919	if (!ciss_cam_action_io(sim, csio))
2920	    return;
2921	break;
2922
2923	/* perform geometry calculations */
2924    case XPT_CALC_GEOMETRY:
2925    {
2926	struct ccb_calc_geometry	*ccg = &ccb->ccg;
2927	struct ciss_ldrive		*ld;
2928
2929	debug(1, "XPT_CALC_GEOMETRY %d:%d:%d", cam_sim_bus(sim), ccb->ccb_h.target_id, ccb->ccb_h.target_lun);
2930
2931	ld = NULL;
2932	if (!physical)
2933	    ld = &sc->ciss_logical[bus][target];
2934
2935	/*
2936	 * Use the cached geometry settings unless the fault tolerance
2937	 * is invalid.
2938	 */
2939	if (physical || ld->cl_geometry.fault_tolerance == 0xFF) {
2940	    u_int32_t			secs_per_cylinder;
2941
2942	    ccg->heads = 255;
2943	    ccg->secs_per_track = 32;
2944	    secs_per_cylinder = ccg->heads * ccg->secs_per_track;
2945	    ccg->cylinders = ccg->volume_size / secs_per_cylinder;
2946	} else {
2947	    ccg->heads = ld->cl_geometry.heads;
2948	    ccg->secs_per_track = ld->cl_geometry.sectors;
2949	    ccg->cylinders = ntohs(ld->cl_geometry.cylinders);
2950	}
2951	ccb->ccb_h.status = CAM_REQ_CMP;
2952        break;
2953    }
2954
2955	/* handle path attribute inquiry */
2956    case XPT_PATH_INQ:
2957    {
2958	struct ccb_pathinq	*cpi = &ccb->cpi;
2959
2960	debug(1, "XPT_PATH_INQ %d:%d:%d", cam_sim_bus(sim), ccb->ccb_h.target_id, ccb->ccb_h.target_lun);
2961
2962	cpi->version_num = 1;
2963	cpi->hba_inquiry = PI_TAG_ABLE;	/* XXX is this correct? */
2964	cpi->target_sprt = 0;
2965	cpi->hba_misc = 0;
2966	cpi->max_target = CISS_MAX_LOGICAL;
2967	cpi->max_lun = 0;		/* 'logical drive' channel only */
2968	cpi->initiator_id = CISS_MAX_LOGICAL;
2969	strncpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
2970        strncpy(cpi->hba_vid, "msmith@freebsd.org", HBA_IDLEN);
2971        strncpy(cpi->dev_name, cam_sim_name(sim), DEV_IDLEN);
2972        cpi->unit_number = cam_sim_unit(sim);
2973        cpi->bus_id = cam_sim_bus(sim);
2974	cpi->base_transfer_speed = 132 * 1024;	/* XXX what to set this to? */
2975	cpi->transport = XPORT_SPI;
2976	cpi->transport_version = 2;
2977	cpi->protocol = PROTO_SCSI;
2978	cpi->protocol_version = SCSI_REV_2;
2979	cpi->maxio = (CISS_MAX_SG_ELEMENTS - 1) * PAGE_SIZE;
2980	ccb->ccb_h.status = CAM_REQ_CMP;
2981	break;
2982    }
2983
2984    case XPT_GET_TRAN_SETTINGS:
2985    {
2986	struct ccb_trans_settings	*cts = &ccb->cts;
2987	int				bus, target;
2988	struct ccb_trans_settings_spi *spi = &cts->xport_specific.spi;
2989	struct ccb_trans_settings_scsi *scsi = &cts->proto_specific.scsi;
2990
2991	bus = cam_sim_bus(sim);
2992	target = cts->ccb_h.target_id;
2993
2994	debug(1, "XPT_GET_TRAN_SETTINGS %d:%d", bus, target);
2995	/* disconnect always OK */
2996	cts->protocol = PROTO_SCSI;
2997	cts->protocol_version = SCSI_REV_2;
2998	cts->transport = XPORT_SPI;
2999	cts->transport_version = 2;
3000
3001	spi->valid = CTS_SPI_VALID_DISC;
3002	spi->flags = CTS_SPI_FLAGS_DISC_ENB;
3003
3004	scsi->valid = CTS_SCSI_VALID_TQ;
3005	scsi->flags = CTS_SCSI_FLAGS_TAG_ENB;
3006
3007	cts->ccb_h.status = CAM_REQ_CMP;
3008	break;
3009    }
3010
3011    default:		/* we can't do this */
3012	debug(1, "unspported func_code = 0x%x", ccb->ccb_h.func_code);
3013	ccb->ccb_h.status = CAM_REQ_INVALID;
3014	break;
3015    }
3016
3017    xpt_done(ccb);
3018}
3019
3020/************************************************************************
3021 * Handle a CAM SCSI I/O request.
3022 */
3023static int
3024ciss_cam_action_io(struct cam_sim *sim, struct ccb_scsiio *csio)
3025{
3026    struct ciss_softc	*sc;
3027    int			bus, target;
3028    struct ciss_request	*cr;
3029    struct ciss_command	*cc;
3030    int			error;
3031
3032    sc = cam_sim_softc(sim);
3033    bus = cam_sim_bus(sim);
3034    target = csio->ccb_h.target_id;
3035
3036    debug(2, "XPT_SCSI_IO %d:%d:%d", bus, target, csio->ccb_h.target_lun);
3037
3038    /* check that the CDB pointer is not to a physical address */
3039    if ((csio->ccb_h.flags & CAM_CDB_POINTER) && (csio->ccb_h.flags & CAM_CDB_PHYS)) {
3040	debug(3, "  CDB pointer is to physical address");
3041	csio->ccb_h.status = CAM_REQ_CMP_ERR;
3042    }
3043
3044    /* if there is data transfer, it must be to/from a virtual address */
3045    if ((csio->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
3046	if (csio->ccb_h.flags & CAM_DATA_PHYS) {		/* we can't map it */
3047	    debug(3, "  data pointer is to physical address");
3048	    csio->ccb_h.status = CAM_REQ_CMP_ERR;
3049	}
3050	if (csio->ccb_h.flags & CAM_SCATTER_VALID) {	/* we want to do the s/g setup */
3051	    debug(3, "  data has premature s/g setup");
3052	    csio->ccb_h.status = CAM_REQ_CMP_ERR;
3053	}
3054    }
3055
3056    /* abandon aborted ccbs or those that have failed validation */
3057    if ((csio->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_INPROG) {
3058	debug(3, "abandoning CCB due to abort/validation failure");
3059	return(EINVAL);
3060    }
3061
3062    /* handle emulation of some SCSI commands ourself */
3063    if (ciss_cam_emulate(sc, csio))
3064	return(0);
3065
3066    /*
3067     * Get a request to manage this command.  If we can't, return the
3068     * ccb, freeze the queue and flag so that we unfreeze it when a
3069     * request completes.
3070     */
3071    if ((error = ciss_get_request(sc, &cr)) != 0) {
3072	xpt_freeze_simq(sim, 1);
3073	csio->ccb_h.status |= CAM_REQUEUE_REQ;
3074	return(error);
3075    }
3076
3077    /*
3078     * Build the command.
3079     */
3080    cc = CISS_FIND_COMMAND(cr);
3081    cr->cr_data = csio->data_ptr;
3082    cr->cr_length = csio->dxfer_len;
3083    cr->cr_complete = ciss_cam_complete;
3084    cr->cr_private = csio;
3085
3086    /*
3087     * Target the right logical volume.
3088     */
3089    if (CISS_IS_PHYSICAL(bus))
3090	cc->header.address =
3091	    sc->ciss_physical[CISS_CAM_TO_PBUS(bus)][target].cp_address;
3092    else
3093	cc->header.address =
3094	    sc->ciss_logical[bus][target].cl_address;
3095    cc->cdb.cdb_length = csio->cdb_len;
3096    cc->cdb.type = CISS_CDB_TYPE_COMMAND;
3097    cc->cdb.attribute = CISS_CDB_ATTRIBUTE_SIMPLE;	/* XXX ordered tags? */
3098    if ((csio->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_OUT) {
3099	cr->cr_flags = CISS_REQ_DATAOUT;
3100	cc->cdb.direction = CISS_CDB_DIRECTION_WRITE;
3101    } else if ((csio->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
3102	cr->cr_flags = CISS_REQ_DATAIN;
3103	cc->cdb.direction = CISS_CDB_DIRECTION_READ;
3104    } else {
3105	cr->cr_flags = 0;
3106	cc->cdb.direction = CISS_CDB_DIRECTION_NONE;
3107    }
3108    cc->cdb.timeout = (csio->ccb_h.timeout / 1000) + 1;
3109    if (csio->ccb_h.flags & CAM_CDB_POINTER) {
3110	bcopy(csio->cdb_io.cdb_ptr, &cc->cdb.cdb[0], csio->cdb_len);
3111    } else {
3112	bcopy(csio->cdb_io.cdb_bytes, &cc->cdb.cdb[0], csio->cdb_len);
3113    }
3114
3115    /*
3116     * Submit the request to the adapter.
3117     *
3118     * Note that this may fail if we're unable to map the request (and
3119     * if we ever learn a transport layer other than simple, may fail
3120     * if the adapter rejects the command).
3121     */
3122    if ((error = ciss_start(cr)) != 0) {
3123	xpt_freeze_simq(sim, 1);
3124	if (error == EINPROGRESS) {
3125	    csio->ccb_h.status |= CAM_RELEASE_SIMQ;
3126	    error = 0;
3127	} else {
3128	    csio->ccb_h.status |= CAM_REQUEUE_REQ;
3129	    ciss_release_request(cr);
3130	}
3131	return(error);
3132    }
3133
3134    return(0);
3135}
3136
3137/************************************************************************
3138 * Emulate SCSI commands the adapter doesn't handle as we might like.
3139 */
3140static int
3141ciss_cam_emulate(struct ciss_softc *sc, struct ccb_scsiio *csio)
3142{
3143    int		bus, target;
3144    u_int8_t	opcode;
3145
3146    target = csio->ccb_h.target_id;
3147    bus = cam_sim_bus(xpt_path_sim(csio->ccb_h.path));
3148    opcode = (csio->ccb_h.flags & CAM_CDB_POINTER) ?
3149	*(u_int8_t *)csio->cdb_io.cdb_ptr : csio->cdb_io.cdb_bytes[0];
3150
3151    if (CISS_IS_PHYSICAL(bus)) {
3152	if (sc->ciss_physical[CISS_CAM_TO_PBUS(bus)][target].cp_online != 1) {
3153	    csio->ccb_h.status = CAM_SEL_TIMEOUT;
3154	    xpt_done((union ccb *)csio);
3155	    return(1);
3156	} else
3157	    return(0);
3158    }
3159
3160    /*
3161     * Handle requests for volumes that don't exist or are not online.
3162     * A selection timeout is slightly better than an illegal request.
3163     * Other errors might be better.
3164     */
3165    if (sc->ciss_logical[bus][target].cl_status != CISS_LD_ONLINE) {
3166	csio->ccb_h.status = CAM_SEL_TIMEOUT;
3167	xpt_done((union ccb *)csio);
3168	return(1);
3169    }
3170
3171    /* if we have to fake Synchronise Cache */
3172    if (sc->ciss_flags & CISS_FLAG_FAKE_SYNCH) {
3173	/*
3174	 * If this is a Synchronise Cache command, typically issued when
3175	 * a device is closed, flush the adapter and complete now.
3176	 */
3177	if (((csio->ccb_h.flags & CAM_CDB_POINTER) ?
3178	     *(u_int8_t *)csio->cdb_io.cdb_ptr : csio->cdb_io.cdb_bytes[0]) == SYNCHRONIZE_CACHE) {
3179	    ciss_flush_adapter(sc);
3180	    csio->ccb_h.status = CAM_REQ_CMP;
3181	    xpt_done((union ccb *)csio);
3182	    return(1);
3183	}
3184    }
3185
3186    return(0);
3187}
3188
3189/************************************************************************
3190 * Check for possibly-completed commands.
3191 */
3192static void
3193ciss_cam_poll(struct cam_sim *sim)
3194{
3195    cr_qhead_t qh;
3196    struct ciss_softc	*sc = cam_sim_softc(sim);
3197
3198    debug_called(2);
3199
3200    STAILQ_INIT(&qh);
3201    if (sc->ciss_perf)
3202	ciss_perf_done(sc, &qh);
3203    else
3204	ciss_done(sc, &qh);
3205    ciss_complete(sc, &qh);
3206}
3207
3208/************************************************************************
3209 * Handle completion of a command - pass results back through the CCB
3210 */
3211static void
3212ciss_cam_complete(struct ciss_request *cr)
3213{
3214    struct ciss_softc		*sc;
3215    struct ciss_command		*cc;
3216    struct ciss_error_info	*ce;
3217    struct ccb_scsiio		*csio;
3218    int				scsi_status;
3219    int				command_status;
3220
3221    debug_called(2);
3222
3223    sc = cr->cr_sc;
3224    cc = CISS_FIND_COMMAND(cr);
3225    ce = (struct ciss_error_info *)&(cc->sg[0]);
3226    csio = (struct ccb_scsiio *)cr->cr_private;
3227
3228    /*
3229     * Extract status values from request.
3230     */
3231    ciss_report_request(cr, &command_status, &scsi_status);
3232    csio->scsi_status = scsi_status;
3233
3234    /*
3235     * Handle specific SCSI status values.
3236     */
3237    switch(scsi_status) {
3238	/* no status due to adapter error */
3239    case -1:
3240	debug(0, "adapter error");
3241	csio->ccb_h.status = CAM_REQ_CMP_ERR;
3242	break;
3243
3244	/* no status due to command completed OK */
3245    case SCSI_STATUS_OK:		/* CISS_SCSI_STATUS_GOOD */
3246	debug(2, "SCSI_STATUS_OK");
3247	csio->ccb_h.status = CAM_REQ_CMP;
3248	break;
3249
3250	/* check condition, sense data included */
3251    case SCSI_STATUS_CHECK_COND:	/* CISS_SCSI_STATUS_CHECK_CONDITION */
3252	debug(0, "SCSI_STATUS_CHECK_COND  sense size %d  resid %d\n",
3253	      ce->sense_length, ce->residual_count);
3254	bzero(&csio->sense_data, SSD_FULL_SIZE);
3255	bcopy(&ce->sense_info[0], &csio->sense_data, ce->sense_length);
3256	csio->sense_len = ce->sense_length;
3257	csio->resid = ce->residual_count;
3258	csio->ccb_h.status = CAM_SCSI_STATUS_ERROR | CAM_AUTOSNS_VALID;
3259#ifdef CISS_DEBUG
3260	{
3261	    struct scsi_sense_data	*sns = (struct scsi_sense_data *)&ce->sense_info[0];
3262	    debug(0, "sense key %x", sns->flags & SSD_KEY);
3263	}
3264#endif
3265	break;
3266
3267    case SCSI_STATUS_BUSY:		/* CISS_SCSI_STATUS_BUSY */
3268	debug(0, "SCSI_STATUS_BUSY");
3269	csio->ccb_h.status = CAM_SCSI_BUSY;
3270	break;
3271
3272    default:
3273	debug(0, "unknown status 0x%x", csio->scsi_status);
3274	csio->ccb_h.status = CAM_REQ_CMP_ERR;
3275	break;
3276    }
3277
3278    /* handle post-command fixup */
3279    ciss_cam_complete_fixup(sc, csio);
3280
3281    /* tell CAM we're ready for more commands */
3282    csio->ccb_h.status |= CAM_RELEASE_SIMQ;
3283
3284    ciss_release_request(cr);
3285    xpt_done((union ccb *)csio);
3286}
3287
3288/********************************************************************************
3289 * Fix up the result of some commands here.
3290 */
3291static void
3292ciss_cam_complete_fixup(struct ciss_softc *sc, struct ccb_scsiio *csio)
3293{
3294    struct scsi_inquiry_data	*inq;
3295    struct ciss_ldrive		*cl;
3296    int				bus, target;
3297
3298    if (((csio->ccb_h.flags & CAM_CDB_POINTER) ?
3299	 *(u_int8_t *)csio->cdb_io.cdb_ptr : csio->cdb_io.cdb_bytes[0]) == INQUIRY) {
3300
3301	inq = (struct scsi_inquiry_data *)csio->data_ptr;
3302	target = csio->ccb_h.target_id;
3303	bus = cam_sim_bus(xpt_path_sim(csio->ccb_h.path));
3304
3305	/*
3306	 * Don't let hard drives be seen by the DA driver.  They will still be
3307	 * attached by the PASS driver.
3308	 */
3309	if (CISS_IS_PHYSICAL(bus)) {
3310	    if (SID_TYPE(inq) == T_DIRECT)
3311		inq->device = (inq->device & 0xe0) | T_NODEVICE;
3312	    return;
3313	}
3314
3315	cl = &sc->ciss_logical[bus][target];
3316
3317	padstr(inq->vendor, "COMPAQ", 8);
3318	padstr(inq->product, ciss_name_ldrive_org(cl->cl_ldrive->fault_tolerance), 8);
3319	padstr(inq->revision, ciss_name_ldrive_status(cl->cl_lstatus->status), 16);
3320    }
3321}
3322
3323
3324/********************************************************************************
3325 * Find a peripheral attached at (target)
3326 */
3327static struct cam_periph *
3328ciss_find_periph(struct ciss_softc *sc, int bus, int target)
3329{
3330    struct cam_periph	*periph;
3331    struct cam_path	*path;
3332    int			status;
3333
3334    status = xpt_create_path(&path, NULL, cam_sim_path(sc->ciss_cam_sim[bus]),
3335			     target, 0);
3336    if (status == CAM_REQ_CMP) {
3337	periph = cam_periph_find(path, NULL);
3338	xpt_free_path(path);
3339    } else {
3340	periph = NULL;
3341    }
3342    return(periph);
3343}
3344
3345/********************************************************************************
3346 * Name the device at (target)
3347 *
3348 * XXX is this strictly correct?
3349 */
3350static int
3351ciss_name_device(struct ciss_softc *sc, int bus, int target)
3352{
3353    struct cam_periph	*periph;
3354
3355    if (CISS_IS_PHYSICAL(bus))
3356	return (0);
3357    if ((periph = ciss_find_periph(sc, bus, target)) != NULL) {
3358	sprintf(sc->ciss_logical[bus][target].cl_name, "%s%d",
3359		periph->periph_name, periph->unit_number);
3360	return(0);
3361    }
3362    sc->ciss_logical[bus][target].cl_name[0] = 0;
3363    return(ENOENT);
3364}
3365
3366/************************************************************************
3367 * Periodic status monitoring.
3368 */
3369static void
3370ciss_periodic(void *arg)
3371{
3372    struct ciss_softc	*sc;
3373    struct ciss_request	*cr = NULL;
3374    struct ciss_command	*cc = NULL;
3375    int			error = 0;
3376
3377    debug_called(1);
3378
3379    sc = (struct ciss_softc *)arg;
3380
3381    /*
3382     * Check the adapter heartbeat.
3383     */
3384    if (sc->ciss_cfg->heartbeat == sc->ciss_heartbeat) {
3385	sc->ciss_heart_attack++;
3386	debug(0, "adapter heart attack in progress 0x%x/%d",
3387	      sc->ciss_heartbeat, sc->ciss_heart_attack);
3388	if (sc->ciss_heart_attack == 3) {
3389	    ciss_printf(sc, "ADAPTER HEARTBEAT FAILED\n");
3390	    ciss_disable_adapter(sc);
3391	    return;
3392	}
3393    } else {
3394	sc->ciss_heartbeat = sc->ciss_cfg->heartbeat;
3395	sc->ciss_heart_attack = 0;
3396	debug(3, "new heartbeat 0x%x", sc->ciss_heartbeat);
3397    }
3398
3399    /*
3400     * Send the NOP message and wait for a response.
3401     */
3402    if (ciss_nop_message_heartbeat != 0 && (error = ciss_get_request(sc, &cr)) == 0) {
3403	cc = CISS_FIND_COMMAND(cr);
3404	cr->cr_complete = ciss_nop_complete;
3405	cc->cdb.cdb_length = 1;
3406	cc->cdb.type = CISS_CDB_TYPE_MESSAGE;
3407	cc->cdb.attribute = CISS_CDB_ATTRIBUTE_SIMPLE;
3408	cc->cdb.direction = CISS_CDB_DIRECTION_WRITE;
3409	cc->cdb.timeout = 0;
3410	cc->cdb.cdb[0] = CISS_OPCODE_MESSAGE_NOP;
3411
3412	if ((error = ciss_start(cr)) != 0) {
3413	    ciss_printf(sc, "SENDING NOP MESSAGE FAILED\n");
3414	}
3415    }
3416
3417    /*
3418     * If the notify event request has died for some reason, or has
3419     * not started yet, restart it.
3420     */
3421    if (!(sc->ciss_flags & CISS_FLAG_NOTIFY_OK)) {
3422	debug(0, "(re)starting Event Notify chain");
3423	ciss_notify_event(sc);
3424    }
3425
3426    /*
3427     * Reschedule.
3428     */
3429    callout_reset(&sc->ciss_periodic, CISS_HEARTBEAT_RATE * hz, ciss_periodic, sc);
3430}
3431
3432static void
3433ciss_nop_complete(struct ciss_request *cr)
3434{
3435    struct ciss_softc		*sc;
3436    static int			first_time = 1;
3437
3438    sc = cr->cr_sc;
3439    if (ciss_report_request(cr, NULL, NULL) != 0) {
3440	if (first_time == 1) {
3441	    first_time = 0;
3442	    ciss_printf(sc, "SENDING NOP MESSAGE FAILED (not logging anymore)\n");
3443	}
3444    }
3445
3446    ciss_release_request(cr);
3447}
3448
3449/************************************************************************
3450 * Disable the adapter.
3451 *
3452 * The all requests in completed queue is failed with hardware error.
3453 * This will cause failover in a multipath configuration.
3454 */
3455static void
3456ciss_disable_adapter(struct ciss_softc *sc)
3457{
3458    cr_qhead_t			qh;
3459    struct ciss_request		*cr;
3460    struct ciss_command		*cc;
3461    struct ciss_error_info	*ce;
3462    int				i;
3463
3464    CISS_TL_SIMPLE_DISABLE_INTERRUPTS(sc);
3465    pci_disable_busmaster(sc->ciss_dev);
3466    sc->ciss_flags &= ~CISS_FLAG_RUNNING;
3467
3468    for (i = 1; i < sc->ciss_max_requests; i++) {
3469	cr = &sc->ciss_request[i];
3470	if ((cr->cr_flags & CISS_REQ_BUSY) == 0)
3471	    continue;
3472
3473	cc = CISS_FIND_COMMAND(cr);
3474	ce = (struct ciss_error_info *)&(cc->sg[0]);
3475	ce->command_status = CISS_CMD_STATUS_HARDWARE_ERROR;
3476	ciss_enqueue_complete(cr, &qh);
3477    }
3478
3479    for (;;) {
3480	if ((cr = ciss_dequeue_complete(sc, &qh)) == NULL)
3481	    break;
3482
3483	/*
3484	 * If the request has a callback, invoke it.
3485	 */
3486	if (cr->cr_complete != NULL) {
3487	    cr->cr_complete(cr);
3488	    continue;
3489	}
3490
3491	/*
3492	 * If someone is sleeping on this request, wake them up.
3493	 */
3494	if (cr->cr_flags & CISS_REQ_SLEEP) {
3495	    cr->cr_flags &= ~CISS_REQ_SLEEP;
3496	    wakeup(cr);
3497	    continue;
3498	}
3499    }
3500}
3501
3502/************************************************************************
3503 * Request a notification response from the adapter.
3504 *
3505 * If (cr) is NULL, this is the first request of the adapter, so
3506 * reset the adapter's message pointer and start with the oldest
3507 * message available.
3508 */
3509static void
3510ciss_notify_event(struct ciss_softc *sc)
3511{
3512    struct ciss_request		*cr;
3513    struct ciss_command		*cc;
3514    struct ciss_notify_cdb	*cnc;
3515    int				error;
3516
3517    debug_called(1);
3518
3519    cr = sc->ciss_periodic_notify;
3520
3521    /* get a request if we don't already have one */
3522    if (cr == NULL) {
3523	if ((error = ciss_get_request(sc, &cr)) != 0) {
3524	    debug(0, "can't get notify event request");
3525	    goto out;
3526	}
3527	sc->ciss_periodic_notify = cr;
3528	cr->cr_complete = ciss_notify_complete;
3529	debug(1, "acquired request %d", cr->cr_tag);
3530    }
3531
3532    /*
3533     * Get a databuffer if we don't already have one, note that the
3534     * adapter command wants a larger buffer than the actual
3535     * structure.
3536     */
3537    if (cr->cr_data == NULL) {
3538	if ((cr->cr_data = malloc(CISS_NOTIFY_DATA_SIZE, CISS_MALLOC_CLASS, M_NOWAIT)) == NULL) {
3539	    debug(0, "can't get notify event request buffer");
3540	    error = ENOMEM;
3541	    goto out;
3542	}
3543	cr->cr_length = CISS_NOTIFY_DATA_SIZE;
3544    }
3545
3546    /* re-setup the request's command (since we never release it) XXX overkill*/
3547    ciss_preen_command(cr);
3548
3549    /* (re)build the notify event command */
3550    cc = CISS_FIND_COMMAND(cr);
3551    cc->header.address.physical.mode = CISS_HDR_ADDRESS_MODE_PERIPHERAL;
3552    cc->header.address.physical.bus = 0;
3553    cc->header.address.physical.target = 0;
3554
3555    cc->cdb.cdb_length = sizeof(*cnc);
3556    cc->cdb.type = CISS_CDB_TYPE_COMMAND;
3557    cc->cdb.attribute = CISS_CDB_ATTRIBUTE_SIMPLE;
3558    cc->cdb.direction = CISS_CDB_DIRECTION_READ;
3559    cc->cdb.timeout = 0;	/* no timeout, we hope */
3560
3561    cnc = (struct ciss_notify_cdb *)&(cc->cdb.cdb[0]);
3562    bzero(cr->cr_data, CISS_NOTIFY_DATA_SIZE);
3563    cnc->opcode = CISS_OPCODE_READ;
3564    cnc->command = CISS_COMMAND_NOTIFY_ON_EVENT;
3565    cnc->timeout = 0;		/* no timeout, we hope */
3566    cnc->synchronous = 0;
3567    cnc->ordered = 0;
3568    cnc->seek_to_oldest = 0;
3569    if ((sc->ciss_flags & CISS_FLAG_RUNNING) == 0)
3570	cnc->new_only = 1;
3571    else
3572	cnc->new_only = 0;
3573    cnc->length = htonl(CISS_NOTIFY_DATA_SIZE);
3574
3575    /* submit the request */
3576    error = ciss_start(cr);
3577
3578 out:
3579    if (error) {
3580	if (cr != NULL) {
3581	    if (cr->cr_data != NULL)
3582		free(cr->cr_data, CISS_MALLOC_CLASS);
3583	    ciss_release_request(cr);
3584	}
3585	sc->ciss_periodic_notify = NULL;
3586	debug(0, "can't submit notify event request");
3587	sc->ciss_flags &= ~CISS_FLAG_NOTIFY_OK;
3588    } else {
3589	debug(1, "notify event submitted");
3590	sc->ciss_flags |= CISS_FLAG_NOTIFY_OK;
3591    }
3592}
3593
3594static void
3595ciss_notify_complete(struct ciss_request *cr)
3596{
3597    struct ciss_command	*cc;
3598    struct ciss_notify	*cn;
3599    struct ciss_softc	*sc;
3600    int			scsi_status;
3601    int			command_status;
3602    debug_called(1);
3603
3604    cc = CISS_FIND_COMMAND(cr);
3605    cn = (struct ciss_notify *)cr->cr_data;
3606    sc = cr->cr_sc;
3607
3608    /*
3609     * Report request results, decode status.
3610     */
3611    ciss_report_request(cr, &command_status, &scsi_status);
3612
3613    /*
3614     * Abort the chain on a fatal error.
3615     *
3616     * XXX which of these are actually errors?
3617     */
3618    if ((command_status != CISS_CMD_STATUS_SUCCESS) &&
3619	(command_status != CISS_CMD_STATUS_TARGET_STATUS) &&
3620	(command_status != CISS_CMD_STATUS_TIMEOUT)) {	/* XXX timeout? */
3621	ciss_printf(sc, "fatal error in Notify Event request (%s)\n",
3622		    ciss_name_command_status(command_status));
3623	ciss_release_request(cr);
3624	sc->ciss_flags &= ~CISS_FLAG_NOTIFY_OK;
3625	return;
3626    }
3627
3628    /*
3629     * If the adapter gave us a text message, print it.
3630     */
3631    if (cn->message[0] != 0)
3632	ciss_printf(sc, "*** %.80s\n", cn->message);
3633
3634    debug(0, "notify event class %d subclass %d detail %d",
3635		cn->class, cn->subclass, cn->detail);
3636
3637    /*
3638     * If the response indicates that the notifier has been aborted,
3639     * release the notifier command.
3640     */
3641    if ((cn->class == CISS_NOTIFY_NOTIFIER) &&
3642	(cn->subclass == CISS_NOTIFY_NOTIFIER_STATUS) &&
3643	(cn->detail == 1)) {
3644	debug(0, "notifier exiting");
3645	sc->ciss_flags &= ~CISS_FLAG_NOTIFY_OK;
3646	ciss_release_request(cr);
3647	sc->ciss_periodic_notify = NULL;
3648	wakeup(&sc->ciss_periodic_notify);
3649    } else {
3650	/* Handle notify events in a kernel thread */
3651	ciss_enqueue_notify(cr);
3652	sc->ciss_periodic_notify = NULL;
3653	wakeup(&sc->ciss_periodic_notify);
3654	wakeup(&sc->ciss_notify);
3655    }
3656    /*
3657     * Send a new notify event command, if we're not aborting.
3658     */
3659    if (!(sc->ciss_flags & CISS_FLAG_ABORTING)) {
3660	ciss_notify_event(sc);
3661    }
3662}
3663
3664/************************************************************************
3665 * Abort the Notify Event chain.
3666 *
3667 * Note that we can't just abort the command in progress; we have to
3668 * explicitly issue an Abort Notify Event command in order for the
3669 * adapter to clean up correctly.
3670 *
3671 * If we are called with CISS_FLAG_ABORTING set in the adapter softc,
3672 * the chain will not restart itself.
3673 */
3674static int
3675ciss_notify_abort(struct ciss_softc *sc)
3676{
3677    struct ciss_request		*cr;
3678    struct ciss_command		*cc;
3679    struct ciss_notify_cdb	*cnc;
3680    int				error, command_status, scsi_status;
3681
3682    debug_called(1);
3683
3684    cr = NULL;
3685    error = 0;
3686
3687    /* verify that there's an outstanding command */
3688    if (!(sc->ciss_flags & CISS_FLAG_NOTIFY_OK))
3689	goto out;
3690
3691    /* get a command to issue the abort with */
3692    if ((error = ciss_get_request(sc, &cr)))
3693	goto out;
3694
3695    /* get a buffer for the result */
3696    if ((cr->cr_data = malloc(CISS_NOTIFY_DATA_SIZE, CISS_MALLOC_CLASS, M_NOWAIT)) == NULL) {
3697	debug(0, "can't get notify event request buffer");
3698	error = ENOMEM;
3699	goto out;
3700    }
3701    cr->cr_length = CISS_NOTIFY_DATA_SIZE;
3702
3703    /* build the CDB */
3704    cc = CISS_FIND_COMMAND(cr);
3705    cc->header.address.physical.mode = CISS_HDR_ADDRESS_MODE_PERIPHERAL;
3706    cc->header.address.physical.bus = 0;
3707    cc->header.address.physical.target = 0;
3708    cc->cdb.cdb_length = sizeof(*cnc);
3709    cc->cdb.type = CISS_CDB_TYPE_COMMAND;
3710    cc->cdb.attribute = CISS_CDB_ATTRIBUTE_SIMPLE;
3711    cc->cdb.direction = CISS_CDB_DIRECTION_READ;
3712    cc->cdb.timeout = 0;	/* no timeout, we hope */
3713
3714    cnc = (struct ciss_notify_cdb *)&(cc->cdb.cdb[0]);
3715    bzero(cnc, sizeof(*cnc));
3716    cnc->opcode = CISS_OPCODE_WRITE;
3717    cnc->command = CISS_COMMAND_ABORT_NOTIFY;
3718    cnc->length = htonl(CISS_NOTIFY_DATA_SIZE);
3719
3720    ciss_print_request(cr);
3721
3722    /*
3723     * Submit the request and wait for it to complete.
3724     */
3725    if ((error = ciss_synch_request(cr, 60 * 1000)) != 0) {
3726	ciss_printf(sc, "Abort Notify Event command failed (%d)\n", error);
3727	goto out;
3728    }
3729
3730    /*
3731     * Check response.
3732     */
3733    ciss_report_request(cr, &command_status, &scsi_status);
3734    switch(command_status) {
3735    case CISS_CMD_STATUS_SUCCESS:
3736	break;
3737    case CISS_CMD_STATUS_INVALID_COMMAND:
3738	/*
3739	 * Some older adapters don't support the CISS version of this
3740	 * command.  Fall back to using the BMIC version.
3741	 */
3742	error = ciss_notify_abort_bmic(sc);
3743	if (error != 0)
3744	    goto out;
3745	break;
3746
3747    case CISS_CMD_STATUS_TARGET_STATUS:
3748	/*
3749	 * This can happen if the adapter thinks there wasn't an outstanding
3750	 * Notify Event command but we did.  We clean up here.
3751	 */
3752	if (scsi_status == CISS_SCSI_STATUS_CHECK_CONDITION) {
3753	    if (sc->ciss_periodic_notify != NULL)
3754		ciss_release_request(sc->ciss_periodic_notify);
3755	    error = 0;
3756	    goto out;
3757	}
3758	/* FALLTHROUGH */
3759
3760    default:
3761	ciss_printf(sc, "Abort Notify Event command failed (%s)\n",
3762		    ciss_name_command_status(command_status));
3763	error = EIO;
3764	goto out;
3765    }
3766
3767    /*
3768     * Sleep waiting for the notifier command to complete.  Note
3769     * that if it doesn't, we may end up in a bad situation, since
3770     * the adapter may deliver it later.  Also note that the adapter
3771     * requires the Notify Event command to be cancelled in order to
3772     * maintain internal bookkeeping.
3773     */
3774    while (sc->ciss_periodic_notify != NULL) {
3775	error = msleep(&sc->ciss_periodic_notify, &sc->ciss_mtx, PRIBIO, "cissNEA", hz * 5);
3776	if (error == EWOULDBLOCK) {
3777	    ciss_printf(sc, "Notify Event command failed to abort, adapter may wedge.\n");
3778	    break;
3779	}
3780    }
3781
3782 out:
3783    /* release the cancel request */
3784    if (cr != NULL) {
3785	if (cr->cr_data != NULL)
3786	    free(cr->cr_data, CISS_MALLOC_CLASS);
3787	ciss_release_request(cr);
3788    }
3789    if (error == 0)
3790	sc->ciss_flags &= ~CISS_FLAG_NOTIFY_OK;
3791    return(error);
3792}
3793
3794/************************************************************************
3795 * Abort the Notify Event chain using a BMIC command.
3796 */
3797static int
3798ciss_notify_abort_bmic(struct ciss_softc *sc)
3799{
3800    struct ciss_request			*cr;
3801    int					error, command_status;
3802
3803    debug_called(1);
3804
3805    cr = NULL;
3806    error = 0;
3807
3808    /* verify that there's an outstanding command */
3809    if (!(sc->ciss_flags & CISS_FLAG_NOTIFY_OK))
3810	goto out;
3811
3812    /*
3813     * Build a BMIC command to cancel the Notify on Event command.
3814     *
3815     * Note that we are sending a CISS opcode here.  Odd.
3816     */
3817    if ((error = ciss_get_bmic_request(sc, &cr, CISS_COMMAND_ABORT_NOTIFY,
3818				       NULL, 0)) != 0)
3819	goto out;
3820
3821    /*
3822     * Submit the request and wait for it to complete.
3823     */
3824    if ((error = ciss_synch_request(cr, 60 * 1000)) != 0) {
3825	ciss_printf(sc, "error sending BMIC Cancel Notify on Event command (%d)\n", error);
3826	goto out;
3827    }
3828
3829    /*
3830     * Check response.
3831     */
3832    ciss_report_request(cr, &command_status, NULL);
3833    switch(command_status) {
3834    case CISS_CMD_STATUS_SUCCESS:
3835	break;
3836    default:
3837	ciss_printf(sc, "error cancelling Notify on Event (%s)\n",
3838		    ciss_name_command_status(command_status));
3839	error = EIO;
3840	goto out;
3841    }
3842
3843out:
3844    if (cr != NULL)
3845	ciss_release_request(cr);
3846    return(error);
3847}
3848
3849/************************************************************************
3850 * Handle rescanning all the logical volumes when a notify event
3851 * causes the drives to come online or offline.
3852 */
3853static void
3854ciss_notify_rescan_logical(struct ciss_softc *sc)
3855{
3856    struct ciss_lun_report      *cll;
3857    struct ciss_ldrive		*ld;
3858    int                         i, j, ndrives;
3859
3860    /*
3861     * We must rescan all logical volumes to get the right logical
3862     * drive address.
3863     */
3864    cll = ciss_report_luns(sc, CISS_OPCODE_REPORT_LOGICAL_LUNS,
3865                           CISS_MAX_LOGICAL);
3866    if (cll == NULL)
3867        return;
3868
3869    ndrives = (ntohl(cll->list_size) / sizeof(union ciss_device_address));
3870
3871    /*
3872     * Delete any of the drives which were destroyed by the
3873     * firmware.
3874     */
3875    for (i = 0; i < sc->ciss_max_logical_bus; i++) {
3876	for (j = 0; j < CISS_MAX_LOGICAL; j++) {
3877	    ld = &sc->ciss_logical[i][j];
3878
3879	    if (ld->cl_update == 0)
3880		continue;
3881
3882	    if (ld->cl_status != CISS_LD_ONLINE) {
3883		ciss_cam_rescan_target(sc, i, j);
3884		ld->cl_update = 0;
3885		if (ld->cl_ldrive)
3886		    free(ld->cl_ldrive, CISS_MALLOC_CLASS);
3887		if (ld->cl_lstatus)
3888		    free(ld->cl_lstatus, CISS_MALLOC_CLASS);
3889
3890		ld->cl_ldrive = NULL;
3891		ld->cl_lstatus = NULL;
3892	    }
3893	}
3894    }
3895
3896    /*
3897     * Scan for new drives.
3898     */
3899    for (i = 0; i < ndrives; i++) {
3900	int	bus, target;
3901
3902	bus 	= CISS_LUN_TO_BUS(cll->lun[i].logical.lun);
3903	target	= CISS_LUN_TO_TARGET(cll->lun[i].logical.lun);
3904	ld	= &sc->ciss_logical[bus][target];
3905
3906	if (ld->cl_update == 0)
3907		continue;
3908
3909	ld->cl_update		= 0;
3910	ld->cl_address		= cll->lun[i];
3911	ld->cl_controller	= &sc->ciss_controllers[bus];
3912	if (ciss_identify_logical(sc, ld) == 0) {
3913	    ciss_cam_rescan_target(sc, bus, target);
3914	}
3915    }
3916    free(cll, CISS_MALLOC_CLASS);
3917}
3918
3919/************************************************************************
3920 * Handle a notify event relating to the status of a logical drive.
3921 *
3922 * XXX need to be able to defer some of these to properly handle
3923 *     calling the "ID Physical drive" command, unless the 'extended'
3924 *     drive IDs are always in BIG_MAP format.
3925 */
3926static void
3927ciss_notify_logical(struct ciss_softc *sc, struct ciss_notify *cn)
3928{
3929    struct ciss_ldrive	*ld;
3930    int			ostatus, bus, target;
3931
3932    debug_called(2);
3933
3934    bus		= cn->device.physical.bus;
3935    target	= cn->data.logical_status.logical_drive;
3936    ld		= &sc->ciss_logical[bus][target];
3937
3938    switch (cn->subclass) {
3939    case CISS_NOTIFY_LOGICAL_STATUS:
3940	switch (cn->detail) {
3941	case 0:
3942	    ciss_name_device(sc, bus, target);
3943	    ciss_printf(sc, "logical drive %d (%s) changed status %s->%s, spare status 0x%b\n",
3944			cn->data.logical_status.logical_drive, ld->cl_name,
3945			ciss_name_ldrive_status(cn->data.logical_status.previous_state),
3946			ciss_name_ldrive_status(cn->data.logical_status.new_state),
3947			cn->data.logical_status.spare_state,
3948			"\20\1configured\2rebuilding\3failed\4in use\5available\n");
3949
3950	    /*
3951	     * Update our idea of the drive's status.
3952	     */
3953	    ostatus = ciss_decode_ldrive_status(cn->data.logical_status.previous_state);
3954	    ld->cl_status = ciss_decode_ldrive_status(cn->data.logical_status.new_state);
3955	    if (ld->cl_lstatus != NULL)
3956		ld->cl_lstatus->status = cn->data.logical_status.new_state;
3957
3958	    /*
3959	     * Have CAM rescan the drive if its status has changed.
3960	     */
3961	    if (ostatus != ld->cl_status) {
3962		ld->cl_update = 1;
3963		ciss_notify_rescan_logical(sc);
3964	    }
3965
3966	    break;
3967
3968	case 1:	/* logical drive has recognised new media, needs Accept Media Exchange */
3969	    ciss_name_device(sc, bus, target);
3970	    ciss_printf(sc, "logical drive %d (%s) media exchanged, ready to go online\n",
3971			cn->data.logical_status.logical_drive, ld->cl_name);
3972	    ciss_accept_media(sc, ld);
3973
3974	    ld->cl_update = 1;
3975	    ld->cl_status = ciss_decode_ldrive_status(cn->data.logical_status.new_state);
3976	    ciss_notify_rescan_logical(sc);
3977	    break;
3978
3979	case 2:
3980	case 3:
3981	    ciss_printf(sc, "rebuild of logical drive %d (%s) failed due to %s error\n",
3982			cn->data.rebuild_aborted.logical_drive,
3983			ld->cl_name,
3984			(cn->detail == 2) ? "read" : "write");
3985	    break;
3986	}
3987	break;
3988
3989    case CISS_NOTIFY_LOGICAL_ERROR:
3990	if (cn->detail == 0) {
3991	    ciss_printf(sc, "FATAL I/O ERROR on logical drive %d (%s), SCSI port %d ID %d\n",
3992			cn->data.io_error.logical_drive,
3993			ld->cl_name,
3994			cn->data.io_error.failure_bus,
3995			cn->data.io_error.failure_drive);
3996	    /* XXX should we take the drive down at this point, or will we be told? */
3997	}
3998	break;
3999
4000    case CISS_NOTIFY_LOGICAL_SURFACE:
4001	if (cn->detail == 0)
4002	    ciss_printf(sc, "logical drive %d (%s) completed consistency initialisation\n",
4003			cn->data.consistency_completed.logical_drive,
4004			ld->cl_name);
4005	break;
4006    }
4007}
4008
4009/************************************************************************
4010 * Handle a notify event relating to the status of a physical drive.
4011 */
4012static void
4013ciss_notify_physical(struct ciss_softc *sc, struct ciss_notify *cn)
4014{
4015}
4016
4017/************************************************************************
4018 * Handle a notify event relating to the status of a physical drive.
4019 */
4020static void
4021ciss_notify_hotplug(struct ciss_softc *sc, struct ciss_notify *cn)
4022{
4023    struct ciss_lun_report *cll = NULL;
4024    int bus, target;
4025
4026    switch (cn->subclass) {
4027    case CISS_NOTIFY_HOTPLUG_PHYSICAL:
4028    case CISS_NOTIFY_HOTPLUG_NONDISK:
4029	bus = CISS_BIG_MAP_BUS(sc, cn->data.drive.big_physical_drive_number);
4030	target =
4031	    CISS_BIG_MAP_TARGET(sc, cn->data.drive.big_physical_drive_number);
4032
4033	if (cn->detail == 0) {
4034	    /*
4035	     * Mark the device offline so that it'll start producing selection
4036	     * timeouts to the upper layer.
4037	     */
4038	    if ((bus >= 0) && (target >= 0))
4039		sc->ciss_physical[bus][target].cp_online = 0;
4040	} else {
4041	    /*
4042	     * Rescan the physical lun list for new items
4043	     */
4044	    cll = ciss_report_luns(sc, CISS_OPCODE_REPORT_PHYSICAL_LUNS,
4045				   CISS_MAX_PHYSICAL);
4046	    if (cll == NULL) {
4047		ciss_printf(sc, "Warning, cannot get physical lun list\n");
4048		break;
4049	    }
4050	    ciss_filter_physical(sc, cll);
4051	}
4052	break;
4053
4054    default:
4055	ciss_printf(sc, "Unknown hotplug event %d\n", cn->subclass);
4056	return;
4057    }
4058
4059    if (cll != NULL)
4060	free(cll, CISS_MALLOC_CLASS);
4061}
4062
4063/************************************************************************
4064 * Handle deferred processing of notify events.  Notify events may need
4065 * sleep which is unsafe during an interrupt.
4066 */
4067static void
4068ciss_notify_thread(void *arg)
4069{
4070    struct ciss_softc		*sc;
4071    struct ciss_request		*cr;
4072    struct ciss_notify		*cn;
4073
4074    sc = (struct ciss_softc *)arg;
4075#if __FreeBSD_version >= 500000
4076    mtx_lock(&sc->ciss_mtx);
4077#endif
4078
4079    for (;;) {
4080	if (STAILQ_EMPTY(&sc->ciss_notify) != 0 &&
4081	    (sc->ciss_flags & CISS_FLAG_THREAD_SHUT) == 0) {
4082	    msleep(&sc->ciss_notify, &sc->ciss_mtx, PUSER, "idle", 0);
4083	}
4084
4085	if (sc->ciss_flags & CISS_FLAG_THREAD_SHUT)
4086	    break;
4087
4088	cr = ciss_dequeue_notify(sc);
4089
4090	if (cr == NULL)
4091		panic("cr null");
4092	cn = (struct ciss_notify *)cr->cr_data;
4093
4094	switch (cn->class) {
4095	case CISS_NOTIFY_HOTPLUG:
4096	    ciss_notify_hotplug(sc, cn);
4097	    break;
4098	case CISS_NOTIFY_LOGICAL:
4099	    ciss_notify_logical(sc, cn);
4100	    break;
4101	case CISS_NOTIFY_PHYSICAL:
4102	    ciss_notify_physical(sc, cn);
4103	    break;
4104	}
4105
4106	ciss_release_request(cr);
4107
4108    }
4109    sc->ciss_notify_thread = NULL;
4110    wakeup(&sc->ciss_notify_thread);
4111
4112#if __FreeBSD_version >= 500000
4113    mtx_unlock(&sc->ciss_mtx);
4114#endif
4115    kproc_exit(0);
4116}
4117
4118/************************************************************************
4119 * Start the notification kernel thread.
4120 */
4121static void
4122ciss_spawn_notify_thread(struct ciss_softc *sc)
4123{
4124
4125#if __FreeBSD_version > 500005
4126    if (kproc_create((void(*)(void *))ciss_notify_thread, sc,
4127		       &sc->ciss_notify_thread, 0, 0, "ciss_notify%d",
4128		       device_get_unit(sc->ciss_dev)))
4129#else
4130    if (kproc_create((void(*)(void *))ciss_notify_thread, sc,
4131		       &sc->ciss_notify_thread, "ciss_notify%d",
4132		       device_get_unit(sc->ciss_dev)))
4133#endif
4134	panic("Could not create notify thread\n");
4135}
4136
4137/************************************************************************
4138 * Kill the notification kernel thread.
4139 */
4140static void
4141ciss_kill_notify_thread(struct ciss_softc *sc)
4142{
4143
4144    if (sc->ciss_notify_thread == NULL)
4145	return;
4146
4147    sc->ciss_flags |= CISS_FLAG_THREAD_SHUT;
4148    wakeup(&sc->ciss_notify);
4149    msleep(&sc->ciss_notify_thread, &sc->ciss_mtx, PUSER, "thtrm", 0);
4150}
4151
4152/************************************************************************
4153 * Print a request.
4154 */
4155static void
4156ciss_print_request(struct ciss_request *cr)
4157{
4158    struct ciss_softc	*sc;
4159    struct ciss_command	*cc;
4160    int			i;
4161
4162    sc = cr->cr_sc;
4163    cc = CISS_FIND_COMMAND(cr);
4164
4165    ciss_printf(sc, "REQUEST @ %p\n", cr);
4166    ciss_printf(sc, "  data %p/%d  tag %d  flags %b\n",
4167	      cr->cr_data, cr->cr_length, cr->cr_tag, cr->cr_flags,
4168	      "\20\1mapped\2sleep\3poll\4dataout\5datain\n");
4169    ciss_printf(sc, "  sg list/total %d/%d  host tag 0x%x\n",
4170		cc->header.sg_in_list, cc->header.sg_total, cc->header.host_tag);
4171    switch(cc->header.address.mode.mode) {
4172    case CISS_HDR_ADDRESS_MODE_PERIPHERAL:
4173    case CISS_HDR_ADDRESS_MODE_MASK_PERIPHERAL:
4174	ciss_printf(sc, "  physical bus %d target %d\n",
4175		    cc->header.address.physical.bus, cc->header.address.physical.target);
4176	break;
4177    case CISS_HDR_ADDRESS_MODE_LOGICAL:
4178	ciss_printf(sc, "  logical unit %d\n", cc->header.address.logical.lun);
4179	break;
4180    }
4181    ciss_printf(sc, "  %s cdb length %d type %s attribute %s\n",
4182		(cc->cdb.direction == CISS_CDB_DIRECTION_NONE) ? "no-I/O" :
4183		(cc->cdb.direction == CISS_CDB_DIRECTION_READ) ? "READ" :
4184		(cc->cdb.direction == CISS_CDB_DIRECTION_WRITE) ? "WRITE" : "??",
4185		cc->cdb.cdb_length,
4186		(cc->cdb.type == CISS_CDB_TYPE_COMMAND) ? "command" :
4187		(cc->cdb.type == CISS_CDB_TYPE_MESSAGE) ? "message" : "??",
4188		(cc->cdb.attribute == CISS_CDB_ATTRIBUTE_UNTAGGED) ? "untagged" :
4189		(cc->cdb.attribute == CISS_CDB_ATTRIBUTE_SIMPLE) ? "simple" :
4190		(cc->cdb.attribute == CISS_CDB_ATTRIBUTE_HEAD_OF_QUEUE) ? "head-of-queue" :
4191		(cc->cdb.attribute == CISS_CDB_ATTRIBUTE_ORDERED) ? "ordered" :
4192		(cc->cdb.attribute == CISS_CDB_ATTRIBUTE_AUTO_CONTINGENT) ? "auto-contingent" : "??");
4193    ciss_printf(sc, "  %*D\n", cc->cdb.cdb_length, &cc->cdb.cdb[0], " ");
4194
4195    if (cc->header.host_tag & CISS_HDR_HOST_TAG_ERROR) {
4196	/* XXX print error info */
4197    } else {
4198	/* since we don't use chained s/g, don't support it here */
4199	for (i = 0; i < cc->header.sg_in_list; i++) {
4200	    if ((i % 4) == 0)
4201		ciss_printf(sc, "   ");
4202	    printf("0x%08x/%d ", (u_int32_t)cc->sg[i].address, cc->sg[i].length);
4203	    if ((((i + 1) % 4) == 0) || (i == (cc->header.sg_in_list - 1)))
4204		printf("\n");
4205	}
4206    }
4207}
4208
4209/************************************************************************
4210 * Print information about the status of a logical drive.
4211 */
4212static void
4213ciss_print_ldrive(struct ciss_softc *sc, struct ciss_ldrive *ld)
4214{
4215    int		bus, target, i;
4216
4217    if (ld->cl_lstatus == NULL) {
4218	printf("does not exist\n");
4219	return;
4220    }
4221
4222    /* print drive status */
4223    switch(ld->cl_lstatus->status) {
4224    case CISS_LSTATUS_OK:
4225	printf("online\n");
4226	break;
4227    case CISS_LSTATUS_INTERIM_RECOVERY:
4228	printf("in interim recovery mode\n");
4229	break;
4230    case CISS_LSTATUS_READY_RECOVERY:
4231	printf("ready to begin recovery\n");
4232	break;
4233    case CISS_LSTATUS_RECOVERING:
4234	bus = CISS_BIG_MAP_BUS(sc, ld->cl_lstatus->drive_rebuilding);
4235	target = CISS_BIG_MAP_BUS(sc, ld->cl_lstatus->drive_rebuilding);
4236	printf("being recovered, working on physical drive %d.%d, %u blocks remaining\n",
4237	       bus, target, ld->cl_lstatus->blocks_to_recover);
4238	break;
4239    case CISS_LSTATUS_EXPANDING:
4240	printf("being expanded, %u blocks remaining\n",
4241	       ld->cl_lstatus->blocks_to_recover);
4242	break;
4243    case CISS_LSTATUS_QUEUED_FOR_EXPANSION:
4244	printf("queued for expansion\n");
4245	break;
4246    case CISS_LSTATUS_FAILED:
4247	printf("queued for expansion\n");
4248	break;
4249    case CISS_LSTATUS_WRONG_PDRIVE:
4250	printf("wrong physical drive inserted\n");
4251	break;
4252    case CISS_LSTATUS_MISSING_PDRIVE:
4253	printf("missing a needed physical drive\n");
4254	break;
4255    case CISS_LSTATUS_BECOMING_READY:
4256	printf("becoming ready\n");
4257	break;
4258    }
4259
4260    /* print failed physical drives */
4261    for (i = 0; i < CISS_BIG_MAP_ENTRIES / 8; i++) {
4262	bus = CISS_BIG_MAP_BUS(sc, ld->cl_lstatus->drive_failure_map[i]);
4263	target = CISS_BIG_MAP_TARGET(sc, ld->cl_lstatus->drive_failure_map[i]);
4264	if (bus == -1)
4265	    continue;
4266	ciss_printf(sc, "physical drive %d:%d (%x) failed\n", bus, target,
4267		    ld->cl_lstatus->drive_failure_map[i]);
4268    }
4269}
4270
4271#ifdef CISS_DEBUG
4272/************************************************************************
4273 * Print information about the controller/driver.
4274 */
4275static void
4276ciss_print_adapter(struct ciss_softc *sc)
4277{
4278    int		i, j;
4279
4280    ciss_printf(sc, "ADAPTER:\n");
4281    for (i = 0; i < CISSQ_COUNT; i++) {
4282	ciss_printf(sc, "%s     %d/%d\n",
4283	    i == 0 ? "free" :
4284	    i == 1 ? "busy" : "complete",
4285	    sc->ciss_qstat[i].q_length,
4286	    sc->ciss_qstat[i].q_max);
4287    }
4288    ciss_printf(sc, "max_requests %d\n", sc->ciss_max_requests);
4289    ciss_printf(sc, "flags %b\n", sc->ciss_flags,
4290	"\20\1notify_ok\2control_open\3aborting\4running\21fake_synch\22bmic_abort\n");
4291
4292    for (i = 0; i < sc->ciss_max_logical_bus; i++) {
4293	for (j = 0; j < CISS_MAX_LOGICAL; j++) {
4294	    ciss_printf(sc, "LOGICAL DRIVE %d:  ", i);
4295	    ciss_print_ldrive(sc, &sc->ciss_logical[i][j]);
4296	}
4297    }
4298
4299    /* XXX Should physical drives be printed out here? */
4300
4301    for (i = 1; i < sc->ciss_max_requests; i++)
4302	ciss_print_request(sc->ciss_request + i);
4303}
4304
4305/* DDB hook */
4306static void
4307ciss_print0(void)
4308{
4309    struct ciss_softc	*sc;
4310
4311    sc = devclass_get_softc(devclass_find("ciss"), 0);
4312    if (sc == NULL) {
4313	printf("no ciss controllers\n");
4314    } else {
4315	ciss_print_adapter(sc);
4316    }
4317}
4318#endif
4319
4320/************************************************************************
4321 * Return a name for a logical drive status value.
4322 */
4323static const char *
4324ciss_name_ldrive_status(int status)
4325{
4326    switch (status) {
4327    case CISS_LSTATUS_OK:
4328	return("OK");
4329    case CISS_LSTATUS_FAILED:
4330	return("failed");
4331    case CISS_LSTATUS_NOT_CONFIGURED:
4332	return("not configured");
4333    case CISS_LSTATUS_INTERIM_RECOVERY:
4334	return("interim recovery");
4335    case CISS_LSTATUS_READY_RECOVERY:
4336	return("ready for recovery");
4337    case CISS_LSTATUS_RECOVERING:
4338	return("recovering");
4339    case CISS_LSTATUS_WRONG_PDRIVE:
4340	return("wrong physical drive inserted");
4341    case CISS_LSTATUS_MISSING_PDRIVE:
4342	return("missing physical drive");
4343    case CISS_LSTATUS_EXPANDING:
4344	return("expanding");
4345    case CISS_LSTATUS_BECOMING_READY:
4346	return("becoming ready");
4347    case CISS_LSTATUS_QUEUED_FOR_EXPANSION:
4348	return("queued for expansion");
4349    }
4350    return("unknown status");
4351}
4352
4353/************************************************************************
4354 * Return an online/offline/nonexistent value for a logical drive
4355 * status value.
4356 */
4357static int
4358ciss_decode_ldrive_status(int status)
4359{
4360    switch(status) {
4361    case CISS_LSTATUS_NOT_CONFIGURED:
4362	return(CISS_LD_NONEXISTENT);
4363
4364    case CISS_LSTATUS_OK:
4365    case CISS_LSTATUS_INTERIM_RECOVERY:
4366    case CISS_LSTATUS_READY_RECOVERY:
4367    case CISS_LSTATUS_RECOVERING:
4368    case CISS_LSTATUS_EXPANDING:
4369    case CISS_LSTATUS_QUEUED_FOR_EXPANSION:
4370	return(CISS_LD_ONLINE);
4371
4372    case CISS_LSTATUS_FAILED:
4373    case CISS_LSTATUS_WRONG_PDRIVE:
4374    case CISS_LSTATUS_MISSING_PDRIVE:
4375    case CISS_LSTATUS_BECOMING_READY:
4376    default:
4377	return(CISS_LD_OFFLINE);
4378    }
4379}
4380
4381
4382/************************************************************************
4383 * Return a name for a logical drive's organisation.
4384 */
4385static const char *
4386ciss_name_ldrive_org(int org)
4387{
4388    switch(org) {
4389    case CISS_LDRIVE_RAID0:
4390	return("RAID 0");
4391    case CISS_LDRIVE_RAID1:
4392	return("RAID 1");
4393    case CISS_LDRIVE_RAID4:
4394	return("RAID 4");
4395    case CISS_LDRIVE_RAID5:
4396	return("RAID 5");
4397    case CISS_LDRIVE_RAID51:
4398	return("RAID 5+1");
4399    case CISS_LDRIVE_RAIDADG:
4400	return("RAID ADG");
4401    }
4402    return("unkown");
4403}
4404
4405/************************************************************************
4406 * Return a name for a command status value.
4407 */
4408static const char *
4409ciss_name_command_status(int status)
4410{
4411    switch(status) {
4412    case CISS_CMD_STATUS_SUCCESS:
4413	return("success");
4414    case CISS_CMD_STATUS_TARGET_STATUS:
4415	return("target status");
4416    case CISS_CMD_STATUS_DATA_UNDERRUN:
4417	return("data underrun");
4418    case CISS_CMD_STATUS_DATA_OVERRUN:
4419	return("data overrun");
4420    case CISS_CMD_STATUS_INVALID_COMMAND:
4421	return("invalid command");
4422    case CISS_CMD_STATUS_PROTOCOL_ERROR:
4423	return("protocol error");
4424    case CISS_CMD_STATUS_HARDWARE_ERROR:
4425	return("hardware error");
4426    case CISS_CMD_STATUS_CONNECTION_LOST:
4427	return("connection lost");
4428    case CISS_CMD_STATUS_ABORTED:
4429	return("aborted");
4430    case CISS_CMD_STATUS_ABORT_FAILED:
4431	return("abort failed");
4432    case CISS_CMD_STATUS_UNSOLICITED_ABORT:
4433	return("unsolicited abort");
4434    case CISS_CMD_STATUS_TIMEOUT:
4435	return("timeout");
4436    case CISS_CMD_STATUS_UNABORTABLE:
4437	return("unabortable");
4438    }
4439    return("unknown status");
4440}
4441
4442/************************************************************************
4443 * Handle an open on the control device.
4444 */
4445static int
4446ciss_open(struct cdev *dev, int flags, int fmt, struct thread *p)
4447{
4448    struct ciss_softc	*sc;
4449
4450    debug_called(1);
4451
4452    sc = (struct ciss_softc *)dev->si_drv1;
4453
4454    /* we might want to veto if someone already has us open */
4455
4456    mtx_lock(&sc->ciss_mtx);
4457    sc->ciss_flags |= CISS_FLAG_CONTROL_OPEN;
4458    mtx_unlock(&sc->ciss_mtx);
4459    return(0);
4460}
4461
4462/************************************************************************
4463 * Handle the last close on the control device.
4464 */
4465static int
4466ciss_close(struct cdev *dev, int flags, int fmt, struct thread *p)
4467{
4468    struct ciss_softc	*sc;
4469
4470    debug_called(1);
4471
4472    sc = (struct ciss_softc *)dev->si_drv1;
4473
4474    mtx_lock(&sc->ciss_mtx);
4475    sc->ciss_flags &= ~CISS_FLAG_CONTROL_OPEN;
4476    mtx_unlock(&sc->ciss_mtx);
4477    return (0);
4478}
4479
4480/********************************************************************************
4481 * Handle adapter-specific control operations.
4482 *
4483 * Note that the API here is compatible with the Linux driver, in order to
4484 * simplify the porting of Compaq's userland tools.
4485 */
4486static int
4487ciss_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int32_t flag, struct thread *p)
4488{
4489    struct ciss_softc		*sc;
4490    IOCTL_Command_struct	*ioc	= (IOCTL_Command_struct *)addr;
4491#ifdef __amd64__
4492    IOCTL_Command_struct32	*ioc32	= (IOCTL_Command_struct32 *)addr;
4493    IOCTL_Command_struct	ioc_swab;
4494#endif
4495    int				error;
4496
4497    debug_called(1);
4498
4499    sc = (struct ciss_softc *)dev->si_drv1;
4500    error = 0;
4501    mtx_lock(&sc->ciss_mtx);
4502
4503    switch(cmd) {
4504    case CCISS_GETQSTATS:
4505    {
4506	union ciss_statrequest *cr = (union ciss_statrequest *)addr;
4507
4508	switch (cr->cs_item) {
4509	case CISSQ_FREE:
4510	case CISSQ_NOTIFY:
4511	    bcopy(&sc->ciss_qstat[cr->cs_item], &cr->cs_qstat,
4512		sizeof(struct ciss_qstat));
4513	    break;
4514	default:
4515	    error = ENOIOCTL;
4516	    break;
4517	}
4518
4519	break;
4520    }
4521
4522    case CCISS_GETPCIINFO:
4523    {
4524	cciss_pci_info_struct	*pis = (cciss_pci_info_struct *)addr;
4525
4526	pis->bus = pci_get_bus(sc->ciss_dev);
4527	pis->dev_fn = pci_get_slot(sc->ciss_dev);
4528	pis->board_id = pci_get_devid(sc->ciss_dev);
4529
4530	break;
4531    }
4532
4533    case CCISS_GETINTINFO:
4534    {
4535	cciss_coalint_struct	*cis = (cciss_coalint_struct *)addr;
4536
4537	cis->delay = sc->ciss_cfg->interrupt_coalesce_delay;
4538	cis->count = sc->ciss_cfg->interrupt_coalesce_count;
4539
4540	break;
4541    }
4542
4543    case CCISS_SETINTINFO:
4544    {
4545	cciss_coalint_struct	*cis = (cciss_coalint_struct *)addr;
4546
4547	if ((cis->delay == 0) && (cis->count == 0)) {
4548	    error = EINVAL;
4549	    break;
4550	}
4551
4552	/*
4553	 * XXX apparently this is only safe if the controller is idle,
4554	 *     we should suspend it before doing this.
4555	 */
4556	sc->ciss_cfg->interrupt_coalesce_delay = cis->delay;
4557	sc->ciss_cfg->interrupt_coalesce_count = cis->count;
4558
4559	if (ciss_update_config(sc))
4560	    error = EIO;
4561
4562	/* XXX resume the controller here */
4563	break;
4564    }
4565
4566    case CCISS_GETNODENAME:
4567	bcopy(sc->ciss_cfg->server_name, (NodeName_type *)addr,
4568	      sizeof(NodeName_type));
4569	break;
4570
4571    case CCISS_SETNODENAME:
4572	bcopy((NodeName_type *)addr, sc->ciss_cfg->server_name,
4573	      sizeof(NodeName_type));
4574	if (ciss_update_config(sc))
4575	    error = EIO;
4576	break;
4577
4578    case CCISS_GETHEARTBEAT:
4579	*(Heartbeat_type *)addr = sc->ciss_cfg->heartbeat;
4580	break;
4581
4582    case CCISS_GETBUSTYPES:
4583	*(BusTypes_type *)addr = sc->ciss_cfg->bus_types;
4584	break;
4585
4586    case CCISS_GETFIRMVER:
4587	bcopy(sc->ciss_id->running_firmware_revision, (FirmwareVer_type *)addr,
4588	      sizeof(FirmwareVer_type));
4589	break;
4590
4591    case CCISS_GETDRIVERVER:
4592	*(DriverVer_type *)addr = CISS_DRIVER_VERSION;
4593	break;
4594
4595    case CCISS_REVALIDVOLS:
4596	/*
4597	 * This is a bit ugly; to do it "right" we really need
4598	 * to find any disks that have changed, kick CAM off them,
4599	 * then rescan only these disks.  It'd be nice if they
4600	 * a) told us which disk(s) they were going to play with,
4601	 * and b) which ones had arrived. 8(
4602	 */
4603	break;
4604
4605#ifdef __amd64__
4606    case CCISS_PASSTHRU32:
4607	ioc_swab.LUN_info	= ioc32->LUN_info;
4608	ioc_swab.Request	= ioc32->Request;
4609	ioc_swab.error_info	= ioc32->error_info;
4610	ioc_swab.buf_size	= ioc32->buf_size;
4611	ioc_swab.buf		= (u_int8_t *)(uintptr_t)ioc32->buf;
4612	ioc			= &ioc_swab;
4613	/* FALLTHROUGH */
4614#endif
4615
4616    case CCISS_PASSTHRU:
4617	error = ciss_user_command(sc, ioc);
4618	break;
4619
4620    default:
4621	debug(0, "unknown ioctl 0x%lx", cmd);
4622
4623	debug(1, "CCISS_GETPCIINFO:   0x%lx", CCISS_GETPCIINFO);
4624	debug(1, "CCISS_GETINTINFO:   0x%lx", CCISS_GETINTINFO);
4625	debug(1, "CCISS_SETINTINFO:   0x%lx", CCISS_SETINTINFO);
4626	debug(1, "CCISS_GETNODENAME:  0x%lx", CCISS_GETNODENAME);
4627	debug(1, "CCISS_SETNODENAME:  0x%lx", CCISS_SETNODENAME);
4628	debug(1, "CCISS_GETHEARTBEAT: 0x%lx", CCISS_GETHEARTBEAT);
4629	debug(1, "CCISS_GETBUSTYPES:  0x%lx", CCISS_GETBUSTYPES);
4630	debug(1, "CCISS_GETFIRMVER:   0x%lx", CCISS_GETFIRMVER);
4631	debug(1, "CCISS_GETDRIVERVER: 0x%lx", CCISS_GETDRIVERVER);
4632	debug(1, "CCISS_REVALIDVOLS:  0x%lx", CCISS_REVALIDVOLS);
4633	debug(1, "CCISS_PASSTHRU:     0x%lx", CCISS_PASSTHRU);
4634
4635	error = ENOIOCTL;
4636	break;
4637    }
4638
4639    mtx_unlock(&sc->ciss_mtx);
4640    return(error);
4641}
4642