xref: /freebsd/sys/dev/mvs/mvs.c (revision 2dd83b3f0507fc7bc64b908fb88f285a3b9663c8)
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_SG_ENTRIES, MVS_EPRD_MAX,
374 	    0, busdma_lock_mutex, &ch->mtx, &ch->dma.data_tag)) {
375 		goto error;
376 	}
377 	return;
378 
379 error:
380 	device_printf(dev, "WARNING - DMA initialization failed\n");
381 	mvs_dmafini(dev);
382 }
383 
384 static void
385 mvs_dmasetupc_cb(void *xsc, bus_dma_segment_t *segs, int nsegs, int error)
386 {
387 	struct mvs_dc_cb_args *dcba = (struct mvs_dc_cb_args *)xsc;
388 
389 	if (!(dcba->error = error))
390 		dcba->maddr = segs[0].ds_addr;
391 }
392 
393 static void
394 mvs_dmafini(device_t dev)
395 {
396 	struct mvs_channel *ch = device_get_softc(dev);
397 
398 	if (ch->dma.data_tag) {
399 		bus_dma_tag_destroy(ch->dma.data_tag);
400 		ch->dma.data_tag = NULL;
401 	}
402 	if (ch->dma.workrp_bus) {
403 		bus_dmamap_unload(ch->dma.workrp_tag, ch->dma.workrp_map);
404 		bus_dmamem_free(ch->dma.workrp_tag,
405 		    ch->dma.workrp, ch->dma.workrp_map);
406 		ch->dma.workrp_bus = 0;
407 		ch->dma.workrp = NULL;
408 	}
409 	if (ch->dma.workrp_tag) {
410 		bus_dma_tag_destroy(ch->dma.workrp_tag);
411 		ch->dma.workrp_tag = NULL;
412 	}
413 	if (ch->dma.workrq_bus) {
414 		bus_dmamap_unload(ch->dma.workrq_tag, ch->dma.workrq_map);
415 		bus_dmamem_free(ch->dma.workrq_tag,
416 		    ch->dma.workrq, ch->dma.workrq_map);
417 		ch->dma.workrq_bus = 0;
418 		ch->dma.workrq = NULL;
419 	}
420 	if (ch->dma.workrq_tag) {
421 		bus_dma_tag_destroy(ch->dma.workrq_tag);
422 		ch->dma.workrq_tag = NULL;
423 	}
424 }
425 
426 static void
427 mvs_slotsalloc(device_t dev)
428 {
429 	struct mvs_channel *ch = device_get_softc(dev);
430 	int i;
431 
432 	/* Alloc and setup command/dma slots */
433 	bzero(ch->slot, sizeof(ch->slot));
434 	for (i = 0; i < MVS_MAX_SLOTS; i++) {
435 		struct mvs_slot *slot = &ch->slot[i];
436 
437 		slot->dev = dev;
438 		slot->slot = i;
439 		slot->state = MVS_SLOT_EMPTY;
440 		slot->eprd_offset = MVS_EPRD_OFFSET + MVS_EPRD_SIZE * i;
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 static device_method_t mvsch_methods[] = {
580 	DEVMETHOD(device_probe,     mvs_ch_probe),
581 	DEVMETHOD(device_attach,    mvs_ch_attach),
582 	DEVMETHOD(device_detach,    mvs_ch_detach),
583 	DEVMETHOD(device_suspend,   mvs_ch_suspend),
584 	DEVMETHOD(device_resume,    mvs_ch_resume),
585 	{ 0, 0 }
586 };
587 static driver_t mvsch_driver = {
588         "mvsch",
589         mvsch_methods,
590         sizeof(struct mvs_channel)
591 };
592 DRIVER_MODULE(mvsch, mvs, mvsch_driver, 0, 0);
593 DRIVER_MODULE(mvsch, sata, mvsch_driver, 0, 0);
594 
595 static void
596 mvs_phy_check_events(device_t dev, u_int32_t serr)
597 {
598 	struct mvs_channel *ch = device_get_softc(dev);
599 
600 	if (ch->pm_level == 0) {
601 		u_int32_t status = ATA_INL(ch->r_mem, SATA_SS);
602 		union ccb *ccb;
603 
604 		if (bootverbose) {
605 			if (((status & SATA_SS_DET_MASK) == SATA_SS_DET_PHY_ONLINE) &&
606 			    ((status & SATA_SS_SPD_MASK) != SATA_SS_SPD_NO_SPEED) &&
607 			    ((status & SATA_SS_IPM_MASK) == SATA_SS_IPM_ACTIVE)) {
608 				device_printf(dev, "CONNECT requested\n");
609 			} else
610 				device_printf(dev, "DISCONNECT requested\n");
611 		}
612 		mvs_reset(dev);
613 		if ((ccb = xpt_alloc_ccb_nowait()) == NULL)
614 			return;
615 		if (xpt_create_path(&ccb->ccb_h.path, NULL,
616 		    cam_sim_path(ch->sim),
617 		    CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
618 			xpt_free_ccb(ccb);
619 			return;
620 		}
621 		xpt_rescan(ccb);
622 	}
623 }
624 
625 static void
626 mvs_notify_events(device_t dev)
627 {
628 	struct mvs_channel *ch = device_get_softc(dev);
629 	struct cam_path *dpath;
630 	uint32_t fis;
631 	int d;
632 
633 	/* Try to read PMP field from SDB FIS. Present only for Gen-IIe. */
634 	fis = ATA_INL(ch->r_mem, SATA_FISDW0);
635 	if ((fis & 0x80ff) == 0x80a1)
636 		d = (fis & 0x0f00) >> 8;
637 	else
638 		d = ch->pm_present ? 15 : 0;
639 	if (bootverbose)
640 		device_printf(dev, "SNTF %d\n", d);
641 	if (xpt_create_path(&dpath, NULL,
642 	    xpt_path_path_id(ch->path), d, 0) == CAM_REQ_CMP) {
643 		xpt_async(AC_SCSI_AEN, dpath, NULL);
644 		xpt_free_path(dpath);
645 	}
646 }
647 
648 static void
649 mvs_ch_intr_locked(void *data)
650 {
651 	struct mvs_intr_arg *arg = (struct mvs_intr_arg *)data;
652 	device_t dev = (device_t)arg->arg;
653 	struct mvs_channel *ch = device_get_softc(dev);
654 
655 	mtx_lock(&ch->mtx);
656 	mvs_ch_intr(data);
657 	mtx_unlock(&ch->mtx);
658 }
659 
660 static void
661 mvs_ch_pm(void *arg)
662 {
663 	device_t dev = (device_t)arg;
664 	struct mvs_channel *ch = device_get_softc(dev);
665 	uint32_t work;
666 
667 	if (ch->numrslots != 0)
668 		return;
669 	/* If we are idle - request power state transition. */
670 	work = ATA_INL(ch->r_mem, SATA_SC);
671 	work &= ~SATA_SC_SPM_MASK;
672 	if (ch->pm_level == 4)
673 		work |= SATA_SC_SPM_PARTIAL;
674 	else
675 		work |= SATA_SC_SPM_SLUMBER;
676 	ATA_OUTL(ch->r_mem, SATA_SC, work);
677 }
678 
679 static void
680 mvs_ch_pm_wake(device_t dev)
681 {
682 	struct mvs_channel *ch = device_get_softc(dev);
683 	uint32_t work;
684 	int timeout = 0;
685 
686 	work = ATA_INL(ch->r_mem, SATA_SS);
687 	if (work & SATA_SS_IPM_ACTIVE)
688 		return;
689 	/* If we are not in active state - request power state transition. */
690 	work = ATA_INL(ch->r_mem, SATA_SC);
691 	work &= ~SATA_SC_SPM_MASK;
692 	work |= SATA_SC_SPM_ACTIVE;
693 	ATA_OUTL(ch->r_mem, SATA_SC, work);
694 	/* Wait for transition to happen. */
695 	while ((ATA_INL(ch->r_mem, SATA_SS) & SATA_SS_IPM_ACTIVE) == 0 &&
696 	    timeout++ < 100) {
697 		DELAY(100);
698 	}
699 }
700 
701 static void
702 mvs_ch_intr(void *data)
703 {
704 	struct mvs_intr_arg *arg = (struct mvs_intr_arg *)data;
705 	device_t dev = (device_t)arg->arg;
706 	struct mvs_channel *ch = device_get_softc(dev);
707 	uint32_t iec, serr = 0, fisic = 0;
708 	enum mvs_err_type et;
709 	int i, ccs, port = -1, selfdis = 0;
710 	int edma = (ch->numtslots != 0 || ch->numdslots != 0);
711 
712 	/* New item in response queue. */
713 	if ((arg->cause & 2) && edma)
714 		mvs_crbq_intr(dev);
715 	/* Some error or special event. */
716 	if (arg->cause & 1) {
717 		iec = ATA_INL(ch->r_mem, EDMA_IEC);
718 		if (iec & EDMA_IE_SERRINT) {
719 			serr = ATA_INL(ch->r_mem, SATA_SE);
720 			ATA_OUTL(ch->r_mem, SATA_SE, serr);
721 		}
722 		/* EDMA self-disabled due to error. */
723 		if (iec & EDMA_IE_ESELFDIS)
724 			selfdis = 1;
725 		/* Transport interrupt. */
726 		if (iec & EDMA_IE_ETRANSINT) {
727 			/* For Gen-I this bit means self-disable. */
728 			if (ch->quirks & MVS_Q_GENI)
729 				selfdis = 1;
730 			/* For Gen-II this bit means SDB-N. */
731 			else if (ch->quirks & MVS_Q_GENII)
732 				fisic = SATA_FISC_FISWAIT4HOSTRDYEN_B1;
733 			else	/* For Gen-IIe - read FIS interrupt cause. */
734 				fisic = ATA_INL(ch->r_mem, SATA_FISIC);
735 		}
736 		if (selfdis)
737 			ch->curr_mode = MVS_EDMA_UNKNOWN;
738 		ATA_OUTL(ch->r_mem, EDMA_IEC, ~iec);
739 		/* Interface errors or Device error. */
740 		if (iec & (0xfc1e9000 | EDMA_IE_EDEVERR)) {
741 			port = -1;
742 			if (ch->numpslots != 0) {
743 				ccs = 0;
744 			} else {
745 				if (ch->quirks & MVS_Q_GENIIE)
746 					ccs = EDMA_S_EIOID(ATA_INL(ch->r_mem, EDMA_S));
747 				else
748 					ccs = EDMA_S_EDEVQUETAG(ATA_INL(ch->r_mem, EDMA_S));
749 				/* Check if error is one-PMP-port-specific, */
750 				if (ch->fbs_enabled) {
751 					/* Which ports were active. */
752 					for (i = 0; i < 16; i++) {
753 						if (ch->numrslotspd[i] == 0)
754 							continue;
755 						if (port == -1)
756 							port = i;
757 						else if (port != i) {
758 							port = -2;
759 							break;
760 						}
761 					}
762 					/* If several ports were active and EDMA still enabled -
763 					 * other ports are probably unaffected and may continue.
764 					 */
765 					if (port == -2 && !selfdis) {
766 						uint16_t p = ATA_INL(ch->r_mem, SATA_SATAITC) >> 16;
767 						port = ffs(p) - 1;
768 						if (port != (fls(p) - 1))
769 							port = -2;
770 					}
771 				}
772 			}
773 			mvs_requeue_frozen(dev);
774 			for (i = 0; i < MVS_MAX_SLOTS; i++) {
775 				/* XXX: reqests in loading state. */
776 				if (((ch->rslots >> i) & 1) == 0)
777 					continue;
778 				if (port >= 0 &&
779 				    ch->slot[i].ccb->ccb_h.target_id != port)
780 					continue;
781 				if (iec & EDMA_IE_EDEVERR) { /* Device error. */
782 				    if (port != -2) {
783 					if (ch->numtslots == 0) {
784 						/* Untagged operation. */
785 						if (i == ccs)
786 							et = MVS_ERR_TFE;
787 						else
788 							et = MVS_ERR_INNOCENT;
789 					} else {
790 						/* Tagged operation. */
791 						et = MVS_ERR_NCQ;
792 					}
793 				    } else {
794 					et = MVS_ERR_TFE;
795 					ch->fatalerr = 1;
796 				    }
797 				} else if (iec & 0xfc1e9000) {
798 					if (ch->numtslots == 0 &&
799 					    i != ccs && port != -2)
800 						et = MVS_ERR_INNOCENT;
801 					else
802 						et = MVS_ERR_SATA;
803 				} else
804 					et = MVS_ERR_INVALID;
805 				mvs_end_transaction(&ch->slot[i], et);
806 			}
807 		}
808 		/* Process SDB-N. */
809 		if (fisic & SATA_FISC_FISWAIT4HOSTRDYEN_B1)
810 			mvs_notify_events(dev);
811 		if (fisic)
812 			ATA_OUTL(ch->r_mem, SATA_FISIC, ~fisic);
813 		/* Process hot-plug. */
814 		if ((iec & (EDMA_IE_EDEVDIS | EDMA_IE_EDEVCON)) ||
815 		    (serr & SATA_SE_PHY_CHANGED))
816 			mvs_phy_check_events(dev, serr);
817 	}
818 	/* Legacy mode device interrupt. */
819 	if ((arg->cause & 2) && !edma)
820 		mvs_legacy_intr(dev, arg->cause & 4);
821 }
822 
823 static uint8_t
824 mvs_getstatus(device_t dev, int clear)
825 {
826 	struct mvs_channel *ch = device_get_softc(dev);
827 	uint8_t status = ATA_INB(ch->r_mem, clear ? ATA_STATUS : ATA_ALTSTAT);
828 
829 	if (ch->fake_busy) {
830 		if (status & (ATA_S_BUSY | ATA_S_DRQ | ATA_S_ERROR))
831 			ch->fake_busy = 0;
832 		else
833 			status |= ATA_S_BUSY;
834 	}
835 	return (status);
836 }
837 
838 static void
839 mvs_legacy_intr(device_t dev, int poll)
840 {
841 	struct mvs_channel *ch = device_get_softc(dev);
842 	struct mvs_slot *slot = &ch->slot[0]; /* PIO is always in slot 0. */
843 	union ccb *ccb = slot->ccb;
844 	enum mvs_err_type et = MVS_ERR_NONE;
845 	u_int length, resid, size;
846 	uint8_t buf[2];
847 	uint8_t status, ireason;
848 
849 	/* Clear interrupt and get status. */
850 	status = mvs_getstatus(dev, 1);
851 	if (slot->state < MVS_SLOT_RUNNING)
852 	    return;
853 	/* Wait a bit for late !BUSY status update. */
854 	if (status & ATA_S_BUSY) {
855 		if (poll)
856 			return;
857 		DELAY(100);
858 		if ((status = mvs_getstatus(dev, 1)) & ATA_S_BUSY) {
859 			DELAY(1000);
860 			if ((status = mvs_getstatus(dev, 1)) & ATA_S_BUSY)
861 				return;
862 		}
863 	}
864 	/* If we got an error, we are done. */
865 	if (status & ATA_S_ERROR) {
866 		et = MVS_ERR_TFE;
867 		goto end_finished;
868 	}
869 	if (ccb->ccb_h.func_code == XPT_ATA_IO) { /* ATA PIO */
870 		ccb->ataio.res.status = status;
871 		/* Are we moving data? */
872 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
873 		    /* If data read command - get them. */
874 		    if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
875 			if (mvs_wait(dev, ATA_S_DRQ, ATA_S_BUSY, 1000) < 0) {
876 			    device_printf(dev, "timeout waiting for read DRQ\n");
877 			    et = MVS_ERR_TIMEOUT;
878 			    xpt_freeze_simq(ch->sim, 1);
879 			    ch->toslots |= (1 << slot->slot);
880 			    goto end_finished;
881 			}
882 			ATA_INSW_STRM(ch->r_mem, ATA_DATA,
883 			   (uint16_t *)(ccb->ataio.data_ptr + ch->donecount),
884 			   ch->transfersize / 2);
885 		    }
886 		    /* Update how far we've gotten. */
887 		    ch->donecount += ch->transfersize;
888 		    /* Do we need more? */
889 		    if (ccb->ataio.dxfer_len > ch->donecount) {
890 			/* Set this transfer size according to HW capabilities */
891 			ch->transfersize = min(ccb->ataio.dxfer_len - ch->donecount,
892 			    ch->transfersize);
893 			/* If data write command - put them */
894 			if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_OUT) {
895 				if (mvs_wait(dev, ATA_S_DRQ, ATA_S_BUSY, 1000) < 0) {
896 				    device_printf(dev,
897 					"timeout waiting for write DRQ\n");
898 				    et = MVS_ERR_TIMEOUT;
899 				    xpt_freeze_simq(ch->sim, 1);
900 				    ch->toslots |= (1 << slot->slot);
901 				    goto end_finished;
902 				}
903 				ATA_OUTSW_STRM(ch->r_mem, ATA_DATA,
904 				   (uint16_t *)(ccb->ataio.data_ptr + ch->donecount),
905 				   ch->transfersize / 2);
906 				return;
907 			}
908 			/* If data read command, return & wait for interrupt */
909 			if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN)
910 				return;
911 		    }
912 		}
913 	} else if (ch->basic_dma) {	/* ATAPI DMA */
914 		if (status & ATA_S_DWF)
915 			et = MVS_ERR_TFE;
916 		else if (ATA_INL(ch->r_mem, DMA_S) & DMA_S_ERR)
917 			et = MVS_ERR_TFE;
918 		/* Stop basic DMA. */
919 		ATA_OUTL(ch->r_mem, DMA_C, 0);
920 		goto end_finished;
921 	} else {			/* ATAPI PIO */
922 		length = ATA_INB(ch->r_mem,ATA_CYL_LSB) |
923 		    (ATA_INB(ch->r_mem,ATA_CYL_MSB) << 8);
924 		size = min(ch->transfersize, length);
925 		ireason = ATA_INB(ch->r_mem,ATA_IREASON);
926 		switch ((ireason & (ATA_I_CMD | ATA_I_IN)) |
927 			(status & ATA_S_DRQ)) {
928 		case ATAPI_P_CMDOUT:
929 		    device_printf(dev, "ATAPI CMDOUT\n");
930 		    /* Return wait for interrupt */
931 		    return;
932 
933 		case ATAPI_P_WRITE:
934 		    if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
935 			device_printf(dev, "trying to write on read buffer\n");
936 			et = MVS_ERR_TFE;
937 			goto end_finished;
938 			break;
939 		    }
940 		    ATA_OUTSW_STRM(ch->r_mem, ATA_DATA,
941 			(uint16_t *)(ccb->csio.data_ptr + ch->donecount),
942 			(size + 1) / 2);
943 		    for (resid = ch->transfersize + (size & 1);
944 			resid < length; resid += sizeof(int16_t))
945 			    ATA_OUTW(ch->r_mem, ATA_DATA, 0);
946 		    ch->donecount += length;
947 		    /* Set next transfer size according to HW capabilities */
948 		    ch->transfersize = min(ccb->csio.dxfer_len - ch->donecount,
949 			    ch->curr[ccb->ccb_h.target_id].bytecount);
950 		    /* Return wait for interrupt */
951 		    return;
952 
953 		case ATAPI_P_READ:
954 		    if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_OUT) {
955 			device_printf(dev, "trying to read on write buffer\n");
956 			et = MVS_ERR_TFE;
957 			goto end_finished;
958 		    }
959 		    if (size >= 2) {
960 			ATA_INSW_STRM(ch->r_mem, ATA_DATA,
961 			    (uint16_t *)(ccb->csio.data_ptr + ch->donecount),
962 			    size / 2);
963 		    }
964 		    if (size & 1) {
965 			ATA_INSW_STRM(ch->r_mem, ATA_DATA, (void*)buf, 1);
966 			((uint8_t *)ccb->csio.data_ptr + ch->donecount +
967 			    (size & ~1))[0] = buf[0];
968 		    }
969 		    for (resid = ch->transfersize + (size & 1);
970 			resid < length; resid += sizeof(int16_t))
971 			    ATA_INW(ch->r_mem, ATA_DATA);
972 		    ch->donecount += length;
973 		    /* Set next transfer size according to HW capabilities */
974 		    ch->transfersize = min(ccb->csio.dxfer_len - ch->donecount,
975 			    ch->curr[ccb->ccb_h.target_id].bytecount);
976 		    /* Return wait for interrupt */
977 		    return;
978 
979 		case ATAPI_P_DONEDRQ:
980 		    device_printf(dev,
981 			  "WARNING - DONEDRQ non conformant device\n");
982 		    if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
983 			ATA_INSW_STRM(ch->r_mem, ATA_DATA,
984 			    (uint16_t *)(ccb->csio.data_ptr + ch->donecount),
985 			    length / 2);
986 			ch->donecount += length;
987 		    }
988 		    else if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_OUT) {
989 			ATA_OUTSW_STRM(ch->r_mem, ATA_DATA,
990 			    (uint16_t *)(ccb->csio.data_ptr + ch->donecount),
991 			    length / 2);
992 			ch->donecount += length;
993 		    }
994 		    else
995 			et = MVS_ERR_TFE;
996 		    /* FALLTHROUGH */
997 
998 		case ATAPI_P_ABORT:
999 		case ATAPI_P_DONE:
1000 		    if (status & (ATA_S_ERROR | ATA_S_DWF))
1001 			et = MVS_ERR_TFE;
1002 		    goto end_finished;
1003 
1004 		default:
1005 		    device_printf(dev, "unknown transfer phase"
1006 			" (status %02x, ireason %02x)\n",
1007 			status, ireason);
1008 		    et = MVS_ERR_TFE;
1009 		}
1010 	}
1011 
1012 end_finished:
1013 	mvs_end_transaction(slot, et);
1014 }
1015 
1016 static void
1017 mvs_crbq_intr(device_t dev)
1018 {
1019 	struct mvs_channel *ch = device_get_softc(dev);
1020 	struct mvs_crpb *crpb;
1021 	union ccb *ccb;
1022 	int in_idx, fin_idx, cin_idx, slot;
1023 	uint32_t val;
1024 	uint16_t flags;
1025 
1026 	val = ATA_INL(ch->r_mem, EDMA_RESQIP);
1027 	if (val == 0)
1028 		val = ATA_INL(ch->r_mem, EDMA_RESQIP);
1029 	in_idx = (val & EDMA_RESQP_ERPQP_MASK) >>
1030 	    EDMA_RESQP_ERPQP_SHIFT;
1031 	bus_dmamap_sync(ch->dma.workrp_tag, ch->dma.workrp_map,
1032 	    BUS_DMASYNC_POSTREAD);
1033 	fin_idx = cin_idx = ch->in_idx;
1034 	ch->in_idx = in_idx;
1035 	while (in_idx != cin_idx) {
1036 		crpb = (struct mvs_crpb *)
1037 		    (ch->dma.workrp + MVS_CRPB_OFFSET +
1038 		    (MVS_CRPB_SIZE * cin_idx));
1039 		slot = le16toh(crpb->id) & MVS_CRPB_TAG_MASK;
1040 		flags = le16toh(crpb->rspflg);
1041 		/*
1042 		 * Handle only successful completions here.
1043 		 * Errors will be handled by main intr handler.
1044 		 */
1045 #if defined(__i386__) || defined(__amd64__)
1046 		if (crpb->id == 0xffff && crpb->rspflg == 0xffff) {
1047 			device_printf(dev, "Unfilled CRPB "
1048 			    "%d (%d->%d) tag %d flags %04x rs %08x\n",
1049 			    cin_idx, fin_idx, in_idx, slot, flags, ch->rslots);
1050 		} else
1051 #endif
1052 		if (ch->numtslots != 0 ||
1053 		    (flags & EDMA_IE_EDEVERR) == 0) {
1054 #if defined(__i386__) || defined(__amd64__)
1055 			crpb->id = 0xffff;
1056 			crpb->rspflg = 0xffff;
1057 #endif
1058 			if (ch->slot[slot].state >= MVS_SLOT_RUNNING) {
1059 				ccb = ch->slot[slot].ccb;
1060 				ccb->ataio.res.status =
1061 				    (flags & MVS_CRPB_ATASTS_MASK) >>
1062 				    MVS_CRPB_ATASTS_SHIFT;
1063 				mvs_end_transaction(&ch->slot[slot], MVS_ERR_NONE);
1064 			} else {
1065 				device_printf(dev, "Unused tag in CRPB "
1066 				    "%d (%d->%d) tag %d flags %04x rs %08x\n",
1067 				    cin_idx, fin_idx, in_idx, slot, flags,
1068 				    ch->rslots);
1069 			}
1070 		} else {
1071 			device_printf(dev,
1072 			    "CRPB with error %d tag %d flags %04x\n",
1073 			    cin_idx, slot, flags);
1074 		}
1075 		cin_idx = (cin_idx + 1) & (MVS_MAX_SLOTS - 1);
1076 	}
1077 	bus_dmamap_sync(ch->dma.workrp_tag, ch->dma.workrp_map,
1078 	    BUS_DMASYNC_PREREAD);
1079 	if (cin_idx == ch->in_idx) {
1080 		ATA_OUTL(ch->r_mem, EDMA_RESQOP,
1081 		    ch->dma.workrp_bus | (cin_idx << EDMA_RESQP_ERPQP_SHIFT));
1082 	}
1083 }
1084 
1085 /* Must be called with channel locked. */
1086 static int
1087 mvs_check_collision(device_t dev, union ccb *ccb)
1088 {
1089 	struct mvs_channel *ch = device_get_softc(dev);
1090 
1091 	if (ccb->ccb_h.func_code == XPT_ATA_IO) {
1092 		/* NCQ DMA */
1093 		if (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA) {
1094 			/* Can't mix NCQ and non-NCQ DMA commands. */
1095 			if (ch->numdslots != 0)
1096 				return (1);
1097 			/* Can't mix NCQ and PIO commands. */
1098 			if (ch->numpslots != 0)
1099 				return (1);
1100 			/* If we have no FBS */
1101 			if (!ch->fbs_enabled) {
1102 				/* Tagged command while tagged to other target is active. */
1103 				if (ch->numtslots != 0 &&
1104 				    ch->taggedtarget != ccb->ccb_h.target_id)
1105 					return (1);
1106 			}
1107 		/* Non-NCQ DMA */
1108 		} else if (ccb->ataio.cmd.flags & CAM_ATAIO_DMA) {
1109 			/* Can't mix non-NCQ DMA and NCQ commands. */
1110 			if (ch->numtslots != 0)
1111 				return (1);
1112 			/* Can't mix non-NCQ DMA and PIO commands. */
1113 			if (ch->numpslots != 0)
1114 				return (1);
1115 		/* PIO */
1116 		} else {
1117 			/* Can't mix PIO with anything. */
1118 			if (ch->numrslots != 0)
1119 				return (1);
1120 		}
1121 		if (ccb->ataio.cmd.flags & (CAM_ATAIO_CONTROL | CAM_ATAIO_NEEDRESULT)) {
1122 			/* Atomic command while anything active. */
1123 			if (ch->numrslots != 0)
1124 				return (1);
1125 		}
1126 	} else { /* ATAPI */
1127 		/* ATAPI goes without EDMA, so can't mix it with anything. */
1128 		if (ch->numrslots != 0)
1129 			return (1);
1130 	}
1131 	/* We have some atomic command running. */
1132 	if (ch->aslots != 0)
1133 		return (1);
1134 	return (0);
1135 }
1136 
1137 static void
1138 mvs_tfd_read(device_t dev, union ccb *ccb)
1139 {
1140 	struct mvs_channel *ch = device_get_softc(dev);
1141 	struct ata_res *res = &ccb->ataio.res;
1142 
1143 	res->status = ATA_INB(ch->r_mem, ATA_ALTSTAT);
1144 	res->error =  ATA_INB(ch->r_mem, ATA_ERROR);
1145 	res->device = ATA_INB(ch->r_mem, ATA_DRIVE);
1146 	ATA_OUTB(ch->r_mem, ATA_CONTROL, ATA_A_HOB);
1147 	res->sector_count_exp = ATA_INB(ch->r_mem, ATA_COUNT);
1148 	res->lba_low_exp = ATA_INB(ch->r_mem, ATA_SECTOR);
1149 	res->lba_mid_exp = ATA_INB(ch->r_mem, ATA_CYL_LSB);
1150 	res->lba_high_exp = ATA_INB(ch->r_mem, ATA_CYL_MSB);
1151 	ATA_OUTB(ch->r_mem, ATA_CONTROL, 0);
1152 	res->sector_count = ATA_INB(ch->r_mem, ATA_COUNT);
1153 	res->lba_low = ATA_INB(ch->r_mem, ATA_SECTOR);
1154 	res->lba_mid = ATA_INB(ch->r_mem, ATA_CYL_LSB);
1155 	res->lba_high = ATA_INB(ch->r_mem, ATA_CYL_MSB);
1156 }
1157 
1158 static void
1159 mvs_tfd_write(device_t dev, union ccb *ccb)
1160 {
1161 	struct mvs_channel *ch = device_get_softc(dev);
1162 	struct ata_cmd *cmd = &ccb->ataio.cmd;
1163 
1164 	ATA_OUTB(ch->r_mem, ATA_DRIVE, cmd->device);
1165 	ATA_OUTB(ch->r_mem, ATA_CONTROL, cmd->control);
1166 	ATA_OUTB(ch->r_mem, ATA_FEATURE, cmd->features_exp);
1167 	ATA_OUTB(ch->r_mem, ATA_FEATURE, cmd->features);
1168 	ATA_OUTB(ch->r_mem, ATA_COUNT, cmd->sector_count_exp);
1169 	ATA_OUTB(ch->r_mem, ATA_COUNT, cmd->sector_count);
1170 	ATA_OUTB(ch->r_mem, ATA_SECTOR, cmd->lba_low_exp);
1171 	ATA_OUTB(ch->r_mem, ATA_SECTOR, cmd->lba_low);
1172 	ATA_OUTB(ch->r_mem, ATA_CYL_LSB, cmd->lba_mid_exp);
1173 	ATA_OUTB(ch->r_mem, ATA_CYL_LSB, cmd->lba_mid);
1174 	ATA_OUTB(ch->r_mem, ATA_CYL_MSB, cmd->lba_high_exp);
1175 	ATA_OUTB(ch->r_mem, ATA_CYL_MSB, cmd->lba_high);
1176 	ATA_OUTB(ch->r_mem, ATA_COMMAND, cmd->command);
1177 }
1178 
1179 /* Must be called with channel locked. */
1180 static void
1181 mvs_begin_transaction(device_t dev, union ccb *ccb)
1182 {
1183 	struct mvs_channel *ch = device_get_softc(dev);
1184 	struct mvs_slot *slot;
1185 	int slotn, tag;
1186 
1187 	if (ch->pm_level > 0)
1188 		mvs_ch_pm_wake(dev);
1189 	/* Softreset is a special case. */
1190 	if (ccb->ccb_h.func_code == XPT_ATA_IO &&
1191 	    (ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL)) {
1192 		mvs_softreset(dev, ccb);
1193 		return;
1194 	}
1195 	/* Choose empty slot. */
1196 	slotn = ffs(~ch->oslots) - 1;
1197 	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1198 	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA)) {
1199 		if (ch->quirks & MVS_Q_GENIIE)
1200 			tag = ffs(~ch->otagspd[ccb->ccb_h.target_id]) - 1;
1201 		else
1202 			tag = slotn;
1203 	} else
1204 		tag = 0;
1205 	/* Occupy chosen slot. */
1206 	slot = &ch->slot[slotn];
1207 	slot->ccb = ccb;
1208 	slot->tag = tag;
1209 	/* Stop PM timer. */
1210 	if (ch->numrslots == 0 && ch->pm_level > 3)
1211 		callout_stop(&ch->pm_timer);
1212 	/* Update channel stats. */
1213 	ch->oslots |= (1 << slot->slot);
1214 	ch->numrslots++;
1215 	ch->numrslotspd[ccb->ccb_h.target_id]++;
1216 	if (ccb->ccb_h.func_code == XPT_ATA_IO) {
1217 		if (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA) {
1218 			ch->otagspd[ccb->ccb_h.target_id] |= (1 << slot->tag);
1219 			ch->numtslots++;
1220 			ch->numtslotspd[ccb->ccb_h.target_id]++;
1221 			ch->taggedtarget = ccb->ccb_h.target_id;
1222 			mvs_set_edma_mode(dev, MVS_EDMA_NCQ);
1223 		} else if (ccb->ataio.cmd.flags & CAM_ATAIO_DMA) {
1224 			ch->numdslots++;
1225 			mvs_set_edma_mode(dev, MVS_EDMA_ON);
1226 		} else {
1227 			ch->numpslots++;
1228 			mvs_set_edma_mode(dev, MVS_EDMA_OFF);
1229 		}
1230 		if (ccb->ataio.cmd.flags &
1231 		    (CAM_ATAIO_CONTROL | CAM_ATAIO_NEEDRESULT)) {
1232 			ch->aslots |= (1 << slot->slot);
1233 		}
1234 	} else {
1235 		uint8_t *cdb = (ccb->ccb_h.flags & CAM_CDB_POINTER) ?
1236 		    ccb->csio.cdb_io.cdb_ptr : ccb->csio.cdb_io.cdb_bytes;
1237 		ch->numpslots++;
1238 		/* Use ATAPI DMA only for commands without under-/overruns. */
1239 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE &&
1240 		    ch->curr[ccb->ccb_h.target_id].mode >= ATA_DMA &&
1241 		    (ch->quirks & MVS_Q_SOC) == 0 &&
1242 		    (cdb[0] == 0x08 ||
1243 		     cdb[0] == 0x0a ||
1244 		     cdb[0] == 0x28 ||
1245 		     cdb[0] == 0x2a ||
1246 		     cdb[0] == 0x88 ||
1247 		     cdb[0] == 0x8a ||
1248 		     cdb[0] == 0xa8 ||
1249 		     cdb[0] == 0xaa ||
1250 		     cdb[0] == 0xbe)) {
1251 			ch->basic_dma = 1;
1252 		}
1253 		mvs_set_edma_mode(dev, MVS_EDMA_OFF);
1254 	}
1255 	if (ch->numpslots == 0 || ch->basic_dma) {
1256 		slot->state = MVS_SLOT_LOADING;
1257 		bus_dmamap_load_ccb(ch->dma.data_tag, slot->dma.data_map,
1258 		    ccb, mvs_dmasetprd, slot, 0);
1259 	} else
1260 		mvs_legacy_execute_transaction(slot);
1261 }
1262 
1263 /* Locked by busdma engine. */
1264 static void
1265 mvs_dmasetprd(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
1266 {
1267 	struct mvs_slot *slot = arg;
1268 	struct mvs_channel *ch = device_get_softc(slot->dev);
1269 	struct mvs_eprd *eprd;
1270 	int i;
1271 
1272 	if (error) {
1273 		device_printf(slot->dev, "DMA load error\n");
1274 		mvs_end_transaction(slot, MVS_ERR_INVALID);
1275 		return;
1276 	}
1277 	KASSERT(nsegs <= MVS_SG_ENTRIES, ("too many DMA segment entries\n"));
1278 	/* If there is only one segment - no need to use S/G table on Gen-IIe. */
1279 	if (nsegs == 1 && ch->basic_dma == 0 && (ch->quirks & MVS_Q_GENIIE)) {
1280 		slot->dma.addr = segs[0].ds_addr;
1281 		slot->dma.len = segs[0].ds_len;
1282 	} else {
1283 		slot->dma.addr = 0;
1284 		/* Get a piece of the workspace for this EPRD */
1285 		eprd = (struct mvs_eprd *)(ch->dma.workrq + slot->eprd_offset);
1286 		/* Fill S/G table */
1287 		for (i = 0; i < nsegs; i++) {
1288 			eprd[i].prdbal = htole32(segs[i].ds_addr);
1289 			eprd[i].bytecount = htole32(segs[i].ds_len & MVS_EPRD_MASK);
1290 			eprd[i].prdbah = htole32((segs[i].ds_addr >> 16) >> 16);
1291 		}
1292 		eprd[i - 1].bytecount |= htole32(MVS_EPRD_EOF);
1293 	}
1294 	bus_dmamap_sync(ch->dma.data_tag, slot->dma.data_map,
1295 	    ((slot->ccb->ccb_h.flags & CAM_DIR_IN) ?
1296 	    BUS_DMASYNC_PREREAD : BUS_DMASYNC_PREWRITE));
1297 	if (ch->basic_dma)
1298 		mvs_legacy_execute_transaction(slot);
1299 	else
1300 		mvs_execute_transaction(slot);
1301 }
1302 
1303 static void
1304 mvs_legacy_execute_transaction(struct mvs_slot *slot)
1305 {
1306 	device_t dev = slot->dev;
1307 	struct mvs_channel *ch = device_get_softc(dev);
1308 	bus_addr_t eprd;
1309 	union ccb *ccb = slot->ccb;
1310 	int port = ccb->ccb_h.target_id & 0x0f;
1311 	int timeout;
1312 
1313 	slot->state = MVS_SLOT_RUNNING;
1314 	ch->rslots |= (1 << slot->slot);
1315 	ATA_OUTB(ch->r_mem, SATA_SATAICTL, port << SATA_SATAICTL_PMPTX_SHIFT);
1316 	if (ccb->ccb_h.func_code == XPT_ATA_IO) {
1317 		mvs_tfd_write(dev, ccb);
1318 		/* Device reset doesn't interrupt. */
1319 		if (ccb->ataio.cmd.command == ATA_DEVICE_RESET) {
1320 			int timeout = 1000000;
1321 			do {
1322 			    DELAY(10);
1323 			    ccb->ataio.res.status = ATA_INB(ch->r_mem, ATA_STATUS);
1324 			} while (ccb->ataio.res.status & ATA_S_BUSY && timeout--);
1325 			mvs_legacy_intr(dev, 1);
1326 			return;
1327 		}
1328 		ch->donecount = 0;
1329 		if (ccb->ataio.cmd.command == ATA_READ_MUL ||
1330 		    ccb->ataio.cmd.command == ATA_READ_MUL48 ||
1331 		    ccb->ataio.cmd.command == ATA_WRITE_MUL ||
1332 		    ccb->ataio.cmd.command == ATA_WRITE_MUL48) {
1333 			ch->transfersize = min(ccb->ataio.dxfer_len,
1334 			    ch->curr[port].bytecount);
1335 		} else
1336 			ch->transfersize = min(ccb->ataio.dxfer_len, 512);
1337 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE)
1338 			ch->fake_busy = 1;
1339 		/* If data write command - output the data */
1340 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_OUT) {
1341 			if (mvs_wait(dev, ATA_S_DRQ, ATA_S_BUSY, 1000) < 0) {
1342 				device_printf(dev,
1343 				    "timeout waiting for write DRQ\n");
1344 				xpt_freeze_simq(ch->sim, 1);
1345 				ch->toslots |= (1 << slot->slot);
1346 				mvs_end_transaction(slot, MVS_ERR_TIMEOUT);
1347 				return;
1348 			}
1349 			ATA_OUTSW_STRM(ch->r_mem, ATA_DATA,
1350 			   (uint16_t *)(ccb->ataio.data_ptr + ch->donecount),
1351 			   ch->transfersize / 2);
1352 		}
1353 	} else {
1354 		ch->donecount = 0;
1355 		ch->transfersize = min(ccb->csio.dxfer_len,
1356 		    ch->curr[port].bytecount);
1357 		/* Write ATA PACKET command. */
1358 		if (ch->basic_dma) {
1359 			ATA_OUTB(ch->r_mem, ATA_FEATURE, ATA_F_DMA);
1360 			ATA_OUTB(ch->r_mem, ATA_CYL_LSB, 0);
1361 		    	ATA_OUTB(ch->r_mem, ATA_CYL_MSB, 0);
1362 		} else {
1363 			ATA_OUTB(ch->r_mem, ATA_FEATURE, 0);
1364 			ATA_OUTB(ch->r_mem, ATA_CYL_LSB, ch->transfersize);
1365 		    	ATA_OUTB(ch->r_mem, ATA_CYL_MSB, ch->transfersize >> 8);
1366 		}
1367 		ATA_OUTB(ch->r_mem, ATA_COMMAND, ATA_PACKET_CMD);
1368 		ch->fake_busy = 1;
1369 		/* Wait for ready to write ATAPI command block */
1370 		if (mvs_wait(dev, 0, ATA_S_BUSY, 1000) < 0) {
1371 			device_printf(dev, "timeout waiting for ATAPI !BUSY\n");
1372 			xpt_freeze_simq(ch->sim, 1);
1373 			ch->toslots |= (1 << slot->slot);
1374 			mvs_end_transaction(slot, MVS_ERR_TIMEOUT);
1375 			return;
1376 		}
1377 		timeout = 5000;
1378 		while (timeout--) {
1379 		    int reason = ATA_INB(ch->r_mem, ATA_IREASON);
1380 		    int status = ATA_INB(ch->r_mem, ATA_STATUS);
1381 
1382 		    if (((reason & (ATA_I_CMD | ATA_I_IN)) |
1383 			 (status & (ATA_S_DRQ | ATA_S_BUSY))) == ATAPI_P_CMDOUT)
1384 			break;
1385 		    DELAY(20);
1386 		}
1387 		if (timeout <= 0) {
1388 			device_printf(dev,
1389 			    "timeout waiting for ATAPI command ready\n");
1390 			xpt_freeze_simq(ch->sim, 1);
1391 			ch->toslots |= (1 << slot->slot);
1392 			mvs_end_transaction(slot, MVS_ERR_TIMEOUT);
1393 			return;
1394 		}
1395 		/* Write ATAPI command. */
1396 		ATA_OUTSW_STRM(ch->r_mem, ATA_DATA,
1397 		   (uint16_t *)((ccb->ccb_h.flags & CAM_CDB_POINTER) ?
1398 		    ccb->csio.cdb_io.cdb_ptr : ccb->csio.cdb_io.cdb_bytes),
1399 		   ch->curr[port].atapi / 2);
1400 		DELAY(10);
1401 		if (ch->basic_dma) {
1402 			/* Start basic DMA. */
1403 			eprd = ch->dma.workrq_bus + slot->eprd_offset;
1404 			ATA_OUTL(ch->r_mem, DMA_DTLBA, eprd);
1405 			ATA_OUTL(ch->r_mem, DMA_DTHBA, (eprd >> 16) >> 16);
1406 			ATA_OUTL(ch->r_mem, DMA_C, DMA_C_START |
1407 			    (((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) ?
1408 			    DMA_C_READ : 0));
1409 		}
1410 	}
1411 	/* Start command execution timeout */
1412 	callout_reset_sbt(&slot->timeout, SBT_1MS * ccb->ccb_h.timeout, 0,
1413 	    mvs_timeout, slot, 0);
1414 }
1415 
1416 /* Must be called with channel locked. */
1417 static void
1418 mvs_execute_transaction(struct mvs_slot *slot)
1419 {
1420 	device_t dev = slot->dev;
1421 	struct mvs_channel *ch = device_get_softc(dev);
1422 	bus_addr_t eprd;
1423 	struct mvs_crqb *crqb;
1424 	struct mvs_crqb_gen2e *crqb2e;
1425 	union ccb *ccb = slot->ccb;
1426 	int port = ccb->ccb_h.target_id & 0x0f;
1427 	int i;
1428 
1429 	/* Get address of the prepared EPRD */
1430 	eprd = ch->dma.workrq_bus + slot->eprd_offset;
1431 	/* Prepare CRQB. Gen IIe uses different CRQB format. */
1432 	if (ch->quirks & MVS_Q_GENIIE) {
1433 		crqb2e = (struct mvs_crqb_gen2e *)
1434 		    (ch->dma.workrq + MVS_CRQB_OFFSET + (MVS_CRQB_SIZE * ch->out_idx));
1435 		crqb2e->ctrlflg = htole32(
1436 		    ((ccb->ccb_h.flags & CAM_DIR_IN) ? MVS_CRQB2E_READ : 0) |
1437 		    (slot->tag << MVS_CRQB2E_DTAG_SHIFT) |
1438 		    (port << MVS_CRQB2E_PMP_SHIFT) |
1439 		    (slot->slot << MVS_CRQB2E_HTAG_SHIFT));
1440 		/* If there is only one segment - no need to use S/G table. */
1441 		if (slot->dma.addr != 0) {
1442 			eprd = slot->dma.addr;
1443 			crqb2e->ctrlflg |= htole32(MVS_CRQB2E_CPRD);
1444 			crqb2e->drbc = slot->dma.len;
1445 		}
1446 		crqb2e->cprdbl = htole32(eprd);
1447 		crqb2e->cprdbh = htole32((eprd >> 16) >> 16);
1448 		crqb2e->cmd[0] = 0;
1449 		crqb2e->cmd[1] = 0;
1450 		crqb2e->cmd[2] = ccb->ataio.cmd.command;
1451 		crqb2e->cmd[3] = ccb->ataio.cmd.features;
1452 		crqb2e->cmd[4] = ccb->ataio.cmd.lba_low;
1453 		crqb2e->cmd[5] = ccb->ataio.cmd.lba_mid;
1454 		crqb2e->cmd[6] = ccb->ataio.cmd.lba_high;
1455 		crqb2e->cmd[7] = ccb->ataio.cmd.device;
1456 		crqb2e->cmd[8] = ccb->ataio.cmd.lba_low_exp;
1457 		crqb2e->cmd[9] = ccb->ataio.cmd.lba_mid_exp;
1458 		crqb2e->cmd[10] = ccb->ataio.cmd.lba_high_exp;
1459 		crqb2e->cmd[11] = ccb->ataio.cmd.features_exp;
1460 		if (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA) {
1461 			crqb2e->cmd[12] = slot->tag << 3;
1462 			crqb2e->cmd[13] = 0;
1463 		} else {
1464 			crqb2e->cmd[12] = ccb->ataio.cmd.sector_count;
1465 			crqb2e->cmd[13] = ccb->ataio.cmd.sector_count_exp;
1466 		}
1467 		crqb2e->cmd[14] = 0;
1468 		crqb2e->cmd[15] = 0;
1469 	} else {
1470 		crqb = (struct mvs_crqb *)
1471 		    (ch->dma.workrq + MVS_CRQB_OFFSET + (MVS_CRQB_SIZE * ch->out_idx));
1472 		crqb->cprdbl = htole32(eprd);
1473 		crqb->cprdbh = htole32((eprd >> 16) >> 16);
1474 		crqb->ctrlflg = htole16(
1475 		    ((ccb->ccb_h.flags & CAM_DIR_IN) ? MVS_CRQB_READ : 0) |
1476 		    (slot->slot << MVS_CRQB_TAG_SHIFT) |
1477 		    (port << MVS_CRQB_PMP_SHIFT));
1478 		i = 0;
1479 		/*
1480 		 * Controller can handle only 11 of 12 ATA registers,
1481 		 * so we have to choose which one to skip.
1482 		 */
1483 		if (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA) {
1484 			crqb->cmd[i++] = ccb->ataio.cmd.features_exp;
1485 			crqb->cmd[i++] = 0x11;
1486 		}
1487 		crqb->cmd[i++] = ccb->ataio.cmd.features;
1488 		crqb->cmd[i++] = 0x11;
1489 		if (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA) {
1490 			crqb->cmd[i++] = (slot->tag << 3) |
1491 			    (ccb->ataio.cmd.sector_count & 0x07);
1492 			crqb->cmd[i++] = 0x12;
1493 		} else {
1494 			crqb->cmd[i++] = ccb->ataio.cmd.sector_count_exp;
1495 			crqb->cmd[i++] = 0x12;
1496 			crqb->cmd[i++] = ccb->ataio.cmd.sector_count;
1497 			crqb->cmd[i++] = 0x12;
1498 		}
1499 		crqb->cmd[i++] = ccb->ataio.cmd.lba_low_exp;
1500 		crqb->cmd[i++] = 0x13;
1501 		crqb->cmd[i++] = ccb->ataio.cmd.lba_low;
1502 		crqb->cmd[i++] = 0x13;
1503 		crqb->cmd[i++] = ccb->ataio.cmd.lba_mid_exp;
1504 		crqb->cmd[i++] = 0x14;
1505 		crqb->cmd[i++] = ccb->ataio.cmd.lba_mid;
1506 		crqb->cmd[i++] = 0x14;
1507 		crqb->cmd[i++] = ccb->ataio.cmd.lba_high_exp;
1508 		crqb->cmd[i++] = 0x15;
1509 		crqb->cmd[i++] = ccb->ataio.cmd.lba_high;
1510 		crqb->cmd[i++] = 0x15;
1511 		crqb->cmd[i++] = ccb->ataio.cmd.device;
1512 		crqb->cmd[i++] = 0x16;
1513 		crqb->cmd[i++] = ccb->ataio.cmd.command;
1514 		crqb->cmd[i++] = 0x97;
1515 	}
1516 	bus_dmamap_sync(ch->dma.workrq_tag, ch->dma.workrq_map,
1517 	    BUS_DMASYNC_PREWRITE);
1518 	bus_dmamap_sync(ch->dma.workrp_tag, ch->dma.workrp_map,
1519 	    BUS_DMASYNC_PREREAD);
1520 	slot->state = MVS_SLOT_RUNNING;
1521 	ch->rslots |= (1 << slot->slot);
1522 	/* Issue command to the controller. */
1523 	ch->out_idx = (ch->out_idx + 1) & (MVS_MAX_SLOTS - 1);
1524 	ATA_OUTL(ch->r_mem, EDMA_REQQIP,
1525 	    ch->dma.workrq_bus + MVS_CRQB_OFFSET + (MVS_CRQB_SIZE * ch->out_idx));
1526 	/* Start command execution timeout */
1527 	callout_reset_sbt(&slot->timeout, SBT_1MS * ccb->ccb_h.timeout, 0,
1528 	    mvs_timeout, slot, 0);
1529 	return;
1530 }
1531 
1532 /* Must be called with channel locked. */
1533 static void
1534 mvs_process_timeout(device_t dev)
1535 {
1536 	struct mvs_channel *ch = device_get_softc(dev);
1537 	int i;
1538 
1539 	mtx_assert(&ch->mtx, MA_OWNED);
1540 	/* Handle the rest of commands. */
1541 	for (i = 0; i < MVS_MAX_SLOTS; i++) {
1542 		/* Do we have a running request on slot? */
1543 		if (ch->slot[i].state < MVS_SLOT_RUNNING)
1544 			continue;
1545 		mvs_end_transaction(&ch->slot[i], MVS_ERR_TIMEOUT);
1546 	}
1547 }
1548 
1549 /* Must be called with channel locked. */
1550 static void
1551 mvs_rearm_timeout(device_t dev)
1552 {
1553 	struct mvs_channel *ch = device_get_softc(dev);
1554 	int i;
1555 
1556 	mtx_assert(&ch->mtx, MA_OWNED);
1557 	for (i = 0; i < MVS_MAX_SLOTS; i++) {
1558 		struct mvs_slot *slot = &ch->slot[i];
1559 
1560 		/* Do we have a running request on slot? */
1561 		if (slot->state < MVS_SLOT_RUNNING)
1562 			continue;
1563 		if ((ch->toslots & (1 << i)) == 0)
1564 			continue;
1565 		callout_reset_sbt(&slot->timeout,
1566 		    SBT_1MS * slot->ccb->ccb_h.timeout / 2, 0,
1567 		    mvs_timeout, slot, 0);
1568 	}
1569 }
1570 
1571 /* Locked by callout mechanism. */
1572 static void
1573 mvs_timeout(void *arg)
1574 {
1575 	struct mvs_slot *slot = arg;
1576 	device_t dev = slot->dev;
1577 	struct mvs_channel *ch = device_get_softc(dev);
1578 
1579 	/* Check for stale timeout. */
1580 	if (slot->state < MVS_SLOT_RUNNING)
1581 		return;
1582 	device_printf(dev, "Timeout on slot %d\n", slot->slot);
1583 	device_printf(dev, "iec %08x sstat %08x serr %08x edma_s %08x "
1584 	    "dma_c %08x dma_s %08x rs %08x status %02x\n",
1585 	    ATA_INL(ch->r_mem, EDMA_IEC),
1586 	    ATA_INL(ch->r_mem, SATA_SS), ATA_INL(ch->r_mem, SATA_SE),
1587 	    ATA_INL(ch->r_mem, EDMA_S), ATA_INL(ch->r_mem, DMA_C),
1588 	    ATA_INL(ch->r_mem, DMA_S), ch->rslots,
1589 	    ATA_INB(ch->r_mem, ATA_ALTSTAT));
1590 	/* Handle frozen command. */
1591 	mvs_requeue_frozen(dev);
1592 	/* We wait for other commands timeout and pray. */
1593 	if (ch->toslots == 0)
1594 		xpt_freeze_simq(ch->sim, 1);
1595 	ch->toslots |= (1 << slot->slot);
1596 	if ((ch->rslots & ~ch->toslots) == 0)
1597 		mvs_process_timeout(dev);
1598 	else
1599 		device_printf(dev, " ... waiting for slots %08x\n",
1600 		    ch->rslots & ~ch->toslots);
1601 }
1602 
1603 /* Must be called with channel locked. */
1604 static void
1605 mvs_end_transaction(struct mvs_slot *slot, enum mvs_err_type et)
1606 {
1607 	device_t dev = slot->dev;
1608 	struct mvs_channel *ch = device_get_softc(dev);
1609 	union ccb *ccb = slot->ccb;
1610 	int lastto;
1611 
1612 	bus_dmamap_sync(ch->dma.workrq_tag, ch->dma.workrq_map,
1613 	    BUS_DMASYNC_POSTWRITE);
1614 	/* Read result registers to the result struct
1615 	 * May be incorrect if several commands finished same time,
1616 	 * so read only when sure or have to.
1617 	 */
1618 	if (ccb->ccb_h.func_code == XPT_ATA_IO) {
1619 		struct ata_res *res = &ccb->ataio.res;
1620 
1621 		if ((et == MVS_ERR_TFE) ||
1622 		    (ccb->ataio.cmd.flags & CAM_ATAIO_NEEDRESULT)) {
1623 			mvs_tfd_read(dev, ccb);
1624 		} else
1625 			bzero(res, sizeof(*res));
1626 	} else {
1627 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE &&
1628 		    ch->basic_dma == 0)
1629 			ccb->csio.resid = ccb->csio.dxfer_len - ch->donecount;
1630 	}
1631 	if (ch->numpslots == 0 || ch->basic_dma) {
1632 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
1633 			bus_dmamap_sync(ch->dma.data_tag, slot->dma.data_map,
1634 			    (ccb->ccb_h.flags & CAM_DIR_IN) ?
1635 			    BUS_DMASYNC_POSTREAD : BUS_DMASYNC_POSTWRITE);
1636 			bus_dmamap_unload(ch->dma.data_tag, slot->dma.data_map);
1637 		}
1638 	}
1639 	if (et != MVS_ERR_NONE)
1640 		ch->eslots |= (1 << slot->slot);
1641 	/* In case of error, freeze device for proper recovery. */
1642 	if ((et != MVS_ERR_NONE) && (!ch->recoverycmd) &&
1643 	    !(ccb->ccb_h.status & CAM_DEV_QFRZN)) {
1644 		xpt_freeze_devq(ccb->ccb_h.path, 1);
1645 		ccb->ccb_h.status |= CAM_DEV_QFRZN;
1646 	}
1647 	/* Set proper result status. */
1648 	ccb->ccb_h.status &= ~CAM_STATUS_MASK;
1649 	switch (et) {
1650 	case MVS_ERR_NONE:
1651 		ccb->ccb_h.status |= CAM_REQ_CMP;
1652 		if (ccb->ccb_h.func_code == XPT_SCSI_IO)
1653 			ccb->csio.scsi_status = SCSI_STATUS_OK;
1654 		break;
1655 	case MVS_ERR_INVALID:
1656 		ch->fatalerr = 1;
1657 		ccb->ccb_h.status |= CAM_REQ_INVALID;
1658 		break;
1659 	case MVS_ERR_INNOCENT:
1660 		ccb->ccb_h.status |= CAM_REQUEUE_REQ;
1661 		break;
1662 	case MVS_ERR_TFE:
1663 	case MVS_ERR_NCQ:
1664 		if (ccb->ccb_h.func_code == XPT_SCSI_IO) {
1665 			ccb->ccb_h.status |= CAM_SCSI_STATUS_ERROR;
1666 			ccb->csio.scsi_status = SCSI_STATUS_CHECK_COND;
1667 		} else {
1668 			ccb->ccb_h.status |= CAM_ATA_STATUS_ERROR;
1669 		}
1670 		break;
1671 	case MVS_ERR_SATA:
1672 		ch->fatalerr = 1;
1673 		if (!ch->recoverycmd) {
1674 			xpt_freeze_simq(ch->sim, 1);
1675 			ccb->ccb_h.status &= ~CAM_STATUS_MASK;
1676 			ccb->ccb_h.status |= CAM_RELEASE_SIMQ;
1677 		}
1678 		ccb->ccb_h.status |= CAM_UNCOR_PARITY;
1679 		break;
1680 	case MVS_ERR_TIMEOUT:
1681 		if (!ch->recoverycmd) {
1682 			xpt_freeze_simq(ch->sim, 1);
1683 			ccb->ccb_h.status &= ~CAM_STATUS_MASK;
1684 			ccb->ccb_h.status |= CAM_RELEASE_SIMQ;
1685 		}
1686 		ccb->ccb_h.status |= CAM_CMD_TIMEOUT;
1687 		break;
1688 	default:
1689 		ch->fatalerr = 1;
1690 		ccb->ccb_h.status |= CAM_REQ_CMP_ERR;
1691 	}
1692 	/* Free slot. */
1693 	ch->oslots &= ~(1 << slot->slot);
1694 	ch->rslots &= ~(1 << slot->slot);
1695 	ch->aslots &= ~(1 << slot->slot);
1696 	slot->state = MVS_SLOT_EMPTY;
1697 	slot->ccb = NULL;
1698 	/* Update channel stats. */
1699 	ch->numrslots--;
1700 	ch->numrslotspd[ccb->ccb_h.target_id]--;
1701 	if (ccb->ccb_h.func_code == XPT_ATA_IO) {
1702 		if (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA) {
1703 			ch->otagspd[ccb->ccb_h.target_id] &= ~(1 << slot->tag);
1704 			ch->numtslots--;
1705 			ch->numtslotspd[ccb->ccb_h.target_id]--;
1706 		} else if (ccb->ataio.cmd.flags & CAM_ATAIO_DMA) {
1707 			ch->numdslots--;
1708 		} else {
1709 			ch->numpslots--;
1710 		}
1711 	} else {
1712 		ch->numpslots--;
1713 		ch->basic_dma = 0;
1714 	}
1715 	/* Cancel timeout state if request completed normally. */
1716 	if (et != MVS_ERR_TIMEOUT) {
1717 		lastto = (ch->toslots == (1 << slot->slot));
1718 		ch->toslots &= ~(1 << slot->slot);
1719 		if (lastto)
1720 			xpt_release_simq(ch->sim, TRUE);
1721 	}
1722 	/* If it was our READ LOG command - process it. */
1723 	if (ccb->ccb_h.recovery_type == RECOVERY_READ_LOG) {
1724 		mvs_process_read_log(dev, ccb);
1725 	/* If it was our REQUEST SENSE command - process it. */
1726 	} else if (ccb->ccb_h.recovery_type == RECOVERY_REQUEST_SENSE) {
1727 		mvs_process_request_sense(dev, ccb);
1728 	/* If it was NCQ or ATAPI command error, put result on hold. */
1729 	} else if (et == MVS_ERR_NCQ ||
1730 	    ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_SCSI_STATUS_ERROR &&
1731 	     (ccb->ccb_h.flags & CAM_DIS_AUTOSENSE) == 0)) {
1732 		ch->hold[slot->slot] = ccb;
1733 		ch->holdtag[slot->slot] = slot->tag;
1734 		ch->numhslots++;
1735 	} else
1736 		xpt_done(ccb);
1737 	/* If we have no other active commands, ... */
1738 	if (ch->rslots == 0) {
1739 		/* if there was fatal error - reset port. */
1740 		if (ch->toslots != 0 || ch->fatalerr) {
1741 			mvs_reset(dev);
1742 		} else {
1743 			/* if we have slots in error, we can reinit port. */
1744 			if (ch->eslots != 0) {
1745 				mvs_set_edma_mode(dev, MVS_EDMA_OFF);
1746 				ch->eslots = 0;
1747 			}
1748 			/* if there commands on hold, we can do READ LOG. */
1749 			if (!ch->recoverycmd && ch->numhslots)
1750 				mvs_issue_recovery(dev);
1751 		}
1752 	/* If all the rest of commands are in timeout - give them chance. */
1753 	} else if ((ch->rslots & ~ch->toslots) == 0 &&
1754 	    et != MVS_ERR_TIMEOUT)
1755 		mvs_rearm_timeout(dev);
1756 	/* Unfreeze frozen command. */
1757 	if (ch->frozen && !mvs_check_collision(dev, ch->frozen)) {
1758 		union ccb *fccb = ch->frozen;
1759 		ch->frozen = NULL;
1760 		mvs_begin_transaction(dev, fccb);
1761 		xpt_release_simq(ch->sim, TRUE);
1762 	}
1763 	/* Start PM timer. */
1764 	if (ch->numrslots == 0 && ch->pm_level > 3 &&
1765 	    (ch->curr[ch->pm_present ? 15 : 0].caps & CTS_SATA_CAPS_D_PMREQ)) {
1766 		callout_schedule(&ch->pm_timer,
1767 		    (ch->pm_level == 4) ? hz / 1000 : hz / 8);
1768 	}
1769 }
1770 
1771 static void
1772 mvs_issue_recovery(device_t dev)
1773 {
1774 	struct mvs_channel *ch = device_get_softc(dev);
1775 	union ccb *ccb;
1776 	struct ccb_ataio *ataio;
1777 	struct ccb_scsiio *csio;
1778 	int i;
1779 
1780 	/* Find some held command. */
1781 	for (i = 0; i < MVS_MAX_SLOTS; i++) {
1782 		if (ch->hold[i])
1783 			break;
1784 	}
1785 	ccb = xpt_alloc_ccb_nowait();
1786 	if (ccb == NULL) {
1787 		device_printf(dev, "Unable to allocate recovery command\n");
1788 completeall:
1789 		/* We can't do anything -- complete held commands. */
1790 		for (i = 0; i < MVS_MAX_SLOTS; i++) {
1791 			if (ch->hold[i] == NULL)
1792 				continue;
1793 			ch->hold[i]->ccb_h.status &= ~CAM_STATUS_MASK;
1794 			ch->hold[i]->ccb_h.status |= CAM_RESRC_UNAVAIL;
1795 			xpt_done(ch->hold[i]);
1796 			ch->hold[i] = NULL;
1797 			ch->numhslots--;
1798 		}
1799 		mvs_reset(dev);
1800 		return;
1801 	}
1802 	xpt_setup_ccb(&ccb->ccb_h, ch->hold[i]->ccb_h.path,
1803 	    ch->hold[i]->ccb_h.pinfo.priority);
1804 	if (ccb->ccb_h.func_code == XPT_ATA_IO) {
1805 		/* READ LOG */
1806 		ccb->ccb_h.recovery_type = RECOVERY_READ_LOG;
1807 		ccb->ccb_h.func_code = XPT_ATA_IO;
1808 		ccb->ccb_h.flags = CAM_DIR_IN;
1809 		ccb->ccb_h.timeout = 1000;	/* 1s should be enough. */
1810 		ataio = &ccb->ataio;
1811 		ataio->data_ptr = malloc(512, M_MVS, M_NOWAIT);
1812 		if (ataio->data_ptr == NULL) {
1813 			xpt_free_ccb(ccb);
1814 			device_printf(dev,
1815 			    "Unable to allocate memory for READ LOG command\n");
1816 			goto completeall;
1817 		}
1818 		ataio->dxfer_len = 512;
1819 		bzero(&ataio->cmd, sizeof(ataio->cmd));
1820 		ataio->cmd.flags = CAM_ATAIO_48BIT;
1821 		ataio->cmd.command = 0x2F;	/* READ LOG EXT */
1822 		ataio->cmd.sector_count = 1;
1823 		ataio->cmd.sector_count_exp = 0;
1824 		ataio->cmd.lba_low = 0x10;
1825 		ataio->cmd.lba_mid = 0;
1826 		ataio->cmd.lba_mid_exp = 0;
1827 	} else {
1828 		/* REQUEST SENSE */
1829 		ccb->ccb_h.recovery_type = RECOVERY_REQUEST_SENSE;
1830 		ccb->ccb_h.recovery_slot = i;
1831 		ccb->ccb_h.func_code = XPT_SCSI_IO;
1832 		ccb->ccb_h.flags = CAM_DIR_IN;
1833 		ccb->ccb_h.status = 0;
1834 		ccb->ccb_h.timeout = 1000;	/* 1s should be enough. */
1835 		csio = &ccb->csio;
1836 		csio->data_ptr = (void *)&ch->hold[i]->csio.sense_data;
1837 		csio->dxfer_len = ch->hold[i]->csio.sense_len;
1838 		csio->cdb_len = 6;
1839 		bzero(&csio->cdb_io, sizeof(csio->cdb_io));
1840 		csio->cdb_io.cdb_bytes[0] = 0x03;
1841 		csio->cdb_io.cdb_bytes[4] = csio->dxfer_len;
1842 	}
1843 	/* Freeze SIM while doing recovery. */
1844 	ch->recoverycmd = 1;
1845 	xpt_freeze_simq(ch->sim, 1);
1846 	mvs_begin_transaction(dev, ccb);
1847 }
1848 
1849 static void
1850 mvs_process_read_log(device_t dev, union ccb *ccb)
1851 {
1852 	struct mvs_channel *ch = device_get_softc(dev);
1853 	uint8_t *data;
1854 	struct ata_res *res;
1855 	int i;
1856 
1857 	ch->recoverycmd = 0;
1858 
1859 	data = ccb->ataio.data_ptr;
1860 	if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP &&
1861 	    (data[0] & 0x80) == 0) {
1862 		for (i = 0; i < MVS_MAX_SLOTS; i++) {
1863 			if (!ch->hold[i])
1864 				continue;
1865 			if (ch->hold[i]->ccb_h.target_id != ccb->ccb_h.target_id)
1866 				continue;
1867 			if ((data[0] & 0x1F) == ch->holdtag[i]) {
1868 				res = &ch->hold[i]->ataio.res;
1869 				res->status = data[2];
1870 				res->error = data[3];
1871 				res->lba_low = data[4];
1872 				res->lba_mid = data[5];
1873 				res->lba_high = data[6];
1874 				res->device = data[7];
1875 				res->lba_low_exp = data[8];
1876 				res->lba_mid_exp = data[9];
1877 				res->lba_high_exp = data[10];
1878 				res->sector_count = data[12];
1879 				res->sector_count_exp = data[13];
1880 			} else {
1881 				ch->hold[i]->ccb_h.status &= ~CAM_STATUS_MASK;
1882 				ch->hold[i]->ccb_h.status |= CAM_REQUEUE_REQ;
1883 			}
1884 			xpt_done(ch->hold[i]);
1885 			ch->hold[i] = NULL;
1886 			ch->numhslots--;
1887 		}
1888 	} else {
1889 		if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP)
1890 			device_printf(dev, "Error while READ LOG EXT\n");
1891 		else if ((data[0] & 0x80) == 0) {
1892 			device_printf(dev,
1893 			    "Non-queued command error in READ LOG EXT\n");
1894 		}
1895 		for (i = 0; i < MVS_MAX_SLOTS; i++) {
1896 			if (!ch->hold[i])
1897 				continue;
1898 			if (ch->hold[i]->ccb_h.target_id != ccb->ccb_h.target_id)
1899 				continue;
1900 			xpt_done(ch->hold[i]);
1901 			ch->hold[i] = NULL;
1902 			ch->numhslots--;
1903 		}
1904 	}
1905 	free(ccb->ataio.data_ptr, M_MVS);
1906 	xpt_free_ccb(ccb);
1907 	xpt_release_simq(ch->sim, TRUE);
1908 }
1909 
1910 static void
1911 mvs_process_request_sense(device_t dev, union ccb *ccb)
1912 {
1913 	struct mvs_channel *ch = device_get_softc(dev);
1914 	int i;
1915 
1916 	ch->recoverycmd = 0;
1917 
1918 	i = ccb->ccb_h.recovery_slot;
1919 	if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
1920 		ch->hold[i]->ccb_h.status |= CAM_AUTOSNS_VALID;
1921 	} else {
1922 		ch->hold[i]->ccb_h.status &= ~CAM_STATUS_MASK;
1923 		ch->hold[i]->ccb_h.status |= CAM_AUTOSENSE_FAIL;
1924 	}
1925 	xpt_done(ch->hold[i]);
1926 	ch->hold[i] = NULL;
1927 	ch->numhslots--;
1928 	xpt_free_ccb(ccb);
1929 	xpt_release_simq(ch->sim, TRUE);
1930 }
1931 
1932 static int
1933 mvs_wait(device_t dev, u_int s, u_int c, int t)
1934 {
1935 	int timeout = 0;
1936 	uint8_t st;
1937 
1938 	while (((st =  mvs_getstatus(dev, 0)) & (s | c)) != s) {
1939 		if (timeout >= t) {
1940 			if (t != 0)
1941 				device_printf(dev, "Wait status %02x\n", st);
1942 			return (-1);
1943 		}
1944 		DELAY(1000);
1945 		timeout++;
1946 	}
1947 	return (timeout);
1948 }
1949 
1950 static void
1951 mvs_requeue_frozen(device_t dev)
1952 {
1953 	struct mvs_channel *ch = device_get_softc(dev);
1954 	union ccb *fccb = ch->frozen;
1955 
1956 	if (fccb) {
1957 		ch->frozen = NULL;
1958 		fccb->ccb_h.status = CAM_REQUEUE_REQ | CAM_RELEASE_SIMQ;
1959 		if (!(fccb->ccb_h.status & CAM_DEV_QFRZN)) {
1960 			xpt_freeze_devq(fccb->ccb_h.path, 1);
1961 			fccb->ccb_h.status |= CAM_DEV_QFRZN;
1962 		}
1963 		xpt_done(fccb);
1964 	}
1965 }
1966 
1967 static void
1968 mvs_reset_to(void *arg)
1969 {
1970 	device_t dev = arg;
1971 	struct mvs_channel *ch = device_get_softc(dev);
1972 	int t;
1973 
1974 	if (ch->resetting == 0)
1975 		return;
1976 	ch->resetting--;
1977 	if ((t = mvs_wait(dev, 0, ATA_S_BUSY | ATA_S_DRQ, 0)) >= 0) {
1978 		if (bootverbose) {
1979 			device_printf(dev,
1980 			    "MVS reset: device ready after %dms\n",
1981 			    (310 - ch->resetting) * 100);
1982 		}
1983 		ch->resetting = 0;
1984 		xpt_release_simq(ch->sim, TRUE);
1985 		return;
1986 	}
1987 	if (ch->resetting == 0) {
1988 		device_printf(dev,
1989 		    "MVS reset: device not ready after 31000ms\n");
1990 		xpt_release_simq(ch->sim, TRUE);
1991 		return;
1992 	}
1993 	callout_schedule(&ch->reset_timer, hz / 10);
1994 }
1995 
1996 static void
1997 mvs_errata(device_t dev)
1998 {
1999 	struct mvs_channel *ch = device_get_softc(dev);
2000 	uint32_t val;
2001 
2002 	if (ch->quirks & MVS_Q_SOC65) {
2003 		val = ATA_INL(ch->r_mem, SATA_PHYM3);
2004 		val &= ~(0x3 << 27);	/* SELMUPF = 1 */
2005 		val |= (0x1 << 27);
2006 		val &= ~(0x3 << 29);	/* SELMUPI = 1 */
2007 		val |= (0x1 << 29);
2008 		ATA_OUTL(ch->r_mem, SATA_PHYM3, val);
2009 
2010 		val = ATA_INL(ch->r_mem, SATA_PHYM4);
2011 		val &= ~0x1;		/* SATU_OD8 = 0 */
2012 		val |= (0x1 << 16);	/* reserved bit 16 = 1 */
2013 		ATA_OUTL(ch->r_mem, SATA_PHYM4, val);
2014 
2015 		val = ATA_INL(ch->r_mem, SATA_PHYM9_GEN2);
2016 		val &= ~0xf;		/* TXAMP[3:0] = 8 */
2017 		val |= 0x8;
2018 		val &= ~(0x1 << 14);	/* TXAMP[4] = 0 */
2019 		ATA_OUTL(ch->r_mem, SATA_PHYM9_GEN2, val);
2020 
2021 		val = ATA_INL(ch->r_mem, SATA_PHYM9_GEN1);
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_GEN1, val);
2026 	}
2027 }
2028 
2029 static void
2030 mvs_reset(device_t dev)
2031 {
2032 	struct mvs_channel *ch = device_get_softc(dev);
2033 	int i;
2034 
2035 	xpt_freeze_simq(ch->sim, 1);
2036 	if (bootverbose)
2037 		device_printf(dev, "MVS reset...\n");
2038 	/* Forget about previous reset. */
2039 	if (ch->resetting) {
2040 		ch->resetting = 0;
2041 		callout_stop(&ch->reset_timer);
2042 		xpt_release_simq(ch->sim, TRUE);
2043 	}
2044 	/* Requeue freezed command. */
2045 	mvs_requeue_frozen(dev);
2046 	/* Kill the engine and requeue all running commands. */
2047 	mvs_set_edma_mode(dev, MVS_EDMA_OFF);
2048 	ATA_OUTL(ch->r_mem, DMA_C, 0);
2049 	for (i = 0; i < MVS_MAX_SLOTS; i++) {
2050 		/* Do we have a running request on slot? */
2051 		if (ch->slot[i].state < MVS_SLOT_RUNNING)
2052 			continue;
2053 		/* XXX; Commands in loading state. */
2054 		mvs_end_transaction(&ch->slot[i], MVS_ERR_INNOCENT);
2055 	}
2056 	for (i = 0; i < MVS_MAX_SLOTS; i++) {
2057 		if (!ch->hold[i])
2058 			continue;
2059 		xpt_done(ch->hold[i]);
2060 		ch->hold[i] = NULL;
2061 		ch->numhslots--;
2062 	}
2063 	if (ch->toslots != 0)
2064 		xpt_release_simq(ch->sim, TRUE);
2065 	ch->eslots = 0;
2066 	ch->toslots = 0;
2067 	ch->fatalerr = 0;
2068 	ch->fake_busy = 0;
2069 	/* Tell the XPT about the event */
2070 	xpt_async(AC_BUS_RESET, ch->path, NULL);
2071 	ATA_OUTL(ch->r_mem, EDMA_IEM, 0);
2072 	ATA_OUTL(ch->r_mem, EDMA_CMD, EDMA_CMD_EATARST);
2073 	DELAY(25);
2074 	ATA_OUTL(ch->r_mem, EDMA_CMD, 0);
2075 	mvs_errata(dev);
2076 	/* Reset and reconnect PHY, */
2077 	if (!mvs_sata_phy_reset(dev)) {
2078 		if (bootverbose)
2079 			device_printf(dev, "MVS reset: device not found\n");
2080 		ch->devices = 0;
2081 		ATA_OUTL(ch->r_mem, SATA_SE, 0xffffffff);
2082 		ATA_OUTL(ch->r_mem, EDMA_IEC, 0);
2083 		ATA_OUTL(ch->r_mem, EDMA_IEM, ~EDMA_IE_TRANSIENT);
2084 		xpt_release_simq(ch->sim, TRUE);
2085 		return;
2086 	}
2087 	if (bootverbose)
2088 		device_printf(dev, "MVS reset: device found\n");
2089 	/* Wait for clearing busy status. */
2090 	if ((i = mvs_wait(dev, 0, ATA_S_BUSY | ATA_S_DRQ,
2091 	    dumping ? 31000 : 0)) < 0) {
2092 		if (dumping) {
2093 			device_printf(dev,
2094 			    "MVS reset: device not ready after 31000ms\n");
2095 		} else
2096 			ch->resetting = 310;
2097 	} else if (bootverbose)
2098 		device_printf(dev, "MVS reset: device ready after %dms\n", i);
2099 	ch->devices = 1;
2100 	ATA_OUTL(ch->r_mem, SATA_SE, 0xffffffff);
2101 	ATA_OUTL(ch->r_mem, EDMA_IEC, 0);
2102 	ATA_OUTL(ch->r_mem, EDMA_IEM, ~EDMA_IE_TRANSIENT);
2103 	if (ch->resetting)
2104 		callout_reset(&ch->reset_timer, hz / 10, mvs_reset_to, dev);
2105 	else
2106 		xpt_release_simq(ch->sim, TRUE);
2107 }
2108 
2109 static void
2110 mvs_softreset(device_t dev, union ccb *ccb)
2111 {
2112 	struct mvs_channel *ch = device_get_softc(dev);
2113 	int port = ccb->ccb_h.target_id & 0x0f;
2114 	int i, stuck;
2115 	uint8_t status;
2116 
2117 	mvs_set_edma_mode(dev, MVS_EDMA_OFF);
2118 	ATA_OUTB(ch->r_mem, SATA_SATAICTL, port << SATA_SATAICTL_PMPTX_SHIFT);
2119 	ATA_OUTB(ch->r_mem, ATA_CONTROL, ATA_A_RESET);
2120 	DELAY(10000);
2121 	ATA_OUTB(ch->r_mem, ATA_CONTROL, 0);
2122 	ccb->ccb_h.status &= ~CAM_STATUS_MASK;
2123 	/* Wait for clearing busy status. */
2124 	if ((i = mvs_wait(dev, 0, ATA_S_BUSY, ccb->ccb_h.timeout)) < 0) {
2125 		ccb->ccb_h.status |= CAM_CMD_TIMEOUT;
2126 		stuck = 1;
2127 	} else {
2128 		status = mvs_getstatus(dev, 0);
2129 		if (status & ATA_S_ERROR)
2130 			ccb->ccb_h.status |= CAM_ATA_STATUS_ERROR;
2131 		else
2132 			ccb->ccb_h.status |= CAM_REQ_CMP;
2133 		if (status & ATA_S_DRQ)
2134 			stuck = 1;
2135 		else
2136 			stuck = 0;
2137 	}
2138 	mvs_tfd_read(dev, ccb);
2139 
2140 	/*
2141 	 * XXX: If some device on PMP failed to soft-reset,
2142 	 * try to recover by sending dummy soft-reset to PMP.
2143 	 */
2144 	if (stuck && ch->pm_present && port != 15) {
2145 		ATA_OUTB(ch->r_mem, SATA_SATAICTL,
2146 		    15 << SATA_SATAICTL_PMPTX_SHIFT);
2147 		ATA_OUTB(ch->r_mem, ATA_CONTROL, ATA_A_RESET);
2148 		DELAY(10000);
2149 		ATA_OUTB(ch->r_mem, ATA_CONTROL, 0);
2150 		mvs_wait(dev, 0, ATA_S_BUSY | ATA_S_DRQ, ccb->ccb_h.timeout);
2151 	}
2152 
2153 	xpt_done(ccb);
2154 }
2155 
2156 static int
2157 mvs_sata_connect(struct mvs_channel *ch)
2158 {
2159 	u_int32_t status;
2160 	int timeout, found = 0;
2161 
2162 	/* Wait up to 100ms for "connect well" */
2163 	for (timeout = 0; timeout < 1000 ; timeout++) {
2164 		status = ATA_INL(ch->r_mem, SATA_SS);
2165 		if ((status & SATA_SS_DET_MASK) != SATA_SS_DET_NO_DEVICE)
2166 			found = 1;
2167 		if (((status & SATA_SS_DET_MASK) == SATA_SS_DET_PHY_ONLINE) &&
2168 		    ((status & SATA_SS_SPD_MASK) != SATA_SS_SPD_NO_SPEED) &&
2169 		    ((status & SATA_SS_IPM_MASK) == SATA_SS_IPM_ACTIVE))
2170 			break;
2171 		if ((status & SATA_SS_DET_MASK) == SATA_SS_DET_PHY_OFFLINE) {
2172 			if (bootverbose) {
2173 				device_printf(ch->dev, "SATA offline status=%08x\n",
2174 				    status);
2175 			}
2176 			return (0);
2177 		}
2178 		if (found == 0 && timeout >= 100)
2179 			break;
2180 		DELAY(100);
2181 	}
2182 	if (timeout >= 1000 || !found) {
2183 		if (bootverbose) {
2184 			device_printf(ch->dev,
2185 			    "SATA connect timeout time=%dus status=%08x\n",
2186 			    timeout * 100, status);
2187 		}
2188 		return (0);
2189 	}
2190 	if (bootverbose) {
2191 		device_printf(ch->dev, "SATA connect time=%dus status=%08x\n",
2192 		    timeout * 100, status);
2193 	}
2194 	/* Clear SATA error register */
2195 	ATA_OUTL(ch->r_mem, SATA_SE, 0xffffffff);
2196 	return (1);
2197 }
2198 
2199 static int
2200 mvs_sata_phy_reset(device_t dev)
2201 {
2202 	struct mvs_channel *ch = device_get_softc(dev);
2203 	int sata_rev;
2204 	uint32_t val;
2205 
2206 	sata_rev = ch->user[ch->pm_present ? 15 : 0].revision;
2207 	if (sata_rev == 1)
2208 		val = SATA_SC_SPD_SPEED_GEN1;
2209 	else if (sata_rev == 2)
2210 		val = SATA_SC_SPD_SPEED_GEN2;
2211 	else if (sata_rev == 3)
2212 		val = SATA_SC_SPD_SPEED_GEN3;
2213 	else
2214 		val = 0;
2215 	ATA_OUTL(ch->r_mem, SATA_SC,
2216 	    SATA_SC_DET_RESET | val |
2217 	    SATA_SC_IPM_DIS_PARTIAL | SATA_SC_IPM_DIS_SLUMBER);
2218 	DELAY(1000);
2219 	ATA_OUTL(ch->r_mem, SATA_SC,
2220 	    SATA_SC_DET_IDLE | val | ((ch->pm_level > 0) ? 0 :
2221 	    (SATA_SC_IPM_DIS_PARTIAL | SATA_SC_IPM_DIS_SLUMBER)));
2222 	if (!mvs_sata_connect(ch)) {
2223 		if (ch->pm_level > 0)
2224 			ATA_OUTL(ch->r_mem, SATA_SC, SATA_SC_DET_DISABLE);
2225 		return (0);
2226 	}
2227 	return (1);
2228 }
2229 
2230 static int
2231 mvs_check_ids(device_t dev, union ccb *ccb)
2232 {
2233 	struct mvs_channel *ch = device_get_softc(dev);
2234 
2235 	if (ccb->ccb_h.target_id > ((ch->quirks & MVS_Q_GENI) ? 0 : 15)) {
2236 		ccb->ccb_h.status = CAM_TID_INVALID;
2237 		xpt_done(ccb);
2238 		return (-1);
2239 	}
2240 	if (ccb->ccb_h.target_lun != 0) {
2241 		ccb->ccb_h.status = CAM_LUN_INVALID;
2242 		xpt_done(ccb);
2243 		return (-1);
2244 	}
2245 	/*
2246 	 * It's a programming error to see AUXILIARY register requests.
2247 	 */
2248 	KASSERT(ccb->ccb_h.func_code != XPT_ATA_IO ||
2249 	    ((ccb->ataio.ata_flags & ATA_FLAG_AUX) == 0),
2250 	    ("AUX register unsupported"));
2251 	return (0);
2252 }
2253 
2254 static void
2255 mvsaction(struct cam_sim *sim, union ccb *ccb)
2256 {
2257 	device_t dev, parent;
2258 	struct mvs_channel *ch;
2259 
2260 	CAM_DEBUG(ccb->ccb_h.path, CAM_DEBUG_TRACE, ("mvsaction func_code=%x\n",
2261 	    ccb->ccb_h.func_code));
2262 
2263 	ch = (struct mvs_channel *)cam_sim_softc(sim);
2264 	dev = ch->dev;
2265 	switch (ccb->ccb_h.func_code) {
2266 	/* Common cases first */
2267 	case XPT_ATA_IO:	/* Execute the requested I/O operation */
2268 	case XPT_SCSI_IO:
2269 		if (mvs_check_ids(dev, ccb))
2270 			return;
2271 		if (ch->devices == 0 ||
2272 		    (ch->pm_present == 0 &&
2273 		     ccb->ccb_h.target_id > 0 && ccb->ccb_h.target_id < 15)) {
2274 			ccb->ccb_h.status = CAM_SEL_TIMEOUT;
2275 			break;
2276 		}
2277 		ccb->ccb_h.recovery_type = RECOVERY_NONE;
2278 		/* Check for command collision. */
2279 		if (mvs_check_collision(dev, ccb)) {
2280 			/* Freeze command. */
2281 			ch->frozen = ccb;
2282 			/* We have only one frozen slot, so freeze simq also. */
2283 			xpt_freeze_simq(ch->sim, 1);
2284 			return;
2285 		}
2286 		mvs_begin_transaction(dev, ccb);
2287 		return;
2288 	case XPT_ABORT:			/* Abort the specified CCB */
2289 		/* XXX Implement */
2290 		ccb->ccb_h.status = CAM_REQ_INVALID;
2291 		break;
2292 	case XPT_SET_TRAN_SETTINGS:
2293 	{
2294 		struct	ccb_trans_settings *cts = &ccb->cts;
2295 		struct	mvs_device *d;
2296 
2297 		if (mvs_check_ids(dev, ccb))
2298 			return;
2299 		if (cts->type == CTS_TYPE_CURRENT_SETTINGS)
2300 			d = &ch->curr[ccb->ccb_h.target_id];
2301 		else
2302 			d = &ch->user[ccb->ccb_h.target_id];
2303 		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_REVISION)
2304 			d->revision = cts->xport_specific.sata.revision;
2305 		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_MODE)
2306 			d->mode = cts->xport_specific.sata.mode;
2307 		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_BYTECOUNT) {
2308 			d->bytecount = min((ch->quirks & MVS_Q_GENIIE) ? 8192 : 2048,
2309 			    cts->xport_specific.sata.bytecount);
2310 		}
2311 		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_TAGS)
2312 			d->tags = min(MVS_MAX_SLOTS, cts->xport_specific.sata.tags);
2313 		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_PM)
2314 			ch->pm_present = cts->xport_specific.sata.pm_present;
2315 		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_ATAPI)
2316 			d->atapi = cts->xport_specific.sata.atapi;
2317 		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_CAPS)
2318 			d->caps = cts->xport_specific.sata.caps;
2319 		ccb->ccb_h.status = CAM_REQ_CMP;
2320 		break;
2321 	}
2322 	case XPT_GET_TRAN_SETTINGS:
2323 	/* Get default/user set transfer settings for the target */
2324 	{
2325 		struct	ccb_trans_settings *cts = &ccb->cts;
2326 		struct  mvs_device *d;
2327 		uint32_t status;
2328 
2329 		if (mvs_check_ids(dev, ccb))
2330 			return;
2331 		if (cts->type == CTS_TYPE_CURRENT_SETTINGS)
2332 			d = &ch->curr[ccb->ccb_h.target_id];
2333 		else
2334 			d = &ch->user[ccb->ccb_h.target_id];
2335 		cts->protocol = PROTO_UNSPECIFIED;
2336 		cts->protocol_version = PROTO_VERSION_UNSPECIFIED;
2337 		cts->transport = XPORT_SATA;
2338 		cts->transport_version = XPORT_VERSION_UNSPECIFIED;
2339 		cts->proto_specific.valid = 0;
2340 		cts->xport_specific.sata.valid = 0;
2341 		if (cts->type == CTS_TYPE_CURRENT_SETTINGS &&
2342 		    (ccb->ccb_h.target_id == 15 ||
2343 		    (ccb->ccb_h.target_id == 0 && !ch->pm_present))) {
2344 			status = ATA_INL(ch->r_mem, SATA_SS) & SATA_SS_SPD_MASK;
2345 			if (status & 0x0f0) {
2346 				cts->xport_specific.sata.revision =
2347 				    (status & 0x0f0) >> 4;
2348 				cts->xport_specific.sata.valid |=
2349 				    CTS_SATA_VALID_REVISION;
2350 			}
2351 			cts->xport_specific.sata.caps = d->caps & CTS_SATA_CAPS_D;
2352 //			if (ch->pm_level)
2353 //				cts->xport_specific.sata.caps |= CTS_SATA_CAPS_H_PMREQ;
2354 			cts->xport_specific.sata.caps |= CTS_SATA_CAPS_H_AN;
2355 			cts->xport_specific.sata.caps &=
2356 			    ch->user[ccb->ccb_h.target_id].caps;
2357 			cts->xport_specific.sata.valid |= CTS_SATA_VALID_CAPS;
2358 		} else {
2359 			cts->xport_specific.sata.revision = d->revision;
2360 			cts->xport_specific.sata.valid |= CTS_SATA_VALID_REVISION;
2361 			cts->xport_specific.sata.caps = d->caps;
2362 			if (cts->type == CTS_TYPE_CURRENT_SETTINGS/* &&
2363 			    (ch->quirks & MVS_Q_GENIIE) == 0*/)
2364 				cts->xport_specific.sata.caps &= ~CTS_SATA_CAPS_H_AN;
2365 			cts->xport_specific.sata.valid |= CTS_SATA_VALID_CAPS;
2366 		}
2367 		cts->xport_specific.sata.mode = d->mode;
2368 		cts->xport_specific.sata.valid |= CTS_SATA_VALID_MODE;
2369 		cts->xport_specific.sata.bytecount = d->bytecount;
2370 		cts->xport_specific.sata.valid |= CTS_SATA_VALID_BYTECOUNT;
2371 		cts->xport_specific.sata.pm_present = ch->pm_present;
2372 		cts->xport_specific.sata.valid |= CTS_SATA_VALID_PM;
2373 		cts->xport_specific.sata.tags = d->tags;
2374 		cts->xport_specific.sata.valid |= CTS_SATA_VALID_TAGS;
2375 		cts->xport_specific.sata.atapi = d->atapi;
2376 		cts->xport_specific.sata.valid |= CTS_SATA_VALID_ATAPI;
2377 		ccb->ccb_h.status = CAM_REQ_CMP;
2378 		break;
2379 	}
2380 	case XPT_RESET_BUS:		/* Reset the specified SCSI bus */
2381 	case XPT_RESET_DEV:	/* Bus Device Reset the specified SCSI device */
2382 		mvs_reset(dev);
2383 		ccb->ccb_h.status = CAM_REQ_CMP;
2384 		break;
2385 	case XPT_TERM_IO:		/* Terminate the I/O process */
2386 		/* XXX Implement */
2387 		ccb->ccb_h.status = CAM_REQ_INVALID;
2388 		break;
2389 	case XPT_PATH_INQ:		/* Path routing inquiry */
2390 	{
2391 		struct ccb_pathinq *cpi = &ccb->cpi;
2392 
2393 		parent = device_get_parent(dev);
2394 		cpi->version_num = 1; /* XXX??? */
2395 		cpi->hba_inquiry = PI_SDTR_ABLE;
2396 		if (!(ch->quirks & MVS_Q_GENI)) {
2397 			cpi->hba_inquiry |= PI_SATAPM;
2398 			/* Gen-II is extremely slow with NCQ on PMP. */
2399 			if ((ch->quirks & MVS_Q_GENIIE) || ch->pm_present == 0)
2400 				cpi->hba_inquiry |= PI_TAG_ABLE;
2401 		}
2402 		cpi->target_sprt = 0;
2403 		cpi->hba_misc = PIM_SEQSCAN;
2404 		cpi->hba_eng_cnt = 0;
2405 		if (!(ch->quirks & MVS_Q_GENI))
2406 			cpi->max_target = 15;
2407 		else
2408 			cpi->max_target = 0;
2409 		cpi->max_lun = 0;
2410 		cpi->initiator_id = 0;
2411 		cpi->bus_id = cam_sim_bus(sim);
2412 		cpi->base_transfer_speed = 150000;
2413 		strlcpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
2414 		strlcpy(cpi->hba_vid, "Marvell", HBA_IDLEN);
2415 		strlcpy(cpi->dev_name, cam_sim_name(sim), DEV_IDLEN);
2416 		cpi->unit_number = cam_sim_unit(sim);
2417 		cpi->transport = XPORT_SATA;
2418 		cpi->transport_version = XPORT_VERSION_UNSPECIFIED;
2419 		cpi->protocol = PROTO_ATA;
2420 		cpi->protocol_version = PROTO_VERSION_UNSPECIFIED;
2421 		cpi->maxio = maxphys;
2422 		if ((ch->quirks & MVS_Q_SOC) == 0) {
2423 			cpi->hba_vendor = pci_get_vendor(parent);
2424 			cpi->hba_device = pci_get_device(parent);
2425 			cpi->hba_subvendor = pci_get_subvendor(parent);
2426 			cpi->hba_subdevice = pci_get_subdevice(parent);
2427 		}
2428 		cpi->ccb_h.status = CAM_REQ_CMP;
2429 		break;
2430 	}
2431 	default:
2432 		ccb->ccb_h.status = CAM_REQ_INVALID;
2433 		break;
2434 	}
2435 	xpt_done(ccb);
2436 }
2437 
2438 static void
2439 mvspoll(struct cam_sim *sim)
2440 {
2441 	struct mvs_channel *ch = (struct mvs_channel *)cam_sim_softc(sim);
2442 	struct mvs_intr_arg arg;
2443 
2444 	arg.arg = ch->dev;
2445 	arg.cause = 2 | 4; /* XXX */
2446 	mvs_ch_intr(&arg);
2447 	if (ch->resetting != 0 &&
2448 	    (--ch->resetpolldiv <= 0 || !callout_pending(&ch->reset_timer))) {
2449 		ch->resetpolldiv = 1000;
2450 		mvs_reset_to(ch->dev);
2451 	}
2452 }
2453