xref: /freebsd/sys/dev/mvs/mvs.c (revision 732a02b4e77866604a120a275c082bb6221bd2ff)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2010 Alexander Motin <mav@FreeBSD.org>
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer,
12  *    without modification, immediately at the beginning of the file.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28 
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31 
32 #include <sys/param.h>
33 #include <sys/module.h>
34 #include <sys/systm.h>
35 #include <sys/kernel.h>
36 #include <sys/ata.h>
37 #include <sys/bus.h>
38 #include <sys/conf.h>
39 #include <sys/endian.h>
40 #include <sys/malloc.h>
41 #include <sys/lock.h>
42 #include <sys/mutex.h>
43 #include <vm/uma.h>
44 #include <machine/stdarg.h>
45 #include <machine/resource.h>
46 #include <machine/bus.h>
47 #include <sys/rman.h>
48 #include <dev/pci/pcivar.h>
49 #include "mvs.h"
50 
51 #include <cam/cam.h>
52 #include <cam/cam_ccb.h>
53 #include <cam/cam_sim.h>
54 #include <cam/cam_xpt_sim.h>
55 #include <cam/cam_debug.h>
56 
57 /* local prototypes */
58 static int mvs_ch_init(device_t dev);
59 static int mvs_ch_deinit(device_t dev);
60 static int mvs_ch_suspend(device_t dev);
61 static int mvs_ch_resume(device_t dev);
62 static void mvs_dmainit(device_t dev);
63 static void mvs_dmasetupc_cb(void *xsc,
64 	bus_dma_segment_t *segs, int nsegs, int error);
65 static void mvs_dmafini(device_t dev);
66 static void mvs_slotsalloc(device_t dev);
67 static void mvs_slotsfree(device_t dev);
68 static void mvs_setup_edma_queues(device_t dev);
69 static void mvs_set_edma_mode(device_t dev, enum mvs_edma_mode mode);
70 static void mvs_ch_pm(void *arg);
71 static void mvs_ch_intr_locked(void *data);
72 static void mvs_ch_intr(void *data);
73 static void mvs_reset(device_t dev);
74 static void mvs_softreset(device_t dev, union ccb *ccb);
75 
76 static int mvs_sata_connect(struct mvs_channel *ch);
77 static int mvs_sata_phy_reset(device_t dev);
78 static int mvs_wait(device_t dev, u_int s, u_int c, int t);
79 static void mvs_tfd_read(device_t dev, union ccb *ccb);
80 static void mvs_tfd_write(device_t dev, union ccb *ccb);
81 static void mvs_legacy_intr(device_t dev, int poll);
82 static void mvs_crbq_intr(device_t dev);
83 static void mvs_begin_transaction(device_t dev, union ccb *ccb);
84 static void mvs_legacy_execute_transaction(struct mvs_slot *slot);
85 static void mvs_timeout(void *arg);
86 static void mvs_dmasetprd(void *arg,
87 	bus_dma_segment_t *segs, int nsegs, int error);
88 static void mvs_requeue_frozen(device_t dev);
89 static void mvs_execute_transaction(struct mvs_slot *slot);
90 static void mvs_end_transaction(struct mvs_slot *slot, enum mvs_err_type et);
91 
92 static void mvs_issue_recovery(device_t dev);
93 static void mvs_process_read_log(device_t dev, union ccb *ccb);
94 static void mvs_process_request_sense(device_t dev, union ccb *ccb);
95 
96 static void mvsaction(struct cam_sim *sim, union ccb *ccb);
97 static void mvspoll(struct cam_sim *sim);
98 
99 static MALLOC_DEFINE(M_MVS, "MVS driver", "MVS driver data buffers");
100 
101 #define recovery_type		spriv_field0
102 #define RECOVERY_NONE		0
103 #define RECOVERY_READ_LOG	1
104 #define RECOVERY_REQUEST_SENSE	2
105 #define recovery_slot		spriv_field1
106 
107 static int
108 mvs_ch_probe(device_t dev)
109 {
110 
111 	device_set_desc_copy(dev, "Marvell SATA channel");
112 	return (BUS_PROBE_DEFAULT);
113 }
114 
115 static int
116 mvs_ch_attach(device_t dev)
117 {
118 	struct mvs_controller *ctlr = device_get_softc(device_get_parent(dev));
119 	struct mvs_channel *ch = device_get_softc(dev);
120 	struct cam_devq *devq;
121 	int rid, error, i, sata_rev = 0;
122 
123 	ch->dev = dev;
124 	ch->unit = (intptr_t)device_get_ivars(dev);
125 	ch->quirks = ctlr->quirks;
126 	mtx_init(&ch->mtx, "MVS channel lock", NULL, MTX_DEF);
127 	ch->pm_level = 0;
128 	resource_int_value(device_get_name(dev),
129 	    device_get_unit(dev), "pm_level", &ch->pm_level);
130 	if (ch->pm_level > 3)
131 		callout_init_mtx(&ch->pm_timer, &ch->mtx, 0);
132 	callout_init_mtx(&ch->reset_timer, &ch->mtx, 0);
133 	resource_int_value(device_get_name(dev),
134 	    device_get_unit(dev), "sata_rev", &sata_rev);
135 	for (i = 0; i < 16; i++) {
136 		ch->user[i].revision = sata_rev;
137 		ch->user[i].mode = 0;
138 		ch->user[i].bytecount = (ch->quirks & MVS_Q_GENIIE) ? 8192 : 2048;
139 		ch->user[i].tags = MVS_MAX_SLOTS;
140 		ch->curr[i] = ch->user[i];
141 		if (ch->pm_level) {
142 			ch->user[i].caps = CTS_SATA_CAPS_H_PMREQ |
143 			    CTS_SATA_CAPS_H_APST |
144 			    CTS_SATA_CAPS_D_PMREQ | CTS_SATA_CAPS_D_APST;
145 		}
146 		ch->user[i].caps |= CTS_SATA_CAPS_H_AN;
147 	}
148 	rid = ch->unit;
149 	if (!(ch->r_mem = bus_alloc_resource_any(dev, SYS_RES_MEMORY,
150 	    &rid, RF_ACTIVE)))
151 		return (ENXIO);
152 	mvs_dmainit(dev);
153 	mvs_slotsalloc(dev);
154 	mvs_ch_init(dev);
155 	mtx_lock(&ch->mtx);
156 	rid = ATA_IRQ_RID;
157 	if (!(ch->r_irq = bus_alloc_resource_any(dev, SYS_RES_IRQ,
158 	    &rid, RF_SHAREABLE | RF_ACTIVE))) {
159 		device_printf(dev, "Unable to map interrupt\n");
160 		error = ENXIO;
161 		goto err0;
162 	}
163 	if ((bus_setup_intr(dev, ch->r_irq, ATA_INTR_FLAGS, NULL,
164 	    mvs_ch_intr_locked, dev, &ch->ih))) {
165 		device_printf(dev, "Unable to setup interrupt\n");
166 		error = ENXIO;
167 		goto err1;
168 	}
169 	/* Create the device queue for our SIM. */
170 	devq = cam_simq_alloc(MVS_MAX_SLOTS - 1);
171 	if (devq == NULL) {
172 		device_printf(dev, "Unable to allocate simq\n");
173 		error = ENOMEM;
174 		goto err1;
175 	}
176 	/* Construct SIM entry */
177 	ch->sim = cam_sim_alloc(mvsaction, mvspoll, "mvsch", ch,
178 	    device_get_unit(dev), &ch->mtx,
179 	    2, (ch->quirks & MVS_Q_GENI) ? 0 : MVS_MAX_SLOTS - 1,
180 	    devq);
181 	if (ch->sim == NULL) {
182 		cam_simq_free(devq);
183 		device_printf(dev, "unable to allocate sim\n");
184 		error = ENOMEM;
185 		goto err1;
186 	}
187 	if (xpt_bus_register(ch->sim, dev, 0) != CAM_SUCCESS) {
188 		device_printf(dev, "unable to register xpt bus\n");
189 		error = ENXIO;
190 		goto err2;
191 	}
192 	if (xpt_create_path(&ch->path, /*periph*/NULL, cam_sim_path(ch->sim),
193 	    CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
194 		device_printf(dev, "unable to create path\n");
195 		error = ENXIO;
196 		goto err3;
197 	}
198 	if (ch->pm_level > 3) {
199 		callout_reset(&ch->pm_timer,
200 		    (ch->pm_level == 4) ? hz / 1000 : hz / 8,
201 		    mvs_ch_pm, dev);
202 	}
203 	mtx_unlock(&ch->mtx);
204 	return (0);
205 
206 err3:
207 	xpt_bus_deregister(cam_sim_path(ch->sim));
208 err2:
209 	cam_sim_free(ch->sim, /*free_devq*/TRUE);
210 err1:
211 	bus_release_resource(dev, SYS_RES_IRQ, ATA_IRQ_RID, ch->r_irq);
212 err0:
213 	bus_release_resource(dev, SYS_RES_MEMORY, ch->unit, ch->r_mem);
214 	mtx_unlock(&ch->mtx);
215 	mtx_destroy(&ch->mtx);
216 	return (error);
217 }
218 
219 static int
220 mvs_ch_detach(device_t dev)
221 {
222 	struct mvs_channel *ch = device_get_softc(dev);
223 
224 	mtx_lock(&ch->mtx);
225 	xpt_async(AC_LOST_DEVICE, ch->path, NULL);
226 	/* Forget about reset. */
227 	if (ch->resetting) {
228 		ch->resetting = 0;
229 		xpt_release_simq(ch->sim, TRUE);
230 	}
231 	xpt_free_path(ch->path);
232 	xpt_bus_deregister(cam_sim_path(ch->sim));
233 	cam_sim_free(ch->sim, /*free_devq*/TRUE);
234 	mtx_unlock(&ch->mtx);
235 
236 	if (ch->pm_level > 3)
237 		callout_drain(&ch->pm_timer);
238 	callout_drain(&ch->reset_timer);
239 	bus_teardown_intr(dev, ch->r_irq, ch->ih);
240 	bus_release_resource(dev, SYS_RES_IRQ, ATA_IRQ_RID, ch->r_irq);
241 
242 	mvs_ch_deinit(dev);
243 	mvs_slotsfree(dev);
244 	mvs_dmafini(dev);
245 
246 	bus_release_resource(dev, SYS_RES_MEMORY, ch->unit, ch->r_mem);
247 	mtx_destroy(&ch->mtx);
248 	return (0);
249 }
250 
251 static int
252 mvs_ch_init(device_t dev)
253 {
254 	struct mvs_channel *ch = device_get_softc(dev);
255 	uint32_t reg;
256 
257 	/* Disable port interrupts */
258 	ATA_OUTL(ch->r_mem, EDMA_IEM, 0);
259 	/* Stop EDMA */
260 	ch->curr_mode = MVS_EDMA_UNKNOWN;
261 	mvs_set_edma_mode(dev, MVS_EDMA_OFF);
262 	/* Clear and configure FIS interrupts. */
263 	ATA_OUTL(ch->r_mem, SATA_FISIC, 0);
264 	reg = ATA_INL(ch->r_mem, SATA_FISC);
265 	reg |= SATA_FISC_FISWAIT4HOSTRDYEN_B1;
266 	ATA_OUTL(ch->r_mem, SATA_FISC, reg);
267 	reg = ATA_INL(ch->r_mem, SATA_FISIM);
268 	reg |= SATA_FISC_FISWAIT4HOSTRDYEN_B1;
269 	ATA_OUTL(ch->r_mem, SATA_FISC, reg);
270 	/* Clear SATA error register. */
271 	ATA_OUTL(ch->r_mem, SATA_SE, 0xffffffff);
272 	/* Clear any outstanding error interrupts. */
273 	ATA_OUTL(ch->r_mem, EDMA_IEC, 0);
274 	/* Unmask all error interrupts */
275 	ATA_OUTL(ch->r_mem, EDMA_IEM, ~EDMA_IE_TRANSIENT);
276 	return (0);
277 }
278 
279 static int
280 mvs_ch_deinit(device_t dev)
281 {
282 	struct mvs_channel *ch = device_get_softc(dev);
283 
284 	/* Stop EDMA */
285 	mvs_set_edma_mode(dev, MVS_EDMA_OFF);
286 	/* Disable port interrupts. */
287 	ATA_OUTL(ch->r_mem, EDMA_IEM, 0);
288 	return (0);
289 }
290 
291 static int
292 mvs_ch_suspend(device_t dev)
293 {
294 	struct mvs_channel *ch = device_get_softc(dev);
295 
296 	mtx_lock(&ch->mtx);
297 	xpt_freeze_simq(ch->sim, 1);
298 	while (ch->oslots)
299 		msleep(ch, &ch->mtx, PRIBIO, "mvssusp", hz/100);
300 	/* Forget about reset. */
301 	if (ch->resetting) {
302 		ch->resetting = 0;
303 		callout_stop(&ch->reset_timer);
304 		xpt_release_simq(ch->sim, TRUE);
305 	}
306 	mvs_ch_deinit(dev);
307 	mtx_unlock(&ch->mtx);
308 	return (0);
309 }
310 
311 static int
312 mvs_ch_resume(device_t dev)
313 {
314 	struct mvs_channel *ch = device_get_softc(dev);
315 
316 	mtx_lock(&ch->mtx);
317 	mvs_ch_init(dev);
318 	mvs_reset(dev);
319 	xpt_release_simq(ch->sim, TRUE);
320 	mtx_unlock(&ch->mtx);
321 	return (0);
322 }
323 
324 struct mvs_dc_cb_args {
325 	bus_addr_t maddr;
326 	int error;
327 };
328 
329 static void
330 mvs_dmainit(device_t dev)
331 {
332 	struct mvs_channel *ch = device_get_softc(dev);
333 	struct mvs_dc_cb_args dcba;
334 
335 	/* EDMA command request area. */
336 	if (bus_dma_tag_create(bus_get_dma_tag(dev), 1024, 0,
337 	    BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR,
338 	    NULL, NULL, MVS_WORKRQ_SIZE, 1, MVS_WORKRQ_SIZE,
339 	    0, NULL, NULL, &ch->dma.workrq_tag))
340 		goto error;
341 	if (bus_dmamem_alloc(ch->dma.workrq_tag, (void **)&ch->dma.workrq, 0,
342 	    &ch->dma.workrq_map))
343 		goto error;
344 	if (bus_dmamap_load(ch->dma.workrq_tag, ch->dma.workrq_map,
345 	    ch->dma.workrq, MVS_WORKRQ_SIZE, mvs_dmasetupc_cb, &dcba, 0) ||
346 	    dcba.error) {
347 		bus_dmamem_free(ch->dma.workrq_tag,
348 		    ch->dma.workrq, ch->dma.workrq_map);
349 		goto error;
350 	}
351 	ch->dma.workrq_bus = dcba.maddr;
352 	/* EDMA command response area. */
353 	if (bus_dma_tag_create(bus_get_dma_tag(dev), 256, 0,
354 	    BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR,
355 	    NULL, NULL, MVS_WORKRP_SIZE, 1, MVS_WORKRP_SIZE,
356 	    0, NULL, NULL, &ch->dma.workrp_tag))
357 		goto error;
358 	if (bus_dmamem_alloc(ch->dma.workrp_tag, (void **)&ch->dma.workrp, 0,
359 	    &ch->dma.workrp_map))
360 		goto error;
361 	if (bus_dmamap_load(ch->dma.workrp_tag, ch->dma.workrp_map,
362 	    ch->dma.workrp, MVS_WORKRP_SIZE, mvs_dmasetupc_cb, &dcba, 0) ||
363 	    dcba.error) {
364 		bus_dmamem_free(ch->dma.workrp_tag,
365 		    ch->dma.workrp, ch->dma.workrp_map);
366 		goto error;
367 	}
368 	ch->dma.workrp_bus = dcba.maddr;
369 	/* Data area. */
370 	if (bus_dma_tag_create(bus_get_dma_tag(dev), 2, MVS_EPRD_MAX,
371 	    BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR,
372 	    NULL, NULL,
373 	    MVS_SG_ENTRIES * PAGE_SIZE * MVS_MAX_SLOTS,
374 	    MVS_SG_ENTRIES, MVS_EPRD_MAX,
375 	    0, busdma_lock_mutex, &ch->mtx, &ch->dma.data_tag)) {
376 		goto error;
377 	}
378 	return;
379 
380 error:
381 	device_printf(dev, "WARNING - DMA initialization failed\n");
382 	mvs_dmafini(dev);
383 }
384 
385 static void
386 mvs_dmasetupc_cb(void *xsc, bus_dma_segment_t *segs, int nsegs, int error)
387 {
388 	struct mvs_dc_cb_args *dcba = (struct mvs_dc_cb_args *)xsc;
389 
390 	if (!(dcba->error = error))
391 		dcba->maddr = segs[0].ds_addr;
392 }
393 
394 static void
395 mvs_dmafini(device_t dev)
396 {
397 	struct mvs_channel *ch = device_get_softc(dev);
398 
399 	if (ch->dma.data_tag) {
400 		bus_dma_tag_destroy(ch->dma.data_tag);
401 		ch->dma.data_tag = NULL;
402 	}
403 	if (ch->dma.workrp_bus) {
404 		bus_dmamap_unload(ch->dma.workrp_tag, ch->dma.workrp_map);
405 		bus_dmamem_free(ch->dma.workrp_tag,
406 		    ch->dma.workrp, ch->dma.workrp_map);
407 		ch->dma.workrp_bus = 0;
408 		ch->dma.workrp = NULL;
409 	}
410 	if (ch->dma.workrp_tag) {
411 		bus_dma_tag_destroy(ch->dma.workrp_tag);
412 		ch->dma.workrp_tag = NULL;
413 	}
414 	if (ch->dma.workrq_bus) {
415 		bus_dmamap_unload(ch->dma.workrq_tag, ch->dma.workrq_map);
416 		bus_dmamem_free(ch->dma.workrq_tag,
417 		    ch->dma.workrq, ch->dma.workrq_map);
418 		ch->dma.workrq_bus = 0;
419 		ch->dma.workrq = NULL;
420 	}
421 	if (ch->dma.workrq_tag) {
422 		bus_dma_tag_destroy(ch->dma.workrq_tag);
423 		ch->dma.workrq_tag = NULL;
424 	}
425 }
426 
427 static void
428 mvs_slotsalloc(device_t dev)
429 {
430 	struct mvs_channel *ch = device_get_softc(dev);
431 	int i;
432 
433 	/* Alloc and setup command/dma slots */
434 	bzero(ch->slot, sizeof(ch->slot));
435 	for (i = 0; i < MVS_MAX_SLOTS; i++) {
436 		struct mvs_slot *slot = &ch->slot[i];
437 
438 		slot->dev = dev;
439 		slot->slot = i;
440 		slot->state = MVS_SLOT_EMPTY;
441 		slot->ccb = NULL;
442 		callout_init_mtx(&slot->timeout, &ch->mtx, 0);
443 
444 		if (bus_dmamap_create(ch->dma.data_tag, 0, &slot->dma.data_map))
445 			device_printf(ch->dev, "FAILURE - create data_map\n");
446 	}
447 }
448 
449 static void
450 mvs_slotsfree(device_t dev)
451 {
452 	struct mvs_channel *ch = device_get_softc(dev);
453 	int i;
454 
455 	/* Free all dma slots */
456 	for (i = 0; i < MVS_MAX_SLOTS; i++) {
457 		struct mvs_slot *slot = &ch->slot[i];
458 
459 		callout_drain(&slot->timeout);
460 		if (slot->dma.data_map) {
461 			bus_dmamap_destroy(ch->dma.data_tag, slot->dma.data_map);
462 			slot->dma.data_map = NULL;
463 		}
464 	}
465 }
466 
467 static void
468 mvs_setup_edma_queues(device_t dev)
469 {
470 	struct mvs_channel *ch = device_get_softc(dev);
471 	uint64_t work;
472 
473 	/* Requests queue. */
474 	work = ch->dma.workrq_bus;
475 	ATA_OUTL(ch->r_mem, EDMA_REQQBAH, work >> 32);
476 	ATA_OUTL(ch->r_mem, EDMA_REQQIP, work & 0xffffffff);
477 	ATA_OUTL(ch->r_mem, EDMA_REQQOP, work & 0xffffffff);
478 	bus_dmamap_sync(ch->dma.workrq_tag, ch->dma.workrq_map,
479 	    BUS_DMASYNC_PREWRITE);
480 	/* Responses queue. */
481 	memset(ch->dma.workrp, 0xff, MVS_WORKRP_SIZE);
482 	work = ch->dma.workrp_bus;
483 	ATA_OUTL(ch->r_mem, EDMA_RESQBAH, work >> 32);
484 	ATA_OUTL(ch->r_mem, EDMA_RESQIP, work & 0xffffffff);
485 	ATA_OUTL(ch->r_mem, EDMA_RESQOP, work & 0xffffffff);
486 	bus_dmamap_sync(ch->dma.workrp_tag, ch->dma.workrp_map,
487 	    BUS_DMASYNC_PREREAD);
488 	ch->out_idx = 0;
489 	ch->in_idx = 0;
490 }
491 
492 static void
493 mvs_set_edma_mode(device_t dev, enum mvs_edma_mode mode)
494 {
495 	struct mvs_channel *ch = device_get_softc(dev);
496 	int timeout;
497 	uint32_t ecfg, fcfg, hc, ltm, unkn;
498 
499 	if (mode == ch->curr_mode)
500 		return;
501 	/* If we are running, we should stop first. */
502 	if (ch->curr_mode != MVS_EDMA_OFF) {
503 		ATA_OUTL(ch->r_mem, EDMA_CMD, EDMA_CMD_EDSEDMA);
504 		timeout = 0;
505 		while (ATA_INL(ch->r_mem, EDMA_CMD) & EDMA_CMD_EENEDMA) {
506 			DELAY(1000);
507 			if (timeout++ > 1000) {
508 				device_printf(dev, "stopping EDMA engine failed\n");
509 				break;
510 			}
511 		}
512 	}
513 	ch->curr_mode = mode;
514 	ch->fbs_enabled = 0;
515 	ch->fake_busy = 0;
516 	/* Report mode to controller. Needed for correct CCC operation. */
517 	MVS_EDMA(device_get_parent(dev), dev, mode);
518 	/* Configure new mode. */
519 	ecfg = EDMA_CFG_RESERVED | EDMA_CFG_RESERVED2 | EDMA_CFG_EHOSTQUEUECACHEEN;
520 	if (ch->pm_present) {
521 		ecfg |= EDMA_CFG_EMASKRXPM;
522 		if (ch->quirks & MVS_Q_GENIIE) {
523 			ecfg |= EDMA_CFG_EEDMAFBS;
524 			ch->fbs_enabled = 1;
525 		}
526 	}
527 	if (ch->quirks & MVS_Q_GENI)
528 		ecfg |= EDMA_CFG_ERDBSZ;
529 	else if (ch->quirks & MVS_Q_GENII)
530 		ecfg |= EDMA_CFG_ERDBSZEXT | EDMA_CFG_EWRBUFFERLEN;
531 	if (ch->quirks & MVS_Q_CT)
532 		ecfg |= EDMA_CFG_ECUTTHROUGHEN;
533 	if (mode != MVS_EDMA_OFF)
534 		ecfg |= EDMA_CFG_EEARLYCOMPLETIONEN;
535 	if (mode == MVS_EDMA_QUEUED)
536 		ecfg |= EDMA_CFG_EQUE;
537 	else if (mode == MVS_EDMA_NCQ)
538 		ecfg |= EDMA_CFG_ESATANATVCMDQUE;
539 	ATA_OUTL(ch->r_mem, EDMA_CFG, ecfg);
540 	mvs_setup_edma_queues(dev);
541 	if (ch->quirks & MVS_Q_GENIIE) {
542 		/* Configure FBS-related registers */
543 		fcfg = ATA_INL(ch->r_mem, SATA_FISC);
544 		ltm = ATA_INL(ch->r_mem, SATA_LTM);
545 		hc = ATA_INL(ch->r_mem, EDMA_HC);
546 		if (ch->fbs_enabled) {
547 			fcfg |= SATA_FISC_FISDMAACTIVATESYNCRESP;
548 			if (mode == MVS_EDMA_NCQ) {
549 				fcfg &= ~SATA_FISC_FISWAIT4HOSTRDYEN_B0;
550 				hc &= ~EDMA_IE_EDEVERR;
551 			} else {
552 				fcfg |= SATA_FISC_FISWAIT4HOSTRDYEN_B0;
553 				hc |= EDMA_IE_EDEVERR;
554 			}
555 			ltm |= (1 << 8);
556 		} else {
557 			fcfg &= ~SATA_FISC_FISDMAACTIVATESYNCRESP;
558 			fcfg &= ~SATA_FISC_FISWAIT4HOSTRDYEN_B0;
559 			hc |= EDMA_IE_EDEVERR;
560 			ltm &= ~(1 << 8);
561 		}
562 		ATA_OUTL(ch->r_mem, SATA_FISC, fcfg);
563 		ATA_OUTL(ch->r_mem, SATA_LTM, ltm);
564 		ATA_OUTL(ch->r_mem, EDMA_HC, hc);
565 		/* This is some magic, required to handle several DRQs
566 		 * with basic DMA. */
567 		unkn = ATA_INL(ch->r_mem, EDMA_UNKN_RESD);
568 		if (mode == MVS_EDMA_OFF)
569 			unkn |= 1;
570 		else
571 			unkn &= ~1;
572 		ATA_OUTL(ch->r_mem, EDMA_UNKN_RESD, unkn);
573 	}
574 	/* Run EDMA. */
575 	if (mode != MVS_EDMA_OFF)
576 		ATA_OUTL(ch->r_mem, EDMA_CMD, EDMA_CMD_EENEDMA);
577 }
578 
579 devclass_t mvs_devclass;
580 devclass_t mvsch_devclass;
581 static device_method_t mvsch_methods[] = {
582 	DEVMETHOD(device_probe,     mvs_ch_probe),
583 	DEVMETHOD(device_attach,    mvs_ch_attach),
584 	DEVMETHOD(device_detach,    mvs_ch_detach),
585 	DEVMETHOD(device_suspend,   mvs_ch_suspend),
586 	DEVMETHOD(device_resume,    mvs_ch_resume),
587 	{ 0, 0 }
588 };
589 static driver_t mvsch_driver = {
590         "mvsch",
591         mvsch_methods,
592         sizeof(struct mvs_channel)
593 };
594 DRIVER_MODULE(mvsch, mvs, mvsch_driver, mvsch_devclass, 0, 0);
595 DRIVER_MODULE(mvsch, sata, mvsch_driver, mvsch_devclass, 0, 0);
596 
597 static void
598 mvs_phy_check_events(device_t dev, u_int32_t serr)
599 {
600 	struct mvs_channel *ch = device_get_softc(dev);
601 
602 	if (ch->pm_level == 0) {
603 		u_int32_t status = ATA_INL(ch->r_mem, SATA_SS);
604 		union ccb *ccb;
605 
606 		if (bootverbose) {
607 			if (((status & SATA_SS_DET_MASK) == SATA_SS_DET_PHY_ONLINE) &&
608 			    ((status & SATA_SS_SPD_MASK) != SATA_SS_SPD_NO_SPEED) &&
609 			    ((status & SATA_SS_IPM_MASK) == SATA_SS_IPM_ACTIVE)) {
610 				device_printf(dev, "CONNECT requested\n");
611 			} else
612 				device_printf(dev, "DISCONNECT requested\n");
613 		}
614 		mvs_reset(dev);
615 		if ((ccb = xpt_alloc_ccb_nowait()) == NULL)
616 			return;
617 		if (xpt_create_path(&ccb->ccb_h.path, NULL,
618 		    cam_sim_path(ch->sim),
619 		    CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
620 			xpt_free_ccb(ccb);
621 			return;
622 		}
623 		xpt_rescan(ccb);
624 	}
625 }
626 
627 static void
628 mvs_notify_events(device_t dev)
629 {
630 	struct mvs_channel *ch = device_get_softc(dev);
631 	struct cam_path *dpath;
632 	uint32_t fis;
633 	int d;
634 
635 	/* Try to read PMP field from SDB FIS. Present only for Gen-IIe. */
636 	fis = ATA_INL(ch->r_mem, SATA_FISDW0);
637 	if ((fis & 0x80ff) == 0x80a1)
638 		d = (fis & 0x0f00) >> 8;
639 	else
640 		d = ch->pm_present ? 15 : 0;
641 	if (bootverbose)
642 		device_printf(dev, "SNTF %d\n", d);
643 	if (xpt_create_path(&dpath, NULL,
644 	    xpt_path_path_id(ch->path), d, 0) == CAM_REQ_CMP) {
645 		xpt_async(AC_SCSI_AEN, dpath, NULL);
646 		xpt_free_path(dpath);
647 	}
648 }
649 
650 static void
651 mvs_ch_intr_locked(void *data)
652 {
653 	struct mvs_intr_arg *arg = (struct mvs_intr_arg *)data;
654 	device_t dev = (device_t)arg->arg;
655 	struct mvs_channel *ch = device_get_softc(dev);
656 
657 	mtx_lock(&ch->mtx);
658 	mvs_ch_intr(data);
659 	mtx_unlock(&ch->mtx);
660 }
661 
662 static void
663 mvs_ch_pm(void *arg)
664 {
665 	device_t dev = (device_t)arg;
666 	struct mvs_channel *ch = device_get_softc(dev);
667 	uint32_t work;
668 
669 	if (ch->numrslots != 0)
670 		return;
671 	/* If we are idle - request power state transition. */
672 	work = ATA_INL(ch->r_mem, SATA_SC);
673 	work &= ~SATA_SC_SPM_MASK;
674 	if (ch->pm_level == 4)
675 		work |= SATA_SC_SPM_PARTIAL;
676 	else
677 		work |= SATA_SC_SPM_SLUMBER;
678 	ATA_OUTL(ch->r_mem, SATA_SC, work);
679 }
680 
681 static void
682 mvs_ch_pm_wake(device_t dev)
683 {
684 	struct mvs_channel *ch = device_get_softc(dev);
685 	uint32_t work;
686 	int timeout = 0;
687 
688 	work = ATA_INL(ch->r_mem, SATA_SS);
689 	if (work & SATA_SS_IPM_ACTIVE)
690 		return;
691 	/* If we are not in active state - request power state transition. */
692 	work = ATA_INL(ch->r_mem, SATA_SC);
693 	work &= ~SATA_SC_SPM_MASK;
694 	work |= SATA_SC_SPM_ACTIVE;
695 	ATA_OUTL(ch->r_mem, SATA_SC, work);
696 	/* Wait for transition to happen. */
697 	while ((ATA_INL(ch->r_mem, SATA_SS) & SATA_SS_IPM_ACTIVE) == 0 &&
698 	    timeout++ < 100) {
699 		DELAY(100);
700 	}
701 }
702 
703 static void
704 mvs_ch_intr(void *data)
705 {
706 	struct mvs_intr_arg *arg = (struct mvs_intr_arg *)data;
707 	device_t dev = (device_t)arg->arg;
708 	struct mvs_channel *ch = device_get_softc(dev);
709 	uint32_t iec, serr = 0, fisic = 0;
710 	enum mvs_err_type et;
711 	int i, ccs, port = -1, selfdis = 0;
712 	int edma = (ch->numtslots != 0 || ch->numdslots != 0);
713 
714 	/* New item in response queue. */
715 	if ((arg->cause & 2) && edma)
716 		mvs_crbq_intr(dev);
717 	/* Some error or special event. */
718 	if (arg->cause & 1) {
719 		iec = ATA_INL(ch->r_mem, EDMA_IEC);
720 		if (iec & EDMA_IE_SERRINT) {
721 			serr = ATA_INL(ch->r_mem, SATA_SE);
722 			ATA_OUTL(ch->r_mem, SATA_SE, serr);
723 		}
724 		/* EDMA self-disabled due to error. */
725 		if (iec & EDMA_IE_ESELFDIS)
726 			selfdis = 1;
727 		/* Transport interrupt. */
728 		if (iec & EDMA_IE_ETRANSINT) {
729 			/* For Gen-I this bit means self-disable. */
730 			if (ch->quirks & MVS_Q_GENI)
731 				selfdis = 1;
732 			/* For Gen-II this bit means SDB-N. */
733 			else if (ch->quirks & MVS_Q_GENII)
734 				fisic = SATA_FISC_FISWAIT4HOSTRDYEN_B1;
735 			else	/* For Gen-IIe - read FIS interrupt cause. */
736 				fisic = ATA_INL(ch->r_mem, SATA_FISIC);
737 		}
738 		if (selfdis)
739 			ch->curr_mode = MVS_EDMA_UNKNOWN;
740 		ATA_OUTL(ch->r_mem, EDMA_IEC, ~iec);
741 		/* Interface errors or Device error. */
742 		if (iec & (0xfc1e9000 | EDMA_IE_EDEVERR)) {
743 			port = -1;
744 			if (ch->numpslots != 0) {
745 				ccs = 0;
746 			} else {
747 				if (ch->quirks & MVS_Q_GENIIE)
748 					ccs = EDMA_S_EIOID(ATA_INL(ch->r_mem, EDMA_S));
749 				else
750 					ccs = EDMA_S_EDEVQUETAG(ATA_INL(ch->r_mem, EDMA_S));
751 				/* Check if error is one-PMP-port-specific, */
752 				if (ch->fbs_enabled) {
753 					/* Which ports were active. */
754 					for (i = 0; i < 16; i++) {
755 						if (ch->numrslotspd[i] == 0)
756 							continue;
757 						if (port == -1)
758 							port = i;
759 						else if (port != i) {
760 							port = -2;
761 							break;
762 						}
763 					}
764 					/* If several ports were active and EDMA still enabled -
765 					 * other ports are probably unaffected and may continue.
766 					 */
767 					if (port == -2 && !selfdis) {
768 						uint16_t p = ATA_INL(ch->r_mem, SATA_SATAITC) >> 16;
769 						port = ffs(p) - 1;
770 						if (port != (fls(p) - 1))
771 							port = -2;
772 					}
773 				}
774 			}
775 			mvs_requeue_frozen(dev);
776 			for (i = 0; i < MVS_MAX_SLOTS; i++) {
777 				/* XXX: reqests in loading state. */
778 				if (((ch->rslots >> i) & 1) == 0)
779 					continue;
780 				if (port >= 0 &&
781 				    ch->slot[i].ccb->ccb_h.target_id != port)
782 					continue;
783 				if (iec & EDMA_IE_EDEVERR) { /* Device error. */
784 				    if (port != -2) {
785 					if (ch->numtslots == 0) {
786 						/* Untagged operation. */
787 						if (i == ccs)
788 							et = MVS_ERR_TFE;
789 						else
790 							et = MVS_ERR_INNOCENT;
791 					} else {
792 						/* Tagged operation. */
793 						et = MVS_ERR_NCQ;
794 					}
795 				    } else {
796 					et = MVS_ERR_TFE;
797 					ch->fatalerr = 1;
798 				    }
799 				} else if (iec & 0xfc1e9000) {
800 					if (ch->numtslots == 0 &&
801 					    i != ccs && port != -2)
802 						et = MVS_ERR_INNOCENT;
803 					else
804 						et = MVS_ERR_SATA;
805 				} else
806 					et = MVS_ERR_INVALID;
807 				mvs_end_transaction(&ch->slot[i], et);
808 			}
809 		}
810 		/* Process SDB-N. */
811 		if (fisic & SATA_FISC_FISWAIT4HOSTRDYEN_B1)
812 			mvs_notify_events(dev);
813 		if (fisic)
814 			ATA_OUTL(ch->r_mem, SATA_FISIC, ~fisic);
815 		/* Process hot-plug. */
816 		if ((iec & (EDMA_IE_EDEVDIS | EDMA_IE_EDEVCON)) ||
817 		    (serr & SATA_SE_PHY_CHANGED))
818 			mvs_phy_check_events(dev, serr);
819 	}
820 	/* Legacy mode device interrupt. */
821 	if ((arg->cause & 2) && !edma)
822 		mvs_legacy_intr(dev, arg->cause & 4);
823 }
824 
825 static uint8_t
826 mvs_getstatus(device_t dev, int clear)
827 {
828 	struct mvs_channel *ch = device_get_softc(dev);
829 	uint8_t status = ATA_INB(ch->r_mem, clear ? ATA_STATUS : ATA_ALTSTAT);
830 
831 	if (ch->fake_busy) {
832 		if (status & (ATA_S_BUSY | ATA_S_DRQ | ATA_S_ERROR))
833 			ch->fake_busy = 0;
834 		else
835 			status |= ATA_S_BUSY;
836 	}
837 	return (status);
838 }
839 
840 static void
841 mvs_legacy_intr(device_t dev, int poll)
842 {
843 	struct mvs_channel *ch = device_get_softc(dev);
844 	struct mvs_slot *slot = &ch->slot[0]; /* PIO is always in slot 0. */
845 	union ccb *ccb = slot->ccb;
846 	enum mvs_err_type et = MVS_ERR_NONE;
847 	int port;
848 	u_int length, resid, size;
849 	uint8_t buf[2];
850 	uint8_t status, ireason;
851 
852 	/* Clear interrupt and get status. */
853 	status = mvs_getstatus(dev, 1);
854 	if (slot->state < MVS_SLOT_RUNNING)
855 	    return;
856 	port = ccb->ccb_h.target_id & 0x0f;
857 	/* Wait a bit for late !BUSY status update. */
858 	if (status & ATA_S_BUSY) {
859 		if (poll)
860 			return;
861 		DELAY(100);
862 		if ((status = mvs_getstatus(dev, 1)) & ATA_S_BUSY) {
863 			DELAY(1000);
864 			if ((status = mvs_getstatus(dev, 1)) & ATA_S_BUSY)
865 				return;
866 		}
867 	}
868 	/* If we got an error, we are done. */
869 	if (status & ATA_S_ERROR) {
870 		et = MVS_ERR_TFE;
871 		goto end_finished;
872 	}
873 	if (ccb->ccb_h.func_code == XPT_ATA_IO) { /* ATA PIO */
874 		ccb->ataio.res.status = status;
875 		/* Are we moving data? */
876 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
877 		    /* If data read command - get them. */
878 		    if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
879 			if (mvs_wait(dev, ATA_S_DRQ, ATA_S_BUSY, 1000) < 0) {
880 			    device_printf(dev, "timeout waiting for read DRQ\n");
881 			    et = MVS_ERR_TIMEOUT;
882 			    xpt_freeze_simq(ch->sim, 1);
883 			    ch->toslots |= (1 << slot->slot);
884 			    goto end_finished;
885 			}
886 			ATA_INSW_STRM(ch->r_mem, ATA_DATA,
887 			   (uint16_t *)(ccb->ataio.data_ptr + ch->donecount),
888 			   ch->transfersize / 2);
889 		    }
890 		    /* Update how far we've gotten. */
891 		    ch->donecount += ch->transfersize;
892 		    /* Do we need more? */
893 		    if (ccb->ataio.dxfer_len > ch->donecount) {
894 			/* Set this transfer size according to HW capabilities */
895 			ch->transfersize = min(ccb->ataio.dxfer_len - ch->donecount,
896 			    ch->transfersize);
897 			/* If data write command - put them */
898 			if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_OUT) {
899 				if (mvs_wait(dev, ATA_S_DRQ, ATA_S_BUSY, 1000) < 0) {
900 				    device_printf(dev,
901 					"timeout waiting for write DRQ\n");
902 				    et = MVS_ERR_TIMEOUT;
903 				    xpt_freeze_simq(ch->sim, 1);
904 				    ch->toslots |= (1 << slot->slot);
905 				    goto end_finished;
906 				}
907 				ATA_OUTSW_STRM(ch->r_mem, ATA_DATA,
908 				   (uint16_t *)(ccb->ataio.data_ptr + ch->donecount),
909 				   ch->transfersize / 2);
910 				return;
911 			}
912 			/* If data read command, return & wait for interrupt */
913 			if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN)
914 				return;
915 		    }
916 		}
917 	} else if (ch->basic_dma) {	/* ATAPI DMA */
918 		if (status & ATA_S_DWF)
919 			et = MVS_ERR_TFE;
920 		else if (ATA_INL(ch->r_mem, DMA_S) & DMA_S_ERR)
921 			et = MVS_ERR_TFE;
922 		/* Stop basic DMA. */
923 		ATA_OUTL(ch->r_mem, DMA_C, 0);
924 		goto end_finished;
925 	} else {			/* ATAPI PIO */
926 		length = ATA_INB(ch->r_mem,ATA_CYL_LSB) |
927 		    (ATA_INB(ch->r_mem,ATA_CYL_MSB) << 8);
928 		size = min(ch->transfersize, length);
929 		ireason = ATA_INB(ch->r_mem,ATA_IREASON);
930 		switch ((ireason & (ATA_I_CMD | ATA_I_IN)) |
931 			(status & ATA_S_DRQ)) {
932 
933 		case ATAPI_P_CMDOUT:
934 		    device_printf(dev, "ATAPI CMDOUT\n");
935 		    /* Return wait for interrupt */
936 		    return;
937 
938 		case ATAPI_P_WRITE:
939 		    if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
940 			device_printf(dev, "trying to write on read buffer\n");
941 			et = MVS_ERR_TFE;
942 			goto end_finished;
943 			break;
944 		    }
945 		    ATA_OUTSW_STRM(ch->r_mem, ATA_DATA,
946 			(uint16_t *)(ccb->csio.data_ptr + ch->donecount),
947 			(size + 1) / 2);
948 		    for (resid = ch->transfersize + (size & 1);
949 			resid < length; resid += sizeof(int16_t))
950 			    ATA_OUTW(ch->r_mem, ATA_DATA, 0);
951 		    ch->donecount += length;
952 		    /* Set next transfer size according to HW capabilities */
953 		    ch->transfersize = min(ccb->csio.dxfer_len - ch->donecount,
954 			    ch->curr[ccb->ccb_h.target_id].bytecount);
955 		    /* Return wait for interrupt */
956 		    return;
957 
958 		case ATAPI_P_READ:
959 		    if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_OUT) {
960 			device_printf(dev, "trying to read on write buffer\n");
961 			et = MVS_ERR_TFE;
962 			goto end_finished;
963 		    }
964 		    if (size >= 2) {
965 			ATA_INSW_STRM(ch->r_mem, ATA_DATA,
966 			    (uint16_t *)(ccb->csio.data_ptr + ch->donecount),
967 			    size / 2);
968 		    }
969 		    if (size & 1) {
970 			ATA_INSW_STRM(ch->r_mem, ATA_DATA, (void*)buf, 1);
971 			((uint8_t *)ccb->csio.data_ptr + ch->donecount +
972 			    (size & ~1))[0] = buf[0];
973 		    }
974 		    for (resid = ch->transfersize + (size & 1);
975 			resid < length; resid += sizeof(int16_t))
976 			    ATA_INW(ch->r_mem, ATA_DATA);
977 		    ch->donecount += length;
978 		    /* Set next transfer size according to HW capabilities */
979 		    ch->transfersize = min(ccb->csio.dxfer_len - ch->donecount,
980 			    ch->curr[ccb->ccb_h.target_id].bytecount);
981 		    /* Return wait for interrupt */
982 		    return;
983 
984 		case ATAPI_P_DONEDRQ:
985 		    device_printf(dev,
986 			  "WARNING - DONEDRQ non conformant device\n");
987 		    if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
988 			ATA_INSW_STRM(ch->r_mem, ATA_DATA,
989 			    (uint16_t *)(ccb->csio.data_ptr + ch->donecount),
990 			    length / 2);
991 			ch->donecount += length;
992 		    }
993 		    else if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_OUT) {
994 			ATA_OUTSW_STRM(ch->r_mem, ATA_DATA,
995 			    (uint16_t *)(ccb->csio.data_ptr + ch->donecount),
996 			    length / 2);
997 			ch->donecount += length;
998 		    }
999 		    else
1000 			et = MVS_ERR_TFE;
1001 		    /* FALLTHROUGH */
1002 
1003 		case ATAPI_P_ABORT:
1004 		case ATAPI_P_DONE:
1005 		    if (status & (ATA_S_ERROR | ATA_S_DWF))
1006 			et = MVS_ERR_TFE;
1007 		    goto end_finished;
1008 
1009 		default:
1010 		    device_printf(dev, "unknown transfer phase"
1011 			" (status %02x, ireason %02x)\n",
1012 			status, ireason);
1013 		    et = MVS_ERR_TFE;
1014 		}
1015 	}
1016 
1017 end_finished:
1018 	mvs_end_transaction(slot, et);
1019 }
1020 
1021 static void
1022 mvs_crbq_intr(device_t dev)
1023 {
1024 	struct mvs_channel *ch = device_get_softc(dev);
1025 	struct mvs_crpb *crpb;
1026 	union ccb *ccb;
1027 	int in_idx, fin_idx, cin_idx, slot;
1028 	uint32_t val;
1029 	uint16_t flags;
1030 
1031 	val = ATA_INL(ch->r_mem, EDMA_RESQIP);
1032 	if (val == 0)
1033 		val = ATA_INL(ch->r_mem, EDMA_RESQIP);
1034 	in_idx = (val & EDMA_RESQP_ERPQP_MASK) >>
1035 	    EDMA_RESQP_ERPQP_SHIFT;
1036 	bus_dmamap_sync(ch->dma.workrp_tag, ch->dma.workrp_map,
1037 	    BUS_DMASYNC_POSTREAD);
1038 	fin_idx = cin_idx = ch->in_idx;
1039 	ch->in_idx = in_idx;
1040 	while (in_idx != cin_idx) {
1041 		crpb = (struct mvs_crpb *)
1042 		    (ch->dma.workrp + MVS_CRPB_OFFSET +
1043 		    (MVS_CRPB_SIZE * cin_idx));
1044 		slot = le16toh(crpb->id) & MVS_CRPB_TAG_MASK;
1045 		flags = le16toh(crpb->rspflg);
1046 		/*
1047 		 * Handle only successful completions here.
1048 		 * Errors will be handled by main intr handler.
1049 		 */
1050 #if defined(__i386__) || defined(__amd64__)
1051 		if (crpb->id == 0xffff && crpb->rspflg == 0xffff) {
1052 			device_printf(dev, "Unfilled CRPB "
1053 			    "%d (%d->%d) tag %d flags %04x rs %08x\n",
1054 			    cin_idx, fin_idx, in_idx, slot, flags, ch->rslots);
1055 		} else
1056 #endif
1057 		if (ch->numtslots != 0 ||
1058 		    (flags & EDMA_IE_EDEVERR) == 0) {
1059 #if defined(__i386__) || defined(__amd64__)
1060 			crpb->id = 0xffff;
1061 			crpb->rspflg = 0xffff;
1062 #endif
1063 			if (ch->slot[slot].state >= MVS_SLOT_RUNNING) {
1064 				ccb = ch->slot[slot].ccb;
1065 				ccb->ataio.res.status =
1066 				    (flags & MVS_CRPB_ATASTS_MASK) >>
1067 				    MVS_CRPB_ATASTS_SHIFT;
1068 				mvs_end_transaction(&ch->slot[slot], MVS_ERR_NONE);
1069 			} else {
1070 				device_printf(dev, "Unused tag in CRPB "
1071 				    "%d (%d->%d) tag %d flags %04x rs %08x\n",
1072 				    cin_idx, fin_idx, in_idx, slot, flags,
1073 				    ch->rslots);
1074 			}
1075 		} else {
1076 			device_printf(dev,
1077 			    "CRPB with error %d tag %d flags %04x\n",
1078 			    cin_idx, slot, flags);
1079 		}
1080 		cin_idx = (cin_idx + 1) & (MVS_MAX_SLOTS - 1);
1081 	}
1082 	bus_dmamap_sync(ch->dma.workrp_tag, ch->dma.workrp_map,
1083 	    BUS_DMASYNC_PREREAD);
1084 	if (cin_idx == ch->in_idx) {
1085 		ATA_OUTL(ch->r_mem, EDMA_RESQOP,
1086 		    ch->dma.workrp_bus | (cin_idx << EDMA_RESQP_ERPQP_SHIFT));
1087 	}
1088 }
1089 
1090 /* Must be called with channel locked. */
1091 static int
1092 mvs_check_collision(device_t dev, union ccb *ccb)
1093 {
1094 	struct mvs_channel *ch = device_get_softc(dev);
1095 
1096 	if (ccb->ccb_h.func_code == XPT_ATA_IO) {
1097 		/* NCQ DMA */
1098 		if (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA) {
1099 			/* Can't mix NCQ and non-NCQ DMA commands. */
1100 			if (ch->numdslots != 0)
1101 				return (1);
1102 			/* Can't mix NCQ and PIO commands. */
1103 			if (ch->numpslots != 0)
1104 				return (1);
1105 			/* If we have no FBS */
1106 			if (!ch->fbs_enabled) {
1107 				/* Tagged command while tagged to other target is active. */
1108 				if (ch->numtslots != 0 &&
1109 				    ch->taggedtarget != ccb->ccb_h.target_id)
1110 					return (1);
1111 			}
1112 		/* Non-NCQ DMA */
1113 		} else if (ccb->ataio.cmd.flags & CAM_ATAIO_DMA) {
1114 			/* Can't mix non-NCQ DMA and NCQ commands. */
1115 			if (ch->numtslots != 0)
1116 				return (1);
1117 			/* Can't mix non-NCQ DMA and PIO commands. */
1118 			if (ch->numpslots != 0)
1119 				return (1);
1120 		/* PIO */
1121 		} else {
1122 			/* Can't mix PIO with anything. */
1123 			if (ch->numrslots != 0)
1124 				return (1);
1125 		}
1126 		if (ccb->ataio.cmd.flags & (CAM_ATAIO_CONTROL | CAM_ATAIO_NEEDRESULT)) {
1127 			/* Atomic command while anything active. */
1128 			if (ch->numrslots != 0)
1129 				return (1);
1130 		}
1131 	} else { /* ATAPI */
1132 		/* ATAPI goes without EDMA, so can't mix it with anything. */
1133 		if (ch->numrslots != 0)
1134 			return (1);
1135 	}
1136 	/* We have some atomic command running. */
1137 	if (ch->aslots != 0)
1138 		return (1);
1139 	return (0);
1140 }
1141 
1142 static void
1143 mvs_tfd_read(device_t dev, union ccb *ccb)
1144 {
1145 	struct mvs_channel *ch = device_get_softc(dev);
1146 	struct ata_res *res = &ccb->ataio.res;
1147 
1148 	res->status = ATA_INB(ch->r_mem, ATA_ALTSTAT);
1149 	res->error =  ATA_INB(ch->r_mem, ATA_ERROR);
1150 	res->device = ATA_INB(ch->r_mem, ATA_DRIVE);
1151 	ATA_OUTB(ch->r_mem, ATA_CONTROL, ATA_A_HOB);
1152 	res->sector_count_exp = ATA_INB(ch->r_mem, ATA_COUNT);
1153 	res->lba_low_exp = ATA_INB(ch->r_mem, ATA_SECTOR);
1154 	res->lba_mid_exp = ATA_INB(ch->r_mem, ATA_CYL_LSB);
1155 	res->lba_high_exp = ATA_INB(ch->r_mem, ATA_CYL_MSB);
1156 	ATA_OUTB(ch->r_mem, ATA_CONTROL, 0);
1157 	res->sector_count = ATA_INB(ch->r_mem, ATA_COUNT);
1158 	res->lba_low = ATA_INB(ch->r_mem, ATA_SECTOR);
1159 	res->lba_mid = ATA_INB(ch->r_mem, ATA_CYL_LSB);
1160 	res->lba_high = ATA_INB(ch->r_mem, ATA_CYL_MSB);
1161 }
1162 
1163 static void
1164 mvs_tfd_write(device_t dev, union ccb *ccb)
1165 {
1166 	struct mvs_channel *ch = device_get_softc(dev);
1167 	struct ata_cmd *cmd = &ccb->ataio.cmd;
1168 
1169 	ATA_OUTB(ch->r_mem, ATA_DRIVE, cmd->device);
1170 	ATA_OUTB(ch->r_mem, ATA_CONTROL, cmd->control);
1171 	ATA_OUTB(ch->r_mem, ATA_FEATURE, cmd->features_exp);
1172 	ATA_OUTB(ch->r_mem, ATA_FEATURE, cmd->features);
1173 	ATA_OUTB(ch->r_mem, ATA_COUNT, cmd->sector_count_exp);
1174 	ATA_OUTB(ch->r_mem, ATA_COUNT, cmd->sector_count);
1175 	ATA_OUTB(ch->r_mem, ATA_SECTOR, cmd->lba_low_exp);
1176 	ATA_OUTB(ch->r_mem, ATA_SECTOR, cmd->lba_low);
1177 	ATA_OUTB(ch->r_mem, ATA_CYL_LSB, cmd->lba_mid_exp);
1178 	ATA_OUTB(ch->r_mem, ATA_CYL_LSB, cmd->lba_mid);
1179 	ATA_OUTB(ch->r_mem, ATA_CYL_MSB, cmd->lba_high_exp);
1180 	ATA_OUTB(ch->r_mem, ATA_CYL_MSB, cmd->lba_high);
1181 	ATA_OUTB(ch->r_mem, ATA_COMMAND, cmd->command);
1182 }
1183 
1184 
1185 /* Must be called with channel locked. */
1186 static void
1187 mvs_begin_transaction(device_t dev, union ccb *ccb)
1188 {
1189 	struct mvs_channel *ch = device_get_softc(dev);
1190 	struct mvs_slot *slot;
1191 	int slotn, tag;
1192 
1193 	if (ch->pm_level > 0)
1194 		mvs_ch_pm_wake(dev);
1195 	/* Softreset is a special case. */
1196 	if (ccb->ccb_h.func_code == XPT_ATA_IO &&
1197 	    (ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL)) {
1198 		mvs_softreset(dev, ccb);
1199 		return;
1200 	}
1201 	/* Choose empty slot. */
1202 	slotn = ffs(~ch->oslots) - 1;
1203 	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1204 	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA)) {
1205 		if (ch->quirks & MVS_Q_GENIIE)
1206 			tag = ffs(~ch->otagspd[ccb->ccb_h.target_id]) - 1;
1207 		else
1208 			tag = slotn;
1209 	} else
1210 		tag = 0;
1211 	/* Occupy chosen slot. */
1212 	slot = &ch->slot[slotn];
1213 	slot->ccb = ccb;
1214 	slot->tag = tag;
1215 	/* Stop PM timer. */
1216 	if (ch->numrslots == 0 && ch->pm_level > 3)
1217 		callout_stop(&ch->pm_timer);
1218 	/* Update channel stats. */
1219 	ch->oslots |= (1 << slot->slot);
1220 	ch->numrslots++;
1221 	ch->numrslotspd[ccb->ccb_h.target_id]++;
1222 	if (ccb->ccb_h.func_code == XPT_ATA_IO) {
1223 		if (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA) {
1224 			ch->otagspd[ccb->ccb_h.target_id] |= (1 << slot->tag);
1225 			ch->numtslots++;
1226 			ch->numtslotspd[ccb->ccb_h.target_id]++;
1227 			ch->taggedtarget = ccb->ccb_h.target_id;
1228 			mvs_set_edma_mode(dev, MVS_EDMA_NCQ);
1229 		} else if (ccb->ataio.cmd.flags & CAM_ATAIO_DMA) {
1230 			ch->numdslots++;
1231 			mvs_set_edma_mode(dev, MVS_EDMA_ON);
1232 		} else {
1233 			ch->numpslots++;
1234 			mvs_set_edma_mode(dev, MVS_EDMA_OFF);
1235 		}
1236 		if (ccb->ataio.cmd.flags &
1237 		    (CAM_ATAIO_CONTROL | CAM_ATAIO_NEEDRESULT)) {
1238 			ch->aslots |= (1 << slot->slot);
1239 		}
1240 	} else {
1241 		uint8_t *cdb = (ccb->ccb_h.flags & CAM_CDB_POINTER) ?
1242 		    ccb->csio.cdb_io.cdb_ptr : ccb->csio.cdb_io.cdb_bytes;
1243 		ch->numpslots++;
1244 		/* Use ATAPI DMA only for commands without under-/overruns. */
1245 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE &&
1246 		    ch->curr[ccb->ccb_h.target_id].mode >= ATA_DMA &&
1247 		    (ch->quirks & MVS_Q_SOC) == 0 &&
1248 		    (cdb[0] == 0x08 ||
1249 		     cdb[0] == 0x0a ||
1250 		     cdb[0] == 0x28 ||
1251 		     cdb[0] == 0x2a ||
1252 		     cdb[0] == 0x88 ||
1253 		     cdb[0] == 0x8a ||
1254 		     cdb[0] == 0xa8 ||
1255 		     cdb[0] == 0xaa ||
1256 		     cdb[0] == 0xbe)) {
1257 			ch->basic_dma = 1;
1258 		}
1259 		mvs_set_edma_mode(dev, MVS_EDMA_OFF);
1260 	}
1261 	if (ch->numpslots == 0 || ch->basic_dma) {
1262 		slot->state = MVS_SLOT_LOADING;
1263 		bus_dmamap_load_ccb(ch->dma.data_tag, slot->dma.data_map,
1264 		    ccb, mvs_dmasetprd, slot, 0);
1265 	} else
1266 		mvs_legacy_execute_transaction(slot);
1267 }
1268 
1269 /* Locked by busdma engine. */
1270 static void
1271 mvs_dmasetprd(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
1272 {
1273 	struct mvs_slot *slot = arg;
1274 	struct mvs_channel *ch = device_get_softc(slot->dev);
1275 	struct mvs_eprd *eprd;
1276 	int i;
1277 
1278 	if (error) {
1279 		device_printf(slot->dev, "DMA load error\n");
1280 		mvs_end_transaction(slot, MVS_ERR_INVALID);
1281 		return;
1282 	}
1283 	KASSERT(nsegs <= MVS_SG_ENTRIES, ("too many DMA segment entries\n"));
1284 	/* If there is only one segment - no need to use S/G table on Gen-IIe. */
1285 	if (nsegs == 1 && ch->basic_dma == 0 && (ch->quirks & MVS_Q_GENIIE)) {
1286 		slot->dma.addr = segs[0].ds_addr;
1287 		slot->dma.len = segs[0].ds_len;
1288 	} else {
1289 		slot->dma.addr = 0;
1290 		/* Get a piece of the workspace for this EPRD */
1291 		eprd = (struct mvs_eprd *)
1292 		    (ch->dma.workrq + MVS_EPRD_OFFSET + (MVS_EPRD_SIZE * slot->slot));
1293 		/* Fill S/G table */
1294 		for (i = 0; i < nsegs; i++) {
1295 			eprd[i].prdbal = htole32(segs[i].ds_addr);
1296 			eprd[i].bytecount = htole32(segs[i].ds_len & MVS_EPRD_MASK);
1297 			eprd[i].prdbah = htole32((segs[i].ds_addr >> 16) >> 16);
1298 		}
1299 		eprd[i - 1].bytecount |= htole32(MVS_EPRD_EOF);
1300 	}
1301 	bus_dmamap_sync(ch->dma.data_tag, slot->dma.data_map,
1302 	    ((slot->ccb->ccb_h.flags & CAM_DIR_IN) ?
1303 	    BUS_DMASYNC_PREREAD : BUS_DMASYNC_PREWRITE));
1304 	if (ch->basic_dma)
1305 		mvs_legacy_execute_transaction(slot);
1306 	else
1307 		mvs_execute_transaction(slot);
1308 }
1309 
1310 static void
1311 mvs_legacy_execute_transaction(struct mvs_slot *slot)
1312 {
1313 	device_t dev = slot->dev;
1314 	struct mvs_channel *ch = device_get_softc(dev);
1315 	bus_addr_t eprd;
1316 	union ccb *ccb = slot->ccb;
1317 	int port = ccb->ccb_h.target_id & 0x0f;
1318 	int timeout;
1319 
1320 	slot->state = MVS_SLOT_RUNNING;
1321 	ch->rslots |= (1 << slot->slot);
1322 	ATA_OUTB(ch->r_mem, SATA_SATAICTL, port << SATA_SATAICTL_PMPTX_SHIFT);
1323 	if (ccb->ccb_h.func_code == XPT_ATA_IO) {
1324 		mvs_tfd_write(dev, ccb);
1325 		/* Device reset doesn't interrupt. */
1326 		if (ccb->ataio.cmd.command == ATA_DEVICE_RESET) {
1327 			int timeout = 1000000;
1328 			do {
1329 			    DELAY(10);
1330 			    ccb->ataio.res.status = ATA_INB(ch->r_mem, ATA_STATUS);
1331 			} while (ccb->ataio.res.status & ATA_S_BUSY && timeout--);
1332 			mvs_legacy_intr(dev, 1);
1333 			return;
1334 		}
1335 		ch->donecount = 0;
1336 		if (ccb->ataio.cmd.command == ATA_READ_MUL ||
1337 		    ccb->ataio.cmd.command == ATA_READ_MUL48 ||
1338 		    ccb->ataio.cmd.command == ATA_WRITE_MUL ||
1339 		    ccb->ataio.cmd.command == ATA_WRITE_MUL48) {
1340 			ch->transfersize = min(ccb->ataio.dxfer_len,
1341 			    ch->curr[port].bytecount);
1342 		} else
1343 			ch->transfersize = min(ccb->ataio.dxfer_len, 512);
1344 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE)
1345 			ch->fake_busy = 1;
1346 		/* If data write command - output the data */
1347 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_OUT) {
1348 			if (mvs_wait(dev, ATA_S_DRQ, ATA_S_BUSY, 1000) < 0) {
1349 				device_printf(dev,
1350 				    "timeout waiting for write DRQ\n");
1351 				xpt_freeze_simq(ch->sim, 1);
1352 				ch->toslots |= (1 << slot->slot);
1353 				mvs_end_transaction(slot, MVS_ERR_TIMEOUT);
1354 				return;
1355 			}
1356 			ATA_OUTSW_STRM(ch->r_mem, ATA_DATA,
1357 			   (uint16_t *)(ccb->ataio.data_ptr + ch->donecount),
1358 			   ch->transfersize / 2);
1359 		}
1360 	} else {
1361 		ch->donecount = 0;
1362 		ch->transfersize = min(ccb->csio.dxfer_len,
1363 		    ch->curr[port].bytecount);
1364 		/* Write ATA PACKET command. */
1365 		if (ch->basic_dma) {
1366 			ATA_OUTB(ch->r_mem, ATA_FEATURE, ATA_F_DMA);
1367 			ATA_OUTB(ch->r_mem, ATA_CYL_LSB, 0);
1368 		    	ATA_OUTB(ch->r_mem, ATA_CYL_MSB, 0);
1369 		} else {
1370 			ATA_OUTB(ch->r_mem, ATA_FEATURE, 0);
1371 			ATA_OUTB(ch->r_mem, ATA_CYL_LSB, ch->transfersize);
1372 		    	ATA_OUTB(ch->r_mem, ATA_CYL_MSB, ch->transfersize >> 8);
1373 		}
1374 		ATA_OUTB(ch->r_mem, ATA_COMMAND, ATA_PACKET_CMD);
1375 		ch->fake_busy = 1;
1376 		/* Wait for ready to write ATAPI command block */
1377 		if (mvs_wait(dev, 0, ATA_S_BUSY, 1000) < 0) {
1378 			device_printf(dev, "timeout waiting for ATAPI !BUSY\n");
1379 			xpt_freeze_simq(ch->sim, 1);
1380 			ch->toslots |= (1 << slot->slot);
1381 			mvs_end_transaction(slot, MVS_ERR_TIMEOUT);
1382 			return;
1383 		}
1384 		timeout = 5000;
1385 		while (timeout--) {
1386 		    int reason = ATA_INB(ch->r_mem, ATA_IREASON);
1387 		    int status = ATA_INB(ch->r_mem, ATA_STATUS);
1388 
1389 		    if (((reason & (ATA_I_CMD | ATA_I_IN)) |
1390 			 (status & (ATA_S_DRQ | ATA_S_BUSY))) == ATAPI_P_CMDOUT)
1391 			break;
1392 		    DELAY(20);
1393 		}
1394 		if (timeout <= 0) {
1395 			device_printf(dev,
1396 			    "timeout waiting for ATAPI command ready\n");
1397 			xpt_freeze_simq(ch->sim, 1);
1398 			ch->toslots |= (1 << slot->slot);
1399 			mvs_end_transaction(slot, MVS_ERR_TIMEOUT);
1400 			return;
1401 		}
1402 		/* Write ATAPI command. */
1403 		ATA_OUTSW_STRM(ch->r_mem, ATA_DATA,
1404 		   (uint16_t *)((ccb->ccb_h.flags & CAM_CDB_POINTER) ?
1405 		    ccb->csio.cdb_io.cdb_ptr : ccb->csio.cdb_io.cdb_bytes),
1406 		   ch->curr[port].atapi / 2);
1407 		DELAY(10);
1408 		if (ch->basic_dma) {
1409 			/* Start basic DMA. */
1410 			eprd = ch->dma.workrq_bus + MVS_EPRD_OFFSET +
1411 			    (MVS_EPRD_SIZE * slot->slot);
1412 			ATA_OUTL(ch->r_mem, DMA_DTLBA, eprd);
1413 			ATA_OUTL(ch->r_mem, DMA_DTHBA, (eprd >> 16) >> 16);
1414 			ATA_OUTL(ch->r_mem, DMA_C, DMA_C_START |
1415 			    (((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) ?
1416 			    DMA_C_READ : 0));
1417 		}
1418 	}
1419 	/* Start command execution timeout */
1420 	callout_reset_sbt(&slot->timeout, SBT_1MS * ccb->ccb_h.timeout, 0,
1421 	    mvs_timeout, slot, 0);
1422 }
1423 
1424 /* Must be called with channel locked. */
1425 static void
1426 mvs_execute_transaction(struct mvs_slot *slot)
1427 {
1428 	device_t dev = slot->dev;
1429 	struct mvs_channel *ch = device_get_softc(dev);
1430 	bus_addr_t eprd;
1431 	struct mvs_crqb *crqb;
1432 	struct mvs_crqb_gen2e *crqb2e;
1433 	union ccb *ccb = slot->ccb;
1434 	int port = ccb->ccb_h.target_id & 0x0f;
1435 	int i;
1436 
1437 	/* Get address of the prepared EPRD */
1438 	eprd = ch->dma.workrq_bus + MVS_EPRD_OFFSET + (MVS_EPRD_SIZE * slot->slot);
1439 	/* Prepare CRQB. Gen IIe uses different CRQB format. */
1440 	if (ch->quirks & MVS_Q_GENIIE) {
1441 		crqb2e = (struct mvs_crqb_gen2e *)
1442 		    (ch->dma.workrq + MVS_CRQB_OFFSET + (MVS_CRQB_SIZE * ch->out_idx));
1443 		crqb2e->ctrlflg = htole32(
1444 		    ((ccb->ccb_h.flags & CAM_DIR_IN) ? MVS_CRQB2E_READ : 0) |
1445 		    (slot->tag << MVS_CRQB2E_DTAG_SHIFT) |
1446 		    (port << MVS_CRQB2E_PMP_SHIFT) |
1447 		    (slot->slot << MVS_CRQB2E_HTAG_SHIFT));
1448 		/* If there is only one segment - no need to use S/G table. */
1449 		if (slot->dma.addr != 0) {
1450 			eprd = slot->dma.addr;
1451 			crqb2e->ctrlflg |= htole32(MVS_CRQB2E_CPRD);
1452 			crqb2e->drbc = slot->dma.len;
1453 		}
1454 		crqb2e->cprdbl = htole32(eprd);
1455 		crqb2e->cprdbh = htole32((eprd >> 16) >> 16);
1456 		crqb2e->cmd[0] = 0;
1457 		crqb2e->cmd[1] = 0;
1458 		crqb2e->cmd[2] = ccb->ataio.cmd.command;
1459 		crqb2e->cmd[3] = ccb->ataio.cmd.features;
1460 		crqb2e->cmd[4] = ccb->ataio.cmd.lba_low;
1461 		crqb2e->cmd[5] = ccb->ataio.cmd.lba_mid;
1462 		crqb2e->cmd[6] = ccb->ataio.cmd.lba_high;
1463 		crqb2e->cmd[7] = ccb->ataio.cmd.device;
1464 		crqb2e->cmd[8] = ccb->ataio.cmd.lba_low_exp;
1465 		crqb2e->cmd[9] = ccb->ataio.cmd.lba_mid_exp;
1466 		crqb2e->cmd[10] = ccb->ataio.cmd.lba_high_exp;
1467 		crqb2e->cmd[11] = ccb->ataio.cmd.features_exp;
1468 		if (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA) {
1469 			crqb2e->cmd[12] = slot->tag << 3;
1470 			crqb2e->cmd[13] = 0;
1471 		} else {
1472 			crqb2e->cmd[12] = ccb->ataio.cmd.sector_count;
1473 			crqb2e->cmd[13] = ccb->ataio.cmd.sector_count_exp;
1474 		}
1475 		crqb2e->cmd[14] = 0;
1476 		crqb2e->cmd[15] = 0;
1477 	} else {
1478 		crqb = (struct mvs_crqb *)
1479 		    (ch->dma.workrq + MVS_CRQB_OFFSET + (MVS_CRQB_SIZE * ch->out_idx));
1480 		crqb->cprdbl = htole32(eprd);
1481 		crqb->cprdbh = htole32((eprd >> 16) >> 16);
1482 		crqb->ctrlflg = htole16(
1483 		    ((ccb->ccb_h.flags & CAM_DIR_IN) ? MVS_CRQB_READ : 0) |
1484 		    (slot->slot << MVS_CRQB_TAG_SHIFT) |
1485 		    (port << MVS_CRQB_PMP_SHIFT));
1486 		i = 0;
1487 		/*
1488 		 * Controller can handle only 11 of 12 ATA registers,
1489 		 * so we have to choose which one to skip.
1490 		 */
1491 		if (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA) {
1492 			crqb->cmd[i++] = ccb->ataio.cmd.features_exp;
1493 			crqb->cmd[i++] = 0x11;
1494 		}
1495 		crqb->cmd[i++] = ccb->ataio.cmd.features;
1496 		crqb->cmd[i++] = 0x11;
1497 		if (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA) {
1498 			crqb->cmd[i++] = slot->tag << 3;
1499 			crqb->cmd[i++] = 0x12;
1500 		} else {
1501 			crqb->cmd[i++] = ccb->ataio.cmd.sector_count_exp;
1502 			crqb->cmd[i++] = 0x12;
1503 			crqb->cmd[i++] = ccb->ataio.cmd.sector_count;
1504 			crqb->cmd[i++] = 0x12;
1505 		}
1506 		crqb->cmd[i++] = ccb->ataio.cmd.lba_low_exp;
1507 		crqb->cmd[i++] = 0x13;
1508 		crqb->cmd[i++] = ccb->ataio.cmd.lba_low;
1509 		crqb->cmd[i++] = 0x13;
1510 		crqb->cmd[i++] = ccb->ataio.cmd.lba_mid_exp;
1511 		crqb->cmd[i++] = 0x14;
1512 		crqb->cmd[i++] = ccb->ataio.cmd.lba_mid;
1513 		crqb->cmd[i++] = 0x14;
1514 		crqb->cmd[i++] = ccb->ataio.cmd.lba_high_exp;
1515 		crqb->cmd[i++] = 0x15;
1516 		crqb->cmd[i++] = ccb->ataio.cmd.lba_high;
1517 		crqb->cmd[i++] = 0x15;
1518 		crqb->cmd[i++] = ccb->ataio.cmd.device;
1519 		crqb->cmd[i++] = 0x16;
1520 		crqb->cmd[i++] = ccb->ataio.cmd.command;
1521 		crqb->cmd[i++] = 0x97;
1522 	}
1523 	bus_dmamap_sync(ch->dma.workrq_tag, ch->dma.workrq_map,
1524 	    BUS_DMASYNC_PREWRITE);
1525 	bus_dmamap_sync(ch->dma.workrp_tag, ch->dma.workrp_map,
1526 	    BUS_DMASYNC_PREREAD);
1527 	slot->state = MVS_SLOT_RUNNING;
1528 	ch->rslots |= (1 << slot->slot);
1529 	/* Issue command to the controller. */
1530 	ch->out_idx = (ch->out_idx + 1) & (MVS_MAX_SLOTS - 1);
1531 	ATA_OUTL(ch->r_mem, EDMA_REQQIP,
1532 	    ch->dma.workrq_bus + MVS_CRQB_OFFSET + (MVS_CRQB_SIZE * ch->out_idx));
1533 	/* Start command execution timeout */
1534 	callout_reset_sbt(&slot->timeout, SBT_1MS * ccb->ccb_h.timeout, 0,
1535 	    mvs_timeout, slot, 0);
1536 	return;
1537 }
1538 
1539 /* Must be called with channel locked. */
1540 static void
1541 mvs_process_timeout(device_t dev)
1542 {
1543 	struct mvs_channel *ch = device_get_softc(dev);
1544 	int i;
1545 
1546 	mtx_assert(&ch->mtx, MA_OWNED);
1547 	/* Handle the rest of commands. */
1548 	for (i = 0; i < MVS_MAX_SLOTS; i++) {
1549 		/* Do we have a running request on slot? */
1550 		if (ch->slot[i].state < MVS_SLOT_RUNNING)
1551 			continue;
1552 		mvs_end_transaction(&ch->slot[i], MVS_ERR_TIMEOUT);
1553 	}
1554 }
1555 
1556 /* Must be called with channel locked. */
1557 static void
1558 mvs_rearm_timeout(device_t dev)
1559 {
1560 	struct mvs_channel *ch = device_get_softc(dev);
1561 	int i;
1562 
1563 	mtx_assert(&ch->mtx, MA_OWNED);
1564 	for (i = 0; i < MVS_MAX_SLOTS; i++) {
1565 		struct mvs_slot *slot = &ch->slot[i];
1566 
1567 		/* Do we have a running request on slot? */
1568 		if (slot->state < MVS_SLOT_RUNNING)
1569 			continue;
1570 		if ((ch->toslots & (1 << i)) == 0)
1571 			continue;
1572 		callout_reset_sbt(&slot->timeout,
1573 		    SBT_1MS * slot->ccb->ccb_h.timeout / 2, 0,
1574 		    mvs_timeout, slot, 0);
1575 	}
1576 }
1577 
1578 /* Locked by callout mechanism. */
1579 static void
1580 mvs_timeout(void *arg)
1581 {
1582 	struct mvs_slot *slot = arg;
1583 	device_t dev = slot->dev;
1584 	struct mvs_channel *ch = device_get_softc(dev);
1585 
1586 	/* Check for stale timeout. */
1587 	if (slot->state < MVS_SLOT_RUNNING)
1588 		return;
1589 	device_printf(dev, "Timeout on slot %d\n", slot->slot);
1590 	device_printf(dev, "iec %08x sstat %08x serr %08x edma_s %08x "
1591 	    "dma_c %08x dma_s %08x rs %08x status %02x\n",
1592 	    ATA_INL(ch->r_mem, EDMA_IEC),
1593 	    ATA_INL(ch->r_mem, SATA_SS), ATA_INL(ch->r_mem, SATA_SE),
1594 	    ATA_INL(ch->r_mem, EDMA_S), ATA_INL(ch->r_mem, DMA_C),
1595 	    ATA_INL(ch->r_mem, DMA_S), ch->rslots,
1596 	    ATA_INB(ch->r_mem, ATA_ALTSTAT));
1597 	/* Handle frozen command. */
1598 	mvs_requeue_frozen(dev);
1599 	/* We wait for other commands timeout and pray. */
1600 	if (ch->toslots == 0)
1601 		xpt_freeze_simq(ch->sim, 1);
1602 	ch->toslots |= (1 << slot->slot);
1603 	if ((ch->rslots & ~ch->toslots) == 0)
1604 		mvs_process_timeout(dev);
1605 	else
1606 		device_printf(dev, " ... waiting for slots %08x\n",
1607 		    ch->rslots & ~ch->toslots);
1608 }
1609 
1610 /* Must be called with channel locked. */
1611 static void
1612 mvs_end_transaction(struct mvs_slot *slot, enum mvs_err_type et)
1613 {
1614 	device_t dev = slot->dev;
1615 	struct mvs_channel *ch = device_get_softc(dev);
1616 	union ccb *ccb = slot->ccb;
1617 	int lastto;
1618 
1619 	bus_dmamap_sync(ch->dma.workrq_tag, ch->dma.workrq_map,
1620 	    BUS_DMASYNC_POSTWRITE);
1621 	/* Read result registers to the result struct
1622 	 * May be incorrect if several commands finished same time,
1623 	 * so read only when sure or have to.
1624 	 */
1625 	if (ccb->ccb_h.func_code == XPT_ATA_IO) {
1626 		struct ata_res *res = &ccb->ataio.res;
1627 
1628 		if ((et == MVS_ERR_TFE) ||
1629 		    (ccb->ataio.cmd.flags & CAM_ATAIO_NEEDRESULT)) {
1630 			mvs_tfd_read(dev, ccb);
1631 		} else
1632 			bzero(res, sizeof(*res));
1633 	} else {
1634 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE &&
1635 		    ch->basic_dma == 0)
1636 			ccb->csio.resid = ccb->csio.dxfer_len - ch->donecount;
1637 	}
1638 	if (ch->numpslots == 0 || ch->basic_dma) {
1639 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
1640 			bus_dmamap_sync(ch->dma.data_tag, slot->dma.data_map,
1641 			    (ccb->ccb_h.flags & CAM_DIR_IN) ?
1642 			    BUS_DMASYNC_POSTREAD : BUS_DMASYNC_POSTWRITE);
1643 			bus_dmamap_unload(ch->dma.data_tag, slot->dma.data_map);
1644 		}
1645 	}
1646 	if (et != MVS_ERR_NONE)
1647 		ch->eslots |= (1 << slot->slot);
1648 	/* In case of error, freeze device for proper recovery. */
1649 	if ((et != MVS_ERR_NONE) && (!ch->recoverycmd) &&
1650 	    !(ccb->ccb_h.status & CAM_DEV_QFRZN)) {
1651 		xpt_freeze_devq(ccb->ccb_h.path, 1);
1652 		ccb->ccb_h.status |= CAM_DEV_QFRZN;
1653 	}
1654 	/* Set proper result status. */
1655 	ccb->ccb_h.status &= ~CAM_STATUS_MASK;
1656 	switch (et) {
1657 	case MVS_ERR_NONE:
1658 		ccb->ccb_h.status |= CAM_REQ_CMP;
1659 		if (ccb->ccb_h.func_code == XPT_SCSI_IO)
1660 			ccb->csio.scsi_status = SCSI_STATUS_OK;
1661 		break;
1662 	case MVS_ERR_INVALID:
1663 		ch->fatalerr = 1;
1664 		ccb->ccb_h.status |= CAM_REQ_INVALID;
1665 		break;
1666 	case MVS_ERR_INNOCENT:
1667 		ccb->ccb_h.status |= CAM_REQUEUE_REQ;
1668 		break;
1669 	case MVS_ERR_TFE:
1670 	case MVS_ERR_NCQ:
1671 		if (ccb->ccb_h.func_code == XPT_SCSI_IO) {
1672 			ccb->ccb_h.status |= CAM_SCSI_STATUS_ERROR;
1673 			ccb->csio.scsi_status = SCSI_STATUS_CHECK_COND;
1674 		} else {
1675 			ccb->ccb_h.status |= CAM_ATA_STATUS_ERROR;
1676 		}
1677 		break;
1678 	case MVS_ERR_SATA:
1679 		ch->fatalerr = 1;
1680 		if (!ch->recoverycmd) {
1681 			xpt_freeze_simq(ch->sim, 1);
1682 			ccb->ccb_h.status &= ~CAM_STATUS_MASK;
1683 			ccb->ccb_h.status |= CAM_RELEASE_SIMQ;
1684 		}
1685 		ccb->ccb_h.status |= CAM_UNCOR_PARITY;
1686 		break;
1687 	case MVS_ERR_TIMEOUT:
1688 		if (!ch->recoverycmd) {
1689 			xpt_freeze_simq(ch->sim, 1);
1690 			ccb->ccb_h.status &= ~CAM_STATUS_MASK;
1691 			ccb->ccb_h.status |= CAM_RELEASE_SIMQ;
1692 		}
1693 		ccb->ccb_h.status |= CAM_CMD_TIMEOUT;
1694 		break;
1695 	default:
1696 		ch->fatalerr = 1;
1697 		ccb->ccb_h.status |= CAM_REQ_CMP_ERR;
1698 	}
1699 	/* Free slot. */
1700 	ch->oslots &= ~(1 << slot->slot);
1701 	ch->rslots &= ~(1 << slot->slot);
1702 	ch->aslots &= ~(1 << slot->slot);
1703 	slot->state = MVS_SLOT_EMPTY;
1704 	slot->ccb = NULL;
1705 	/* Update channel stats. */
1706 	ch->numrslots--;
1707 	ch->numrslotspd[ccb->ccb_h.target_id]--;
1708 	if (ccb->ccb_h.func_code == XPT_ATA_IO) {
1709 		if (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA) {
1710 			ch->otagspd[ccb->ccb_h.target_id] &= ~(1 << slot->tag);
1711 			ch->numtslots--;
1712 			ch->numtslotspd[ccb->ccb_h.target_id]--;
1713 		} else if (ccb->ataio.cmd.flags & CAM_ATAIO_DMA) {
1714 			ch->numdslots--;
1715 		} else {
1716 			ch->numpslots--;
1717 		}
1718 	} else {
1719 		ch->numpslots--;
1720 		ch->basic_dma = 0;
1721 	}
1722 	/* Cancel timeout state if request completed normally. */
1723 	if (et != MVS_ERR_TIMEOUT) {
1724 		lastto = (ch->toslots == (1 << slot->slot));
1725 		ch->toslots &= ~(1 << slot->slot);
1726 		if (lastto)
1727 			xpt_release_simq(ch->sim, TRUE);
1728 	}
1729 	/* If it was our READ LOG command - process it. */
1730 	if (ccb->ccb_h.recovery_type == RECOVERY_READ_LOG) {
1731 		mvs_process_read_log(dev, ccb);
1732 	/* If it was our REQUEST SENSE command - process it. */
1733 	} else if (ccb->ccb_h.recovery_type == RECOVERY_REQUEST_SENSE) {
1734 		mvs_process_request_sense(dev, ccb);
1735 	/* If it was NCQ or ATAPI command error, put result on hold. */
1736 	} else if (et == MVS_ERR_NCQ ||
1737 	    ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_SCSI_STATUS_ERROR &&
1738 	     (ccb->ccb_h.flags & CAM_DIS_AUTOSENSE) == 0)) {
1739 		ch->hold[slot->slot] = ccb;
1740 		ch->holdtag[slot->slot] = slot->tag;
1741 		ch->numhslots++;
1742 	} else
1743 		xpt_done(ccb);
1744 	/* If we have no other active commands, ... */
1745 	if (ch->rslots == 0) {
1746 		/* if there was fatal error - reset port. */
1747 		if (ch->toslots != 0 || ch->fatalerr) {
1748 			mvs_reset(dev);
1749 		} else {
1750 			/* if we have slots in error, we can reinit port. */
1751 			if (ch->eslots != 0) {
1752 				mvs_set_edma_mode(dev, MVS_EDMA_OFF);
1753 				ch->eslots = 0;
1754 			}
1755 			/* if there commands on hold, we can do READ LOG. */
1756 			if (!ch->recoverycmd && ch->numhslots)
1757 				mvs_issue_recovery(dev);
1758 		}
1759 	/* If all the rest of commands are in timeout - give them chance. */
1760 	} else if ((ch->rslots & ~ch->toslots) == 0 &&
1761 	    et != MVS_ERR_TIMEOUT)
1762 		mvs_rearm_timeout(dev);
1763 	/* Unfreeze frozen command. */
1764 	if (ch->frozen && !mvs_check_collision(dev, ch->frozen)) {
1765 		union ccb *fccb = ch->frozen;
1766 		ch->frozen = NULL;
1767 		mvs_begin_transaction(dev, fccb);
1768 		xpt_release_simq(ch->sim, TRUE);
1769 	}
1770 	/* Start PM timer. */
1771 	if (ch->numrslots == 0 && ch->pm_level > 3 &&
1772 	    (ch->curr[ch->pm_present ? 15 : 0].caps & CTS_SATA_CAPS_D_PMREQ)) {
1773 		callout_schedule(&ch->pm_timer,
1774 		    (ch->pm_level == 4) ? hz / 1000 : hz / 8);
1775 	}
1776 }
1777 
1778 static void
1779 mvs_issue_recovery(device_t dev)
1780 {
1781 	struct mvs_channel *ch = device_get_softc(dev);
1782 	union ccb *ccb;
1783 	struct ccb_ataio *ataio;
1784 	struct ccb_scsiio *csio;
1785 	int i;
1786 
1787 	/* Find some held command. */
1788 	for (i = 0; i < MVS_MAX_SLOTS; i++) {
1789 		if (ch->hold[i])
1790 			break;
1791 	}
1792 	ccb = xpt_alloc_ccb_nowait();
1793 	if (ccb == NULL) {
1794 		device_printf(dev, "Unable to allocate recovery command\n");
1795 completeall:
1796 		/* We can't do anything -- complete held commands. */
1797 		for (i = 0; i < MVS_MAX_SLOTS; i++) {
1798 			if (ch->hold[i] == NULL)
1799 				continue;
1800 			ch->hold[i]->ccb_h.status &= ~CAM_STATUS_MASK;
1801 			ch->hold[i]->ccb_h.status |= CAM_RESRC_UNAVAIL;
1802 			xpt_done(ch->hold[i]);
1803 			ch->hold[i] = NULL;
1804 			ch->numhslots--;
1805 		}
1806 		mvs_reset(dev);
1807 		return;
1808 	}
1809 	ccb->ccb_h = ch->hold[i]->ccb_h;	/* Reuse old header. */
1810 	if (ccb->ccb_h.func_code == XPT_ATA_IO) {
1811 		/* READ LOG */
1812 		ccb->ccb_h.recovery_type = RECOVERY_READ_LOG;
1813 		ccb->ccb_h.func_code = XPT_ATA_IO;
1814 		ccb->ccb_h.flags = CAM_DIR_IN;
1815 		ccb->ccb_h.timeout = 1000;	/* 1s should be enough. */
1816 		ataio = &ccb->ataio;
1817 		ataio->data_ptr = malloc(512, M_MVS, M_NOWAIT);
1818 		if (ataio->data_ptr == NULL) {
1819 			xpt_free_ccb(ccb);
1820 			device_printf(dev,
1821 			    "Unable to allocate memory for READ LOG command\n");
1822 			goto completeall;
1823 		}
1824 		ataio->dxfer_len = 512;
1825 		bzero(&ataio->cmd, sizeof(ataio->cmd));
1826 		ataio->cmd.flags = CAM_ATAIO_48BIT;
1827 		ataio->cmd.command = 0x2F;	/* READ LOG EXT */
1828 		ataio->cmd.sector_count = 1;
1829 		ataio->cmd.sector_count_exp = 0;
1830 		ataio->cmd.lba_low = 0x10;
1831 		ataio->cmd.lba_mid = 0;
1832 		ataio->cmd.lba_mid_exp = 0;
1833 	} else {
1834 		/* REQUEST SENSE */
1835 		ccb->ccb_h.recovery_type = RECOVERY_REQUEST_SENSE;
1836 		ccb->ccb_h.recovery_slot = i;
1837 		ccb->ccb_h.func_code = XPT_SCSI_IO;
1838 		ccb->ccb_h.flags = CAM_DIR_IN;
1839 		ccb->ccb_h.status = 0;
1840 		ccb->ccb_h.timeout = 1000;	/* 1s should be enough. */
1841 		csio = &ccb->csio;
1842 		csio->data_ptr = (void *)&ch->hold[i]->csio.sense_data;
1843 		csio->dxfer_len = ch->hold[i]->csio.sense_len;
1844 		csio->cdb_len = 6;
1845 		bzero(&csio->cdb_io, sizeof(csio->cdb_io));
1846 		csio->cdb_io.cdb_bytes[0] = 0x03;
1847 		csio->cdb_io.cdb_bytes[4] = csio->dxfer_len;
1848 	}
1849 	/* Freeze SIM while doing recovery. */
1850 	ch->recoverycmd = 1;
1851 	xpt_freeze_simq(ch->sim, 1);
1852 	mvs_begin_transaction(dev, ccb);
1853 }
1854 
1855 static void
1856 mvs_process_read_log(device_t dev, union ccb *ccb)
1857 {
1858 	struct mvs_channel *ch = device_get_softc(dev);
1859 	uint8_t *data;
1860 	struct ata_res *res;
1861 	int i;
1862 
1863 	ch->recoverycmd = 0;
1864 
1865 	data = ccb->ataio.data_ptr;
1866 	if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP &&
1867 	    (data[0] & 0x80) == 0) {
1868 		for (i = 0; i < MVS_MAX_SLOTS; i++) {
1869 			if (!ch->hold[i])
1870 				continue;
1871 			if (ch->hold[i]->ccb_h.target_id != ccb->ccb_h.target_id)
1872 				continue;
1873 			if ((data[0] & 0x1F) == ch->holdtag[i]) {
1874 				res = &ch->hold[i]->ataio.res;
1875 				res->status = data[2];
1876 				res->error = data[3];
1877 				res->lba_low = data[4];
1878 				res->lba_mid = data[5];
1879 				res->lba_high = data[6];
1880 				res->device = data[7];
1881 				res->lba_low_exp = data[8];
1882 				res->lba_mid_exp = data[9];
1883 				res->lba_high_exp = data[10];
1884 				res->sector_count = data[12];
1885 				res->sector_count_exp = data[13];
1886 			} else {
1887 				ch->hold[i]->ccb_h.status &= ~CAM_STATUS_MASK;
1888 				ch->hold[i]->ccb_h.status |= CAM_REQUEUE_REQ;
1889 			}
1890 			xpt_done(ch->hold[i]);
1891 			ch->hold[i] = NULL;
1892 			ch->numhslots--;
1893 		}
1894 	} else {
1895 		if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP)
1896 			device_printf(dev, "Error while READ LOG EXT\n");
1897 		else if ((data[0] & 0x80) == 0) {
1898 			device_printf(dev,
1899 			    "Non-queued command error in READ LOG EXT\n");
1900 		}
1901 		for (i = 0; i < MVS_MAX_SLOTS; i++) {
1902 			if (!ch->hold[i])
1903 				continue;
1904 			if (ch->hold[i]->ccb_h.target_id != ccb->ccb_h.target_id)
1905 				continue;
1906 			xpt_done(ch->hold[i]);
1907 			ch->hold[i] = NULL;
1908 			ch->numhslots--;
1909 		}
1910 	}
1911 	free(ccb->ataio.data_ptr, M_MVS);
1912 	xpt_free_ccb(ccb);
1913 	xpt_release_simq(ch->sim, TRUE);
1914 }
1915 
1916 static void
1917 mvs_process_request_sense(device_t dev, union ccb *ccb)
1918 {
1919 	struct mvs_channel *ch = device_get_softc(dev);
1920 	int i;
1921 
1922 	ch->recoverycmd = 0;
1923 
1924 	i = ccb->ccb_h.recovery_slot;
1925 	if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
1926 		ch->hold[i]->ccb_h.status |= CAM_AUTOSNS_VALID;
1927 	} else {
1928 		ch->hold[i]->ccb_h.status &= ~CAM_STATUS_MASK;
1929 		ch->hold[i]->ccb_h.status |= CAM_AUTOSENSE_FAIL;
1930 	}
1931 	xpt_done(ch->hold[i]);
1932 	ch->hold[i] = NULL;
1933 	ch->numhslots--;
1934 	xpt_free_ccb(ccb);
1935 	xpt_release_simq(ch->sim, TRUE);
1936 }
1937 
1938 static int
1939 mvs_wait(device_t dev, u_int s, u_int c, int t)
1940 {
1941 	int timeout = 0;
1942 	uint8_t st;
1943 
1944 	while (((st =  mvs_getstatus(dev, 0)) & (s | c)) != s) {
1945 		if (timeout >= t) {
1946 			if (t != 0)
1947 				device_printf(dev, "Wait status %02x\n", st);
1948 			return (-1);
1949 		}
1950 		DELAY(1000);
1951 		timeout++;
1952 	}
1953 	return (timeout);
1954 }
1955 
1956 static void
1957 mvs_requeue_frozen(device_t dev)
1958 {
1959 	struct mvs_channel *ch = device_get_softc(dev);
1960 	union ccb *fccb = ch->frozen;
1961 
1962 	if (fccb) {
1963 		ch->frozen = NULL;
1964 		fccb->ccb_h.status = CAM_REQUEUE_REQ | CAM_RELEASE_SIMQ;
1965 		if (!(fccb->ccb_h.status & CAM_DEV_QFRZN)) {
1966 			xpt_freeze_devq(fccb->ccb_h.path, 1);
1967 			fccb->ccb_h.status |= CAM_DEV_QFRZN;
1968 		}
1969 		xpt_done(fccb);
1970 	}
1971 }
1972 
1973 static void
1974 mvs_reset_to(void *arg)
1975 {
1976 	device_t dev = arg;
1977 	struct mvs_channel *ch = device_get_softc(dev);
1978 	int t;
1979 
1980 	if (ch->resetting == 0)
1981 		return;
1982 	ch->resetting--;
1983 	if ((t = mvs_wait(dev, 0, ATA_S_BUSY | ATA_S_DRQ, 0)) >= 0) {
1984 		if (bootverbose) {
1985 			device_printf(dev,
1986 			    "MVS reset: device ready after %dms\n",
1987 			    (310 - ch->resetting) * 100);
1988 		}
1989 		ch->resetting = 0;
1990 		xpt_release_simq(ch->sim, TRUE);
1991 		return;
1992 	}
1993 	if (ch->resetting == 0) {
1994 		device_printf(dev,
1995 		    "MVS reset: device not ready after 31000ms\n");
1996 		xpt_release_simq(ch->sim, TRUE);
1997 		return;
1998 	}
1999 	callout_schedule(&ch->reset_timer, hz / 10);
2000 }
2001 
2002 static void
2003 mvs_errata(device_t dev)
2004 {
2005 	struct mvs_channel *ch = device_get_softc(dev);
2006 	uint32_t val;
2007 
2008 	if (ch->quirks & MVS_Q_SOC65) {
2009 		val = ATA_INL(ch->r_mem, SATA_PHYM3);
2010 		val &= ~(0x3 << 27);	/* SELMUPF = 1 */
2011 		val |= (0x1 << 27);
2012 		val &= ~(0x3 << 29);	/* SELMUPI = 1 */
2013 		val |= (0x1 << 29);
2014 		ATA_OUTL(ch->r_mem, SATA_PHYM3, val);
2015 
2016 		val = ATA_INL(ch->r_mem, SATA_PHYM4);
2017 		val &= ~0x1;		/* SATU_OD8 = 0 */
2018 		val |= (0x1 << 16);	/* reserved bit 16 = 1 */
2019 		ATA_OUTL(ch->r_mem, SATA_PHYM4, val);
2020 
2021 		val = ATA_INL(ch->r_mem, SATA_PHYM9_GEN2);
2022 		val &= ~0xf;		/* TXAMP[3:0] = 8 */
2023 		val |= 0x8;
2024 		val &= ~(0x1 << 14);	/* TXAMP[4] = 0 */
2025 		ATA_OUTL(ch->r_mem, SATA_PHYM9_GEN2, val);
2026 
2027 		val = ATA_INL(ch->r_mem, SATA_PHYM9_GEN1);
2028 		val &= ~0xf;		/* TXAMP[3:0] = 8 */
2029 		val |= 0x8;
2030 		val &= ~(0x1 << 14);	/* TXAMP[4] = 0 */
2031 		ATA_OUTL(ch->r_mem, SATA_PHYM9_GEN1, val);
2032 	}
2033 }
2034 
2035 static void
2036 mvs_reset(device_t dev)
2037 {
2038 	struct mvs_channel *ch = device_get_softc(dev);
2039 	int i;
2040 
2041 	xpt_freeze_simq(ch->sim, 1);
2042 	if (bootverbose)
2043 		device_printf(dev, "MVS reset...\n");
2044 	/* Forget about previous reset. */
2045 	if (ch->resetting) {
2046 		ch->resetting = 0;
2047 		callout_stop(&ch->reset_timer);
2048 		xpt_release_simq(ch->sim, TRUE);
2049 	}
2050 	/* Requeue freezed command. */
2051 	mvs_requeue_frozen(dev);
2052 	/* Kill the engine and requeue all running commands. */
2053 	mvs_set_edma_mode(dev, MVS_EDMA_OFF);
2054 	ATA_OUTL(ch->r_mem, DMA_C, 0);
2055 	for (i = 0; i < MVS_MAX_SLOTS; i++) {
2056 		/* Do we have a running request on slot? */
2057 		if (ch->slot[i].state < MVS_SLOT_RUNNING)
2058 			continue;
2059 		/* XXX; Commands in loading state. */
2060 		mvs_end_transaction(&ch->slot[i], MVS_ERR_INNOCENT);
2061 	}
2062 	for (i = 0; i < MVS_MAX_SLOTS; i++) {
2063 		if (!ch->hold[i])
2064 			continue;
2065 		xpt_done(ch->hold[i]);
2066 		ch->hold[i] = NULL;
2067 		ch->numhslots--;
2068 	}
2069 	if (ch->toslots != 0)
2070 		xpt_release_simq(ch->sim, TRUE);
2071 	ch->eslots = 0;
2072 	ch->toslots = 0;
2073 	ch->fatalerr = 0;
2074 	ch->fake_busy = 0;
2075 	/* Tell the XPT about the event */
2076 	xpt_async(AC_BUS_RESET, ch->path, NULL);
2077 	ATA_OUTL(ch->r_mem, EDMA_IEM, 0);
2078 	ATA_OUTL(ch->r_mem, EDMA_CMD, EDMA_CMD_EATARST);
2079 	DELAY(25);
2080 	ATA_OUTL(ch->r_mem, EDMA_CMD, 0);
2081 	mvs_errata(dev);
2082 	/* Reset and reconnect PHY, */
2083 	if (!mvs_sata_phy_reset(dev)) {
2084 		if (bootverbose)
2085 			device_printf(dev, "MVS reset: device not found\n");
2086 		ch->devices = 0;
2087 		ATA_OUTL(ch->r_mem, SATA_SE, 0xffffffff);
2088 		ATA_OUTL(ch->r_mem, EDMA_IEC, 0);
2089 		ATA_OUTL(ch->r_mem, EDMA_IEM, ~EDMA_IE_TRANSIENT);
2090 		xpt_release_simq(ch->sim, TRUE);
2091 		return;
2092 	}
2093 	if (bootverbose)
2094 		device_printf(dev, "MVS reset: device found\n");
2095 	/* Wait for clearing busy status. */
2096 	if ((i = mvs_wait(dev, 0, ATA_S_BUSY | ATA_S_DRQ,
2097 	    dumping ? 31000 : 0)) < 0) {
2098 		if (dumping) {
2099 			device_printf(dev,
2100 			    "MVS reset: device not ready after 31000ms\n");
2101 		} else
2102 			ch->resetting = 310;
2103 	} else if (bootverbose)
2104 		device_printf(dev, "MVS reset: device ready after %dms\n", i);
2105 	ch->devices = 1;
2106 	ATA_OUTL(ch->r_mem, SATA_SE, 0xffffffff);
2107 	ATA_OUTL(ch->r_mem, EDMA_IEC, 0);
2108 	ATA_OUTL(ch->r_mem, EDMA_IEM, ~EDMA_IE_TRANSIENT);
2109 	if (ch->resetting)
2110 		callout_reset(&ch->reset_timer, hz / 10, mvs_reset_to, dev);
2111 	else
2112 		xpt_release_simq(ch->sim, TRUE);
2113 }
2114 
2115 static void
2116 mvs_softreset(device_t dev, union ccb *ccb)
2117 {
2118 	struct mvs_channel *ch = device_get_softc(dev);
2119 	int port = ccb->ccb_h.target_id & 0x0f;
2120 	int i, stuck;
2121 	uint8_t status;
2122 
2123 	mvs_set_edma_mode(dev, MVS_EDMA_OFF);
2124 	ATA_OUTB(ch->r_mem, SATA_SATAICTL, port << SATA_SATAICTL_PMPTX_SHIFT);
2125 	ATA_OUTB(ch->r_mem, ATA_CONTROL, ATA_A_RESET);
2126 	DELAY(10000);
2127 	ATA_OUTB(ch->r_mem, ATA_CONTROL, 0);
2128 	ccb->ccb_h.status &= ~CAM_STATUS_MASK;
2129 	/* Wait for clearing busy status. */
2130 	if ((i = mvs_wait(dev, 0, ATA_S_BUSY, ccb->ccb_h.timeout)) < 0) {
2131 		ccb->ccb_h.status |= CAM_CMD_TIMEOUT;
2132 		stuck = 1;
2133 	} else {
2134 		status = mvs_getstatus(dev, 0);
2135 		if (status & ATA_S_ERROR)
2136 			ccb->ccb_h.status |= CAM_ATA_STATUS_ERROR;
2137 		else
2138 			ccb->ccb_h.status |= CAM_REQ_CMP;
2139 		if (status & ATA_S_DRQ)
2140 			stuck = 1;
2141 		else
2142 			stuck = 0;
2143 	}
2144 	mvs_tfd_read(dev, ccb);
2145 
2146 	/*
2147 	 * XXX: If some device on PMP failed to soft-reset,
2148 	 * try to recover by sending dummy soft-reset to PMP.
2149 	 */
2150 	if (stuck && ch->pm_present && port != 15) {
2151 		ATA_OUTB(ch->r_mem, SATA_SATAICTL,
2152 		    15 << SATA_SATAICTL_PMPTX_SHIFT);
2153 		ATA_OUTB(ch->r_mem, ATA_CONTROL, ATA_A_RESET);
2154 		DELAY(10000);
2155 		ATA_OUTB(ch->r_mem, ATA_CONTROL, 0);
2156 		mvs_wait(dev, 0, ATA_S_BUSY | ATA_S_DRQ, ccb->ccb_h.timeout);
2157 	}
2158 
2159 	xpt_done(ccb);
2160 }
2161 
2162 static int
2163 mvs_sata_connect(struct mvs_channel *ch)
2164 {
2165 	u_int32_t status;
2166 	int timeout, found = 0;
2167 
2168 	/* Wait up to 100ms for "connect well" */
2169 	for (timeout = 0; timeout < 1000 ; timeout++) {
2170 		status = ATA_INL(ch->r_mem, SATA_SS);
2171 		if ((status & SATA_SS_DET_MASK) != SATA_SS_DET_NO_DEVICE)
2172 			found = 1;
2173 		if (((status & SATA_SS_DET_MASK) == SATA_SS_DET_PHY_ONLINE) &&
2174 		    ((status & SATA_SS_SPD_MASK) != SATA_SS_SPD_NO_SPEED) &&
2175 		    ((status & SATA_SS_IPM_MASK) == SATA_SS_IPM_ACTIVE))
2176 			break;
2177 		if ((status & SATA_SS_DET_MASK) == SATA_SS_DET_PHY_OFFLINE) {
2178 			if (bootverbose) {
2179 				device_printf(ch->dev, "SATA offline status=%08x\n",
2180 				    status);
2181 			}
2182 			return (0);
2183 		}
2184 		if (found == 0 && timeout >= 100)
2185 			break;
2186 		DELAY(100);
2187 	}
2188 	if (timeout >= 1000 || !found) {
2189 		if (bootverbose) {
2190 			device_printf(ch->dev,
2191 			    "SATA connect timeout time=%dus status=%08x\n",
2192 			    timeout * 100, status);
2193 		}
2194 		return (0);
2195 	}
2196 	if (bootverbose) {
2197 		device_printf(ch->dev, "SATA connect time=%dus status=%08x\n",
2198 		    timeout * 100, status);
2199 	}
2200 	/* Clear SATA error register */
2201 	ATA_OUTL(ch->r_mem, SATA_SE, 0xffffffff);
2202 	return (1);
2203 }
2204 
2205 static int
2206 mvs_sata_phy_reset(device_t dev)
2207 {
2208 	struct mvs_channel *ch = device_get_softc(dev);
2209 	int sata_rev;
2210 	uint32_t val;
2211 
2212 	sata_rev = ch->user[ch->pm_present ? 15 : 0].revision;
2213 	if (sata_rev == 1)
2214 		val = SATA_SC_SPD_SPEED_GEN1;
2215 	else if (sata_rev == 2)
2216 		val = SATA_SC_SPD_SPEED_GEN2;
2217 	else if (sata_rev == 3)
2218 		val = SATA_SC_SPD_SPEED_GEN3;
2219 	else
2220 		val = 0;
2221 	ATA_OUTL(ch->r_mem, SATA_SC,
2222 	    SATA_SC_DET_RESET | val |
2223 	    SATA_SC_IPM_DIS_PARTIAL | SATA_SC_IPM_DIS_SLUMBER);
2224 	DELAY(1000);
2225 	ATA_OUTL(ch->r_mem, SATA_SC,
2226 	    SATA_SC_DET_IDLE | val | ((ch->pm_level > 0) ? 0 :
2227 	    (SATA_SC_IPM_DIS_PARTIAL | SATA_SC_IPM_DIS_SLUMBER)));
2228 	if (!mvs_sata_connect(ch)) {
2229 		if (ch->pm_level > 0)
2230 			ATA_OUTL(ch->r_mem, SATA_SC, SATA_SC_DET_DISABLE);
2231 		return (0);
2232 	}
2233 	return (1);
2234 }
2235 
2236 static int
2237 mvs_check_ids(device_t dev, union ccb *ccb)
2238 {
2239 	struct mvs_channel *ch = device_get_softc(dev);
2240 
2241 	if (ccb->ccb_h.target_id > ((ch->quirks & MVS_Q_GENI) ? 0 : 15)) {
2242 		ccb->ccb_h.status = CAM_TID_INVALID;
2243 		xpt_done(ccb);
2244 		return (-1);
2245 	}
2246 	if (ccb->ccb_h.target_lun != 0) {
2247 		ccb->ccb_h.status = CAM_LUN_INVALID;
2248 		xpt_done(ccb);
2249 		return (-1);
2250 	}
2251 	/*
2252 	 * It's a programming error to see AUXILIARY register requests.
2253 	 */
2254 	KASSERT(ccb->ccb_h.func_code != XPT_ATA_IO ||
2255 	    ((ccb->ataio.ata_flags & ATA_FLAG_AUX) == 0),
2256 	    ("AUX register unsupported"));
2257 	return (0);
2258 }
2259 
2260 static void
2261 mvsaction(struct cam_sim *sim, union ccb *ccb)
2262 {
2263 	device_t dev, parent;
2264 	struct mvs_channel *ch;
2265 
2266 	CAM_DEBUG(ccb->ccb_h.path, CAM_DEBUG_TRACE, ("mvsaction func_code=%x\n",
2267 	    ccb->ccb_h.func_code));
2268 
2269 	ch = (struct mvs_channel *)cam_sim_softc(sim);
2270 	dev = ch->dev;
2271 	switch (ccb->ccb_h.func_code) {
2272 	/* Common cases first */
2273 	case XPT_ATA_IO:	/* Execute the requested I/O operation */
2274 	case XPT_SCSI_IO:
2275 		if (mvs_check_ids(dev, ccb))
2276 			return;
2277 		if (ch->devices == 0 ||
2278 		    (ch->pm_present == 0 &&
2279 		     ccb->ccb_h.target_id > 0 && ccb->ccb_h.target_id < 15)) {
2280 			ccb->ccb_h.status = CAM_SEL_TIMEOUT;
2281 			break;
2282 		}
2283 		ccb->ccb_h.recovery_type = RECOVERY_NONE;
2284 		/* Check for command collision. */
2285 		if (mvs_check_collision(dev, ccb)) {
2286 			/* Freeze command. */
2287 			ch->frozen = ccb;
2288 			/* We have only one frozen slot, so freeze simq also. */
2289 			xpt_freeze_simq(ch->sim, 1);
2290 			return;
2291 		}
2292 		mvs_begin_transaction(dev, ccb);
2293 		return;
2294 	case XPT_ABORT:			/* Abort the specified CCB */
2295 		/* XXX Implement */
2296 		ccb->ccb_h.status = CAM_REQ_INVALID;
2297 		break;
2298 	case XPT_SET_TRAN_SETTINGS:
2299 	{
2300 		struct	ccb_trans_settings *cts = &ccb->cts;
2301 		struct	mvs_device *d;
2302 
2303 		if (mvs_check_ids(dev, ccb))
2304 			return;
2305 		if (cts->type == CTS_TYPE_CURRENT_SETTINGS)
2306 			d = &ch->curr[ccb->ccb_h.target_id];
2307 		else
2308 			d = &ch->user[ccb->ccb_h.target_id];
2309 		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_REVISION)
2310 			d->revision = cts->xport_specific.sata.revision;
2311 		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_MODE)
2312 			d->mode = cts->xport_specific.sata.mode;
2313 		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_BYTECOUNT) {
2314 			d->bytecount = min((ch->quirks & MVS_Q_GENIIE) ? 8192 : 2048,
2315 			    cts->xport_specific.sata.bytecount);
2316 		}
2317 		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_TAGS)
2318 			d->tags = min(MVS_MAX_SLOTS, cts->xport_specific.sata.tags);
2319 		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_PM)
2320 			ch->pm_present = cts->xport_specific.sata.pm_present;
2321 		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_ATAPI)
2322 			d->atapi = cts->xport_specific.sata.atapi;
2323 		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_CAPS)
2324 			d->caps = cts->xport_specific.sata.caps;
2325 		ccb->ccb_h.status = CAM_REQ_CMP;
2326 		break;
2327 	}
2328 	case XPT_GET_TRAN_SETTINGS:
2329 	/* Get default/user set transfer settings for the target */
2330 	{
2331 		struct	ccb_trans_settings *cts = &ccb->cts;
2332 		struct  mvs_device *d;
2333 		uint32_t status;
2334 
2335 		if (mvs_check_ids(dev, ccb))
2336 			return;
2337 		if (cts->type == CTS_TYPE_CURRENT_SETTINGS)
2338 			d = &ch->curr[ccb->ccb_h.target_id];
2339 		else
2340 			d = &ch->user[ccb->ccb_h.target_id];
2341 		cts->protocol = PROTO_UNSPECIFIED;
2342 		cts->protocol_version = PROTO_VERSION_UNSPECIFIED;
2343 		cts->transport = XPORT_SATA;
2344 		cts->transport_version = XPORT_VERSION_UNSPECIFIED;
2345 		cts->proto_specific.valid = 0;
2346 		cts->xport_specific.sata.valid = 0;
2347 		if (cts->type == CTS_TYPE_CURRENT_SETTINGS &&
2348 		    (ccb->ccb_h.target_id == 15 ||
2349 		    (ccb->ccb_h.target_id == 0 && !ch->pm_present))) {
2350 			status = ATA_INL(ch->r_mem, SATA_SS) & SATA_SS_SPD_MASK;
2351 			if (status & 0x0f0) {
2352 				cts->xport_specific.sata.revision =
2353 				    (status & 0x0f0) >> 4;
2354 				cts->xport_specific.sata.valid |=
2355 				    CTS_SATA_VALID_REVISION;
2356 			}
2357 			cts->xport_specific.sata.caps = d->caps & CTS_SATA_CAPS_D;
2358 //			if (ch->pm_level)
2359 //				cts->xport_specific.sata.caps |= CTS_SATA_CAPS_H_PMREQ;
2360 			cts->xport_specific.sata.caps |= CTS_SATA_CAPS_H_AN;
2361 			cts->xport_specific.sata.caps &=
2362 			    ch->user[ccb->ccb_h.target_id].caps;
2363 			cts->xport_specific.sata.valid |= CTS_SATA_VALID_CAPS;
2364 		} else {
2365 			cts->xport_specific.sata.revision = d->revision;
2366 			cts->xport_specific.sata.valid |= CTS_SATA_VALID_REVISION;
2367 			cts->xport_specific.sata.caps = d->caps;
2368 			if (cts->type == CTS_TYPE_CURRENT_SETTINGS/* &&
2369 			    (ch->quirks & MVS_Q_GENIIE) == 0*/)
2370 				cts->xport_specific.sata.caps &= ~CTS_SATA_CAPS_H_AN;
2371 			cts->xport_specific.sata.valid |= CTS_SATA_VALID_CAPS;
2372 		}
2373 		cts->xport_specific.sata.mode = d->mode;
2374 		cts->xport_specific.sata.valid |= CTS_SATA_VALID_MODE;
2375 		cts->xport_specific.sata.bytecount = d->bytecount;
2376 		cts->xport_specific.sata.valid |= CTS_SATA_VALID_BYTECOUNT;
2377 		cts->xport_specific.sata.pm_present = ch->pm_present;
2378 		cts->xport_specific.sata.valid |= CTS_SATA_VALID_PM;
2379 		cts->xport_specific.sata.tags = d->tags;
2380 		cts->xport_specific.sata.valid |= CTS_SATA_VALID_TAGS;
2381 		cts->xport_specific.sata.atapi = d->atapi;
2382 		cts->xport_specific.sata.valid |= CTS_SATA_VALID_ATAPI;
2383 		ccb->ccb_h.status = CAM_REQ_CMP;
2384 		break;
2385 	}
2386 	case XPT_RESET_BUS:		/* Reset the specified SCSI bus */
2387 	case XPT_RESET_DEV:	/* Bus Device Reset the specified SCSI device */
2388 		mvs_reset(dev);
2389 		ccb->ccb_h.status = CAM_REQ_CMP;
2390 		break;
2391 	case XPT_TERM_IO:		/* Terminate the I/O process */
2392 		/* XXX Implement */
2393 		ccb->ccb_h.status = CAM_REQ_INVALID;
2394 		break;
2395 	case XPT_PATH_INQ:		/* Path routing inquiry */
2396 	{
2397 		struct ccb_pathinq *cpi = &ccb->cpi;
2398 
2399 		parent = device_get_parent(dev);
2400 		cpi->version_num = 1; /* XXX??? */
2401 		cpi->hba_inquiry = PI_SDTR_ABLE;
2402 		if (!(ch->quirks & MVS_Q_GENI)) {
2403 			cpi->hba_inquiry |= PI_SATAPM;
2404 			/* Gen-II is extremely slow with NCQ on PMP. */
2405 			if ((ch->quirks & MVS_Q_GENIIE) || ch->pm_present == 0)
2406 				cpi->hba_inquiry |= PI_TAG_ABLE;
2407 		}
2408 		cpi->target_sprt = 0;
2409 		cpi->hba_misc = PIM_SEQSCAN;
2410 		cpi->hba_eng_cnt = 0;
2411 		if (!(ch->quirks & MVS_Q_GENI))
2412 			cpi->max_target = 15;
2413 		else
2414 			cpi->max_target = 0;
2415 		cpi->max_lun = 0;
2416 		cpi->initiator_id = 0;
2417 		cpi->bus_id = cam_sim_bus(sim);
2418 		cpi->base_transfer_speed = 150000;
2419 		strlcpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
2420 		strlcpy(cpi->hba_vid, "Marvell", HBA_IDLEN);
2421 		strlcpy(cpi->dev_name, cam_sim_name(sim), DEV_IDLEN);
2422 		cpi->unit_number = cam_sim_unit(sim);
2423 		cpi->transport = XPORT_SATA;
2424 		cpi->transport_version = XPORT_VERSION_UNSPECIFIED;
2425 		cpi->protocol = PROTO_ATA;
2426 		cpi->protocol_version = PROTO_VERSION_UNSPECIFIED;
2427 		cpi->maxio = MAXPHYS;
2428 		if ((ch->quirks & MVS_Q_SOC) == 0) {
2429 			cpi->hba_vendor = pci_get_vendor(parent);
2430 			cpi->hba_device = pci_get_device(parent);
2431 			cpi->hba_subvendor = pci_get_subvendor(parent);
2432 			cpi->hba_subdevice = pci_get_subdevice(parent);
2433 		}
2434 		cpi->ccb_h.status = CAM_REQ_CMP;
2435 		break;
2436 	}
2437 	default:
2438 		ccb->ccb_h.status = CAM_REQ_INVALID;
2439 		break;
2440 	}
2441 	xpt_done(ccb);
2442 }
2443 
2444 static void
2445 mvspoll(struct cam_sim *sim)
2446 {
2447 	struct mvs_channel *ch = (struct mvs_channel *)cam_sim_softc(sim);
2448 	struct mvs_intr_arg arg;
2449 
2450 	arg.arg = ch->dev;
2451 	arg.cause = 2 | 4; /* XXX */
2452 	mvs_ch_intr(&arg);
2453 	if (ch->resetting != 0 &&
2454 	    (--ch->resetpolldiv <= 0 || !callout_pending(&ch->reset_timer))) {
2455 		ch->resetpolldiv = 1000;
2456 		mvs_reset_to(ch->dev);
2457 	}
2458 }
2459 
2460