SILI - Work around hardware LRAM bugs part 1/2.
[dragonfly.git] / sys / dev / disk / sili / sili.c
1 /*
2  * Copyright (c) 2009 The DragonFly Project.  All rights reserved.
3  *
4  * This code is derived from software contributed to The DragonFly Project
5  * by Matthew Dillon <dillon@backplane.com>
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  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in
15  *    the documentation and/or other materials provided with the
16  *    distribution.
17  * 3. Neither the name of The DragonFly Project nor the names of its
18  *    contributors may be used to endorse or promote products derived
19  *    from this software without specific, prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
25  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
27  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
31  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  *
35  * Copyright (c) 2006 David Gwynne <dlg@openbsd.org>
36  *
37  * Permission to use, copy, modify, and distribute this software for any
38  * purpose with or without fee is hereby granted, provided that the above
39  * copyright notice and this permission notice appear in all copies.
40  *
41  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
42  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
43  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
44  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
45  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
46  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
47  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
48  *
49  *
50  *
51  * $OpenBSD: sili.c,v 1.147 2009/02/16 21:19:07 miod Exp $
52  */
53
54 #include "sili.h"
55
56 void    sili_port_interrupt_enable(struct sili_port *ap);
57 void    sili_port_interrupt_redisable(struct sili_port *ap);
58 void    sili_port_interrupt_reenable(struct sili_port *ap);
59
60 int     sili_load_prb(struct sili_ccb *);
61 void    sili_unload_prb(struct sili_ccb *);
62 static void sili_load_prb_callback(void *info, bus_dma_segment_t *segs,
63                                     int nsegs, int error);
64 void    sili_start(struct sili_ccb *);
65 int     sili_port_softreset(struct sili_port *ap);
66 int     sili_port_pmprobe(struct sili_port *ap);
67 int     sili_port_hardreset(struct sili_port *ap, int hard);
68 void    sili_port_hardstop(struct sili_port *ap);
69 void    sili_port_listen(struct sili_port *ap);
70
71 static void sili_ata_cmd_timeout_unserialized(void *);
72 static int sili_core_timeout(struct sili_ccb *ccb);
73 void    sili_quick_timeout(struct sili_ccb *ccb);
74 void    sili_check_active_timeouts(struct sili_port *ap);
75
76 void    sili_beg_exclusive_access(struct sili_port *ap, struct ata_port *at);
77 void    sili_end_exclusive_access(struct sili_port *ap, struct ata_port *at);
78 void    sili_issue_pending_commands(struct sili_port *ap, struct sili_ccb *ccb);
79
80 int     sili_port_read_ncq_error(struct sili_port *, int);
81
82 struct sili_dmamem *sili_dmamem_alloc(struct sili_softc *, bus_dma_tag_t tag);
83 void    sili_dmamem_free(struct sili_softc *, struct sili_dmamem *);
84 static void sili_dmamem_saveseg(void *info, bus_dma_segment_t *segs, int nsegs, int error);
85
86 static void sili_dummy_done(struct ata_xfer *xa);
87 static void sili_empty_done(struct sili_ccb *ccb);
88 static void sili_ata_cmd_done(struct sili_ccb *ccb);
89
90 /* Wait for all bits in _b to be cleared */
91 #define sili_pwait_clr(_ap, _r, _b) \
92         sili_pwait_eq((_ap), SILI_PWAIT_TIMEOUT, (_r), (_b), 0)
93 #define sili_pwait_clr_to(_ap, _to,  _r, _b) \
94         sili_pwait_eq((_ap), _to, (_r), (_b), 0)
95
96 /* Wait for all bits in _b to be set */
97 #define sili_pwait_set(_ap, _r, _b) \
98         sili_pwait_eq((_ap), SILI_PWAIT_TIMEOUT, (_r), (_b), (_b))
99 #define sili_pwait_set_to(_ap, _to, _r, _b) \
100         sili_pwait_eq((_ap), _to, (_r), (_b), (_b))
101
102 #define SILI_PWAIT_TIMEOUT      1000
103
104 /*
105  * Initialize the global SILI hardware.  This code does not set up any of
106  * its ports.
107  */
108 int
109 sili_init(struct sili_softc *sc)
110 {
111         DPRINTF(SILI_D_VERBOSE, " GHC 0x%b",
112                 sili_read(sc, SILI_REG_GHC), SILI_FMT_GHC);
113
114         /*
115          * Reset the entire chip.  This also resets all ports.
116          *
117          * The spec doesn't say anything about how long we have to
118          * wait, so wait 10ms.
119          */
120         sili_write(sc, SILI_REG_GCTL, SILI_REG_GCTL_GRESET);
121         sili_os_sleep(10);
122         sili_write(sc, SILI_REG_GCTL, 0);
123         sili_os_sleep(10);
124
125         return (0);
126 }
127
128 /*
129  * Allocate and initialize an SILI port.
130  */
131 int
132 sili_port_alloc(struct sili_softc *sc, u_int port)
133 {
134         struct sili_port        *ap;
135         struct ata_port         *at;
136         struct sili_prb         *prb;
137         struct sili_ccb         *ccb;
138         int     rc = ENOMEM;
139         int     error;
140         int     i;
141
142         ap = kmalloc(sizeof(*ap), M_DEVBUF, M_WAITOK | M_ZERO);
143
144         ksnprintf(ap->ap_name, sizeof(ap->ap_name), "%s%d.%d",
145                   device_get_name(sc->sc_dev),
146                   device_get_unit(sc->sc_dev),
147                   port);
148         sc->sc_ports[port] = ap;
149         kprintf("%s: allocate port\n", PORTNAME(ap));
150
151         /*
152          * Allocate enough so we never have to reallocate, it makes
153          * it easier.
154          *
155          * ap_pmcount will be reduced by the scan if we encounter the
156          * port multiplier port prior to target 15.
157          */
158         if (ap->ap_ata == NULL) {
159                 ap->ap_ata = kmalloc(sizeof(*ap->ap_ata) * SILI_MAX_PMPORTS,
160                                      M_DEVBUF, M_INTWAIT | M_ZERO);
161                 for (i = 0; i < SILI_MAX_PMPORTS; ++i) {
162                         at = &ap->ap_ata[i];
163                         at->at_sili_port = ap;
164                         at->at_target = i;
165                         at->at_probe = ATA_PROBE_NEED_INIT;
166                         at->at_features |= ATA_PORT_F_RESCAN;
167                         ksnprintf(at->at_name, sizeof(at->at_name),
168                                   "%s.%d", ap->ap_name, i);
169                 }
170         }
171         if (bus_space_subregion(sc->sc_piot, sc->sc_pioh,
172                                 SILI_PORT_REGION(port), SILI_PORT_SIZE,
173                                 &ap->ap_ioh) != 0) {
174                 device_printf(sc->sc_dev,
175                               "unable to create register window for port %d\n",
176                               port);
177                 goto freeport;
178         }
179
180         ap->ap_sc = sc;
181         ap->ap_num = port;
182         ap->ap_probe = ATA_PROBE_NEED_INIT;
183         TAILQ_INIT(&ap->ap_ccb_free);
184         TAILQ_INIT(&ap->ap_ccb_pending);
185         lockinit(&ap->ap_ccb_lock, "silipo", 0, 0);
186
187         /* Disable port interrupts */
188         sili_pwrite(ap, SILI_PREG_INT_DISABLE, SILI_PREG_INT_MASK);
189
190         /*
191          * Reset the port.  This is similar to a Device Reset but far
192          * more invasive.  We use Device Reset in our hardreset function.
193          * This function also does the same OOB initialization sequence
194          * that Device Reset does.
195          *
196          * NOTE: SILI_PREG_STATUS_READY will not be asserted unless and until
197          *       a device is connected to the port, so we can't use it to
198          *       verify that the port exists.
199          */
200         sili_pwrite(ap, SILI_PREG_CTL_SET, SILI_PREG_CTL_RESET);
201         if (sili_pread(ap, SILI_PREG_STATUS) & SILI_PREG_STATUS_READY) {
202                 device_printf(sc->sc_dev,
203                               "Port %d will not go into reset\n", port);
204                 goto freeport;
205         }
206         sili_os_sleep(10);
207         sili_pwrite(ap, SILI_PREG_CTL_CLR, SILI_PREG_CTL_RESUME);
208         sili_pwrite(ap, SILI_PREG_CTL_CLR, SILI_PREG_CTL_RESET);
209
210         /*
211          * Adjust FIFO thresholds to improve PCI-e use.
212          */
213         sili_pwrite(ap, SILI_PREG_FIFO_CTL,
214                 SILI_PREG_FIFO_CTL_ENCODE(1024, 1024));
215
216         /*
217          * Allocate the SGE Table
218          */
219         ap->ap_dmamem_prbs = sili_dmamem_alloc(sc, sc->sc_tag_prbs);
220         if (ap->ap_dmamem_prbs == NULL) {
221                 kprintf("%s: NOSGET\n", PORTNAME(ap));
222                 goto freeport;
223         }
224
225         /*
226          * Set up the SGE table base address
227          */
228         ap->ap_prbs = (struct sili_prb *)SILI_DMA_KVA(ap->ap_dmamem_prbs);
229
230         /*
231          * Allocate a CCB for each command slot
232          */
233         ap->ap_ccbs = kmalloc(sizeof(struct sili_ccb) * sc->sc_ncmds, M_DEVBUF,
234                               M_WAITOK | M_ZERO);
235         if (ap->ap_ccbs == NULL) {
236                 device_printf(sc->sc_dev,
237                               "unable to allocate command list for port %d\n",
238                               port);
239                 goto freeport;
240         }
241
242         /*
243          * Port control register setup.
244          */
245         sili_pwrite(ap, SILI_PREG_CTL_SET, SILI_PREG_CTL_NOAUTOCC);
246         sili_pwrite(ap, SILI_PREG_CTL_CLR, SILI_PREG_CTL_32BITDMA |
247                                            SILI_PREG_CTL_PMA |
248                                            SILI_PREG_CTL_NOAUTOCC);
249
250         /*
251          * Most structures are in the port BAR.  Assign convenient
252          * pointers in the CCBs
253          */
254
255         for (i = 0; i < sc->sc_ncmds; i++) {
256                 ccb = &ap->ap_ccbs[i];
257
258                 error = bus_dmamap_create(sc->sc_tag_data, BUS_DMA_ALLOCNOW,
259                                           &ccb->ccb_dmamap);
260                 if (error) {
261                         device_printf(sc->sc_dev,
262                                       "unable to create dmamap for port %d "
263                                       "ccb %d\n", port, i);
264                         goto freeport;
265                 }
266
267                 /*
268                  * WARNING!!!  Access to the rfis is only allowed under very
269                  *             carefully controlled circumstances because it
270                  *             is located in the LRAM and reading from the
271                  *             LRAM has hardware issues which can blow the
272                  *             port up.  I kid you not (from Linux, and
273                  *             verified by testing here).
274                  */
275                 callout_init(&ccb->ccb_timeout);
276                 ccb->ccb_slot = i;
277                 ccb->ccb_port = ap;
278                 ccb->ccb_prb = &ap->ap_prbs[i];
279                 ccb->ccb_prb_paddr = SILI_DMA_DVA(ap->ap_dmamem_prbs) +
280                                      sizeof(*ccb->ccb_prb) * i;
281                 ccb->ccb_xa.fis = &ccb->ccb_prb->prb_h2d;
282                 prb = bus_space_kva(ap->ap_sc->sc_iot, ap->ap_ioh,
283                                     SILI_PREG_LRAM_SLOT(i));
284                 ccb->ccb_xa.rfis = &prb->prb_d2h;
285                 ccb->ccb_xa.packetcmd = prb_packet(ccb->ccb_prb);
286                 ccb->ccb_xa.tag = i;
287
288                 ccb->ccb_xa.state = ATA_S_COMPLETE;
289
290                 /*
291                  * Reserve CCB[1] as the error CCB.  It doesn't matter
292                  * which one we use for the Sili controllers.
293                  */
294                 if (i == 1)
295                         ap->ap_err_ccb = ccb;
296                 else
297                         sili_put_ccb(ccb);
298         }
299         kprintf("%s: start port\n", PORTNAME(ap));
300         sili_os_start_port(ap);
301         return(0);
302 freeport:
303         sili_port_free(sc, port);
304         return (rc);
305 }
306
307 /*
308  * [re]initialize an idle port.  No CCBs should be active.
309  *
310  * If at is NULL we are initializing a directly connected port, otherwise
311  * we are indirectly initializing a port multiplier port.
312  *
313  * This function is called during the initial port allocation sequence
314  * and is also called on hot-plug insertion.  We take no chances and
315  * use a hardreset instead of a softreset.
316  *
317  * This function is the only way to move a failed port back to active
318  * status.
319  *
320  * Returns 0 if a device is successfully detected.
321  */
322 int
323 sili_port_init(struct sili_port *ap, struct ata_port *atx)
324 {
325         u_int32_t data;
326         int rc;
327
328         /*
329          * Clear all notification bits
330          */
331         if (atx == NULL && (ap->ap_sc->sc_flags & SILI_F_SSNTF))
332                 sili_pwrite(ap, SILI_PREG_SNTF, -1);
333
334         /*
335          * Make sure the port is out of continuous COMRESET mode.
336          */
337         data = SILI_PREG_SCTL_SPM_NONE |
338                SILI_PREG_SCTL_IPM_NONE |
339                SILI_PREG_SCTL_SPD_NONE |
340                SILI_PREG_SCTL_DET_NONE;
341         if (SiliForceGen1 & (1 << ap->ap_num)) {
342                 data &= ~SILI_PREG_SCTL_SPD_NONE;
343                 data |= SILI_PREG_SCTL_SPD_GEN1;
344         }
345         sili_pwrite(ap, SILI_PREG_SCTL, data);
346
347         /*
348          * Hard-reset the port.  If a device is detected but it is busy
349          * we try a second time, this time cycling the phy as well.
350          *
351          * XXX note: hard reset mode 2 (cycling the PHY) is not reliable.
352          */
353         if (atx)
354                 atx->at_probe = ATA_PROBE_NEED_HARD_RESET;
355         else
356                 ap->ap_probe = ATA_PROBE_NEED_HARD_RESET;
357
358         rc = sili_port_reset(ap, atx, 1);
359 #if 0
360         rc = sili_port_reset(ap, atx, 1);
361         if (rc == EBUSY) {
362                 rc = sili_port_reset(ap, atx, 2);
363         }
364 #endif
365
366         switch (rc) {
367         case ENODEV:
368                 /*
369                  * We had problems talking to the device on the port.
370                  */
371                 if (atx) {
372                         sili_pm_read(ap, atx->at_target,
373                                      SATA_PMREG_SSTS, &data);
374
375                         switch(data & SATA_PM_SSTS_DET) {
376                         case SATA_PM_SSTS_DET_DEV_NE:
377                                 kprintf("%s: Device not communicating\n",
378                                         ATANAME(ap, atx));
379                                 break;
380                         case SATA_PM_SSTS_DET_PHYOFFLINE:
381                                 kprintf("%s: PHY offline\n",
382                                         ATANAME(ap, atx));
383                                 break;
384                         default:
385                                 kprintf("%s: No device detected\n",
386                                         ATANAME(ap, atx));
387                                 break;
388                         }
389                 } else {
390                         data = sili_pread(ap, SILI_PREG_SSTS);
391
392                         switch(data & SATA_PM_SSTS_DET) {
393                         case SILI_PREG_SSTS_DET_DEV_NE:
394                                 kprintf("%s: Device not communicating\n",
395                                         ATANAME(ap, atx));
396                                 break;
397                         case SILI_PREG_SSTS_DET_OFFLINE:
398                                 kprintf("%s: PHY offline\n",
399                                         ATANAME(ap, atx));
400                                 break;
401                         default:
402                                 kprintf("%s: No device detected\n",
403                                         ATANAME(ap, atx));
404                                 break;
405                         }
406                 }
407                 break;
408
409         case EBUSY:
410                 /*
411                  * The device on the port is still telling us its busy,
412                  * which means that it is not properly handling a SATA
413                  * port COMRESET.
414                  *
415                  * It may be possible to softreset the device using CLO
416                  * and a device reset command.
417                  */
418                 if (atx) {
419                         kprintf("%s: Device on port is bricked, giving up\n",
420                                 ATANAME(ap, atx));
421                 } else {
422                         kprintf("%s: Device on port is bricked, "
423                                 "trying softreset\n", PORTNAME(ap));
424
425                         rc = sili_port_reset(ap, atx, 0);
426                         if (rc) {
427                                 kprintf("%s: Unable unbrick device\n",
428                                         PORTNAME(ap));
429                         } else {
430                                 kprintf("%s: Successfully unbricked\n",
431                                         PORTNAME(ap));
432                         }
433                 }
434                 break;
435
436         default:
437                 break;
438         }
439
440         /*
441          * Command transfers can only be enabled if a device was successfully
442          * detected.
443          *
444          * Allocate or deallocate the ap_ata array here too.
445          */
446         if (atx == NULL) {
447                 switch(ap->ap_type) {
448                 case ATA_PORT_T_NONE:
449                         ap->ap_pmcount = 0;
450                         break;
451                 case ATA_PORT_T_PM:
452                         /* already set */
453                         break;
454                 default:
455                         ap->ap_pmcount = 1;
456                         break;
457                 }
458         }
459
460         /*
461          * Flush interrupts on the port. XXX
462          *
463          * Enable interrupts on the port whether a device is sitting on
464          * it or not, to handle hot-plug events.
465          */
466         if (atx == NULL) {
467 #if 0
468                 sili_pwrite(ap, SILI_PREG_IS, sili_pread(ap, SILI_PREG_IS));
469                 sili_write(ap->ap_sc, SILI_REG_IS, 1 << ap->ap_num);
470 #endif
471                 sili_port_interrupt_enable(ap);
472         }
473         return(rc);
474 }
475
476 /*
477  * Handle an errored port.  This routine is called when the only
478  * commands left on the queue are expired, meaning we can safely
479  * go through a port init to clear its state.
480  *
481  * We complete the expired CCBs and then restart the queue.
482  */
483 static
484 void
485 sili_port_reinit(struct sili_port *ap)
486 {
487         struct sili_ccb *ccb;
488         struct ata_port *at;
489         int slot;
490         int target;
491         u_int32_t data;
492         int reentrant;
493
494         reentrant = (ap->ap_flags & AP_F_ERR_CCB_RESERVED) ? 1 : 0;
495
496         kprintf("%s: PORT REINIT AFTER ERROR reentrant=%d\n",
497                 PORTNAME(ap), reentrant);
498
499         /*
500          * Clear port resume, clear bits 16:13 in the port device status
501          * register.  This is from the data sheet.
502          *
503          * Data sheet does not specify a delay but it seems prudent.
504          */
505         sili_pwrite(ap, SILI_PREG_CTL_CLR, SILI_PREG_CTL_RESUME);
506         sili_os_sleep(10);
507         for (target = 0; target < SILI_MAX_PMPORTS; ++target) {
508                 data = sili_pread(ap, SILI_PREG_PM_STATUS(target));
509                 data &= ~(SILI_PREG_PM_STATUS_SERVICE |
510                           SILI_PREG_PM_STATUS_LEGACY |
511                           SILI_PREG_PM_STATUS_NATIVE |
512                           SILI_PREG_PM_STATUS_VBSY);
513                 sili_pwrite(ap, SILI_PREG_PM_STATUS(target), data);
514                 sili_pwrite(ap, SILI_PREG_PM_QACTIVE(target), 0);
515         }
516
517         /*
518          * Issue a Port Initialize and wait for it to clear.  This flushes
519          * commands but does not reset the port.  Then wait for port ready.
520          */
521         sili_pwrite(ap, SILI_PREG_CTL_SET, SILI_PREG_CTL_INIT);
522         if (sili_pwait_clr(ap, SILI_PREG_STATUS, SILI_PREG_CTL_INIT)) {
523                 kprintf("%s: Unable to reinit, port failed\n",
524                         PORTNAME(ap));
525         }
526         if (sili_pwait_set(ap, SILI_PREG_STATUS, SILI_PREG_STATUS_READY)) {
527                 kprintf("%s: Unable to reinit, port will not come ready\n",
528                         PORTNAME(ap));
529         }
530
531         /*
532          * Read the LOG ERROR page for targets that returned a specific
533          * D2H FIS with ERR set.
534          */
535         if (reentrant == 0) {
536                 for (target = 0; target < SILI_MAX_PMPORTS; ++target) {
537                         at = &ap->ap_ata[target];
538                         if (at->at_features & ATA_PORT_F_READLOG) {
539                                 kprintf("%s: READ LOG ERROR PAGE\n",
540                                         ATANAME(ap, at));
541                                 at->at_features &= ~ATA_PORT_F_READLOG;
542                                 sili_port_read_ncq_error(ap, target);
543                         }
544                 }
545         }
546
547         /*
548          * Finally clean out the expired commands, we've probed the error
549          * status (or hopefully probed the error status).  Well, ok,
550          * we probably didn't XXX.
551          */
552         while (ap->ap_expired) {
553                 slot = ffs(ap->ap_expired) - 1;
554                 ap->ap_expired &= ~(1 << slot);
555                 KKASSERT(ap->ap_active & (1 << slot));
556                 ap->ap_active &= ~(1 << slot);
557                 --ap->ap_active_cnt;
558                 ccb = &ap->ap_ccbs[slot];
559                 ccb->ccb_xa.state = ATA_S_TIMEOUT;
560                 kprintf("%s: reinit: kill slot %d\n",
561                         ATANAME(ap, ccb->ccb_xa.at), ccb->ccb_slot);
562                 ccb->ccb_done(ccb);
563                 ccb->ccb_xa.complete(&ccb->ccb_xa);
564         }
565
566         /*
567          * Wow.  All done.  We can get the port moving again.
568          */
569         if (reentrant) {
570                 kprintf("%s: reinit called reentrantly, skip end\n",
571                         PORTNAME(ap));
572         } else if (ap->ap_probe == ATA_PROBE_FAILED) {
573                 kprintf("%s: reinit failed, port is dead\n", PORTNAME(ap));
574                 while ((ccb = TAILQ_FIRST(&ap->ap_ccb_pending)) != NULL) {
575                         TAILQ_REMOVE(&ap->ap_ccb_pending, ccb, ccb_entry);
576                         ccb->ccb_xa.flags &= ~ATA_F_TIMEOUT_DESIRED;
577                         ccb->ccb_xa.state = ATA_S_TIMEOUT;
578                         ccb->ccb_done(ccb);
579                         ccb->ccb_xa.complete(&ccb->ccb_xa);
580                 }
581         } else {
582                 kprintf("%s: reinit succeeded probe=%d type=%d\n", PORTNAME(ap), ap->ap_probe, ap->ap_type);
583                 sili_issue_pending_commands(ap, NULL);
584         }
585         return;
586 }
587
588 /*
589  * Enable or re-enable interrupts on a port.
590  *
591  * This routine is called from the port initialization code or from the
592  * helper thread as the real interrupt may be forced to turn off certain
593  * interrupt sources.
594  */
595 void
596 sili_port_interrupt_enable(struct sili_port *ap)
597 {
598         u_int32_t data;
599
600         data =  SILI_PREG_INT_CCOMPLETE | SILI_PREG_INT_CERROR |
601                 SILI_PREG_INT_PHYRDYCHG | SILI_PREG_INT_DEVEXCHG |
602                 SILI_PREG_INT_DECODE | SILI_PREG_INT_CRC |
603                 SILI_PREG_INT_HANDSHK | SILI_PREG_INT_PMCHANGE;
604         if (ap->ap_sc->sc_flags & SILI_F_SSNTF)
605                 data |= SILI_PREG_INT_SDB;
606         sili_pwrite(ap, SILI_PREG_INT_ENABLE, data);
607 }
608
609 void
610 sili_port_interrupt_redisable(struct sili_port *ap)
611 {
612         u_int32_t data;
613
614         data = sili_read(ap->ap_sc, SILI_REG_GCTL);
615         data &= SILI_REG_GINT_PORTMASK;
616         data &= ~(1 << ap->ap_num);
617         sili_write(ap->ap_sc, SILI_REG_GCTL, data);
618 }
619
620 void
621 sili_port_interrupt_reenable(struct sili_port *ap)
622 {
623         u_int32_t data;
624
625         data = sili_read(ap->ap_sc, SILI_REG_GCTL);
626         data &= SILI_REG_GINT_PORTMASK;
627         data |= (1 << ap->ap_num);
628         sili_write(ap->ap_sc, SILI_REG_GCTL, data);
629 }
630
631 /*
632  * Run the port / target state machine from a main context.
633  *
634  * The state machine for the port is always run.
635  *
636  * If atx is non-NULL run the state machine for a particular target.
637  * If atx is NULL run the state machine for all targets.
638  */
639 void
640 sili_port_state_machine(struct sili_port *ap, int initial)
641 {
642         struct ata_port *at;
643         u_int32_t data;
644         int target;
645         int didsleep;
646         int loop;
647
648         /*
649          * State machine for port.  Note that CAM is not yet associated
650          * during the initial parallel probe and the port's probe state
651          * will not get past ATA_PROBE_NEED_IDENT.
652          */
653         {
654                 if (initial == 0 && ap->ap_probe <= ATA_PROBE_NEED_HARD_RESET) {
655                         kprintf("%s: Waiting 10 seconds on insertion\n",
656                                 PORTNAME(ap));
657                         sili_os_sleep(10000);
658                         initial = 1;
659                 }
660                 if (ap->ap_probe == ATA_PROBE_NEED_INIT)
661                         sili_port_init(ap, NULL);
662                 if (ap->ap_probe == ATA_PROBE_NEED_HARD_RESET)
663                         sili_port_reset(ap, NULL, 1);
664                 if (ap->ap_probe == ATA_PROBE_NEED_SOFT_RESET)
665                         sili_port_reset(ap, NULL, 0);
666                 if (ap->ap_probe == ATA_PROBE_NEED_IDENT)
667                         sili_cam_probe(ap, NULL);
668         }
669         if (ap->ap_type != ATA_PORT_T_PM) {
670                 if (ap->ap_probe == ATA_PROBE_FAILED) {
671                         sili_cam_changed(ap, NULL, 0);
672                 } else if (ap->ap_probe >= ATA_PROBE_NEED_IDENT) {
673                         sili_cam_changed(ap, NULL, 1);
674                 }
675                 return;
676         }
677
678         /*
679          * Port Multiplier state machine.
680          *
681          * Get a mask of changed targets and combine with any runnable
682          * states already present.
683          */
684         for (loop = 0; ;++loop) {
685                 if (sili_pm_read(ap, 15, SATA_PMREG_EINFO, &data)) {
686                         kprintf("%s: PM unable to read hot-plug bitmap\n",
687                                 PORTNAME(ap));
688                         break;
689                 }
690
691                 /*
692                  * Do at least one loop, then stop if no more state changes
693                  * have occured.  The PM might not generate a new
694                  * notification until we clear the entire bitmap.
695                  */
696                 if (loop && data == 0)
697                         break;
698
699                 /*
700                  * New devices showing up in the bitmap require some spin-up
701                  * time before we start probing them.  Reset didsleep.  The
702                  * first new device we detect will sleep before probing.
703                  *
704                  * This only applies to devices whos change bit is set in
705                  * the data, and does not apply to the initial boot-time
706                  * probe.
707                  */
708                 didsleep = 0;
709
710                 for (target = 0; target < ap->ap_pmcount; ++target) {
711                         at = &ap->ap_ata[target];
712
713                         /*
714                          * Check the target state for targets behind the PM
715                          * which have changed state.  This will adjust
716                          * at_probe and set ATA_PORT_F_RESCAN
717                          *
718                          * We want to wait at least 10 seconds before probing
719                          * a newly inserted device.  If the check status
720                          * indicates a device is present and in need of a
721                          * hard reset, we make sure we have slept before
722                          * continuing.
723                          *
724                          * We also need to wait at least 1 second for the
725                          * PHY state to change after insertion, if we
726                          * haven't already waited the 10 seconds.
727                          *
728                          * NOTE: When pm_check_good finds a good port it
729                          *       typically starts us in probe state
730                          *       NEED_HARD_RESET rather than INIT.
731                          */
732                         if (data & (1 << target)) {
733                                 if (initial == 0 && didsleep == 0)
734                                         sili_os_sleep(1000);
735                                 sili_pm_check_good(ap, target);
736                                 if (initial == 0 && didsleep == 0 &&
737                                     at->at_probe <= ATA_PROBE_NEED_HARD_RESET
738                                 ) {
739                                         didsleep = 1;
740                                         kprintf("%s: Waiting 10 seconds on insertion\n", PORTNAME(ap));
741                                         sili_os_sleep(10000);
742                                 }
743                         }
744
745                         /*
746                          * Report hot-plug events before the probe state
747                          * really gets hot.  Only actual events are reported
748                          * here to reduce spew.
749                          */
750                         if (data & (1 << target)) {
751                                 kprintf("%s: HOTPLUG (PM) - ", ATANAME(ap, at));
752                                 switch(at->at_probe) {
753                                 case ATA_PROBE_NEED_INIT:
754                                 case ATA_PROBE_NEED_HARD_RESET:
755                                         kprintf("Device inserted\n");
756                                         break;
757                                 case ATA_PROBE_FAILED:
758                                         kprintf("Device removed\n");
759                                         break;
760                                 default:
761                                         kprintf("Device probe in progress\n");
762                                         break;
763                                 }
764                         }
765
766                         /*
767                          * Run through the state machine as necessary if
768                          * the port is not marked failed.
769                          *
770                          * The state machine may stop at NEED_IDENT if
771                          * CAM is not yet attached.
772                          *
773                          * Acquire exclusive access to the port while we
774                          * are doing this.  This prevents command-completion
775                          * from queueing commands for non-polled targets
776                          * inbetween our probe steps.  We need to do this
777                          * because the reset probes can generate severe PHY
778                          * and protocol errors and soft-brick the port.
779                          */
780                         if (at->at_probe != ATA_PROBE_FAILED &&
781                             at->at_probe != ATA_PROBE_GOOD) {
782                                 sili_beg_exclusive_access(ap, at);
783                                 if (at->at_probe == ATA_PROBE_NEED_INIT)
784                                         sili_port_init(ap, at);
785                                 if (at->at_probe == ATA_PROBE_NEED_HARD_RESET)
786                                         sili_port_reset(ap, at, 1);
787                                 if (at->at_probe == ATA_PROBE_NEED_SOFT_RESET)
788                                         sili_port_reset(ap, at, 0);
789                                 if (at->at_probe == ATA_PROBE_NEED_IDENT)
790                                         sili_cam_probe(ap, at);
791                                 sili_end_exclusive_access(ap, at);
792                         }
793
794                         /*
795                          * Add or remove from CAM
796                          */
797                         if (at->at_features & ATA_PORT_F_RESCAN) {
798                                 at->at_features &= ~ATA_PORT_F_RESCAN;
799                                 if (at->at_probe == ATA_PROBE_FAILED) {
800                                         sili_cam_changed(ap, at, 0);
801                                 } else if (at->at_probe >= ATA_PROBE_NEED_IDENT) {
802                                         sili_cam_changed(ap, at, 1);
803                                 }
804                         }
805                         data &= ~(1 << target);
806                 }
807                 if (data) {
808                         kprintf("%s: WARNING (PM): extra bits set in "
809                                 "EINFO: %08x\n", PORTNAME(ap), data);
810                         while (target < SILI_MAX_PMPORTS) {
811                                 sili_pm_check_good(ap, target);
812                                 ++target;
813                         }
814                 }
815         }
816 }
817
818 /*
819  * De-initialize and detach a port.
820  */
821 void
822 sili_port_free(struct sili_softc *sc, u_int port)
823 {
824         struct sili_port                *ap = sc->sc_ports[port];
825         struct sili_ccb                 *ccb;
826
827         /*
828          * Ensure port is disabled and its interrupts are all flushed.
829          */
830         if (ap->ap_sc) {
831                 sili_os_stop_port(ap);
832                 sili_pwrite(ap, SILI_PREG_INT_DISABLE, SILI_PREG_INT_MASK);
833                 sili_pwrite(ap, SILI_PREG_CTL_SET, SILI_PREG_CTL_RESET);
834                 sili_write(ap->ap_sc, SILI_REG_GCTL,
835                         sili_read(ap->ap_sc, SILI_REG_GCTL) &
836                         ~SILI_REG_GINT_PORTST(ap->ap_num));
837         }
838
839         if (ap->ap_ccbs) {
840                 while ((ccb = sili_get_ccb(ap)) != NULL) {
841                         if (ccb->ccb_dmamap) {
842                                 bus_dmamap_destroy(sc->sc_tag_data,
843                                                    ccb->ccb_dmamap);
844                                 ccb->ccb_dmamap = NULL;
845                         }
846                 }
847                 if ((ccb = ap->ap_err_ccb) != NULL) {
848                         if (ccb->ccb_dmamap) {
849                                 bus_dmamap_destroy(sc->sc_tag_data,
850                                                    ccb->ccb_dmamap);
851                                 ccb->ccb_dmamap = NULL;
852                         }
853                         ap->ap_err_ccb = NULL;
854                 }
855                 kfree(ap->ap_ccbs, M_DEVBUF);
856                 ap->ap_ccbs = NULL;
857         }
858
859         if (ap->ap_dmamem_prbs) {
860                 sili_dmamem_free(sc, ap->ap_dmamem_prbs);
861                 ap->ap_dmamem_prbs = NULL;
862         }
863         if (ap->ap_ata) {
864                 kfree(ap->ap_ata, M_DEVBUF);
865                 ap->ap_ata = NULL;
866         }
867
868         /* bus_space(9) says we dont free the subregions handle */
869
870         kfree(ap, M_DEVBUF);
871         sc->sc_ports[port] = NULL;
872 }
873
874 /*
875  * Reset a port.
876  *
877  * If hard is 0 perform a softreset of the port.
878  * If hard is 1 perform a hard reset of the port.
879  * If hard is 2 perform a hard reset of the port and cycle the phy.
880  *
881  * If at is non-NULL an indirect port via a port-multiplier is being
882  * reset, otherwise a direct port is being reset.
883  *
884  * NOTE: Indirect ports can only be soft-reset.
885  */
886 int
887 sili_port_reset(struct sili_port *ap, struct ata_port *at, int hard)
888 {
889         int rc;
890
891         if (hard) {
892                 if (at)
893                         rc = sili_pm_hardreset(ap, at->at_target, hard);
894                 else
895                         rc = sili_port_hardreset(ap, hard);
896         } else {
897                 if (at)
898                         rc = sili_pm_softreset(ap, at->at_target);
899                 else
900                         rc = sili_port_softreset(ap);
901         }
902         return(rc);
903 }
904
905 /*
906  * SILI soft reset, Section 10.4.1
907  *
908  * (at) will be NULL when soft-resetting a directly-attached device, and
909  * non-NULL when soft-resetting a device through a port multiplier.
910  *
911  * This function keeps port communications intact and attempts to generate
912  * a reset to the connected device using device commands.
913  */
914 int
915 sili_port_softreset(struct sili_port *ap)
916 {
917         struct sili_ccb         *ccb = NULL;
918         struct sili_prb         *prb;
919         int                     error;
920         u_int32_t               sig;
921
922         error = EIO;
923
924         kprintf("%s: START SOFTRESET\n", PORTNAME(ap));
925
926         DPRINTF(SILI_D_VERBOSE, "%s: soft reset\n", PORTNAME(ap));
927
928         crit_enter();
929         ap->ap_state = AP_S_NORMAL;
930
931         /*
932          * Prep the special soft-reset SII command.
933          */
934         ccb = sili_get_err_ccb(ap);
935         ccb->ccb_done = sili_empty_done;
936         ccb->ccb_xa.flags = ATA_F_POLL;
937         ccb->ccb_xa.complete = sili_dummy_done;
938         ccb->ccb_xa.at = NULL;
939
940         prb = ccb->ccb_prb;
941         bzero(&prb->prb_h2d, sizeof(prb->prb_h2d));
942         prb->prb_h2d.flags = 0;
943         prb->prb_control = SILI_PRB_CTRL_SOFTRESET;
944         prb->prb_override = 0;
945
946         ccb->ccb_xa.state = ATA_S_PENDING;
947         ccb->ccb_xa.flags = 0;
948
949                                 /* XXX */
950         if (sili_poll(ccb, 8000, sili_quick_timeout) != ATA_S_COMPLETE) {
951                 kprintf("%s: First FIS failed\n", PORTNAME(ap));
952                 goto err;
953         }
954
955         sig = (prb->prb_d2h.lba_high << 24) |
956               (prb->prb_d2h.lba_mid << 16) |
957               (prb->prb_d2h.lba_low << 8) |
958               (prb->prb_d2h.sector_count);
959         kprintf("%s: SOFTRESET SIGNATURE %08x\n", PORTNAME(ap), sig);
960
961         /*
962          * If the softreset is trying to clear a BSY condition after a
963          * normal portreset we assign the port type.
964          *
965          * If the softreset is being run first as part of the ccb error
966          * processing code then report if the device signature changed
967          * unexpectedly.
968          */
969         if (ap->ap_type == ATA_PORT_T_NONE) {
970                 ap->ap_type = sili_port_signature(ap, NULL, sig);
971         } else {
972                 if (sili_port_signature(ap, NULL, sig) != ap->ap_type) {
973                         kprintf("%s: device signature unexpectedly "
974                                 "changed\n", PORTNAME(ap));
975                         error = EBUSY; /* XXX */
976                 }
977         }
978         error = 0;
979 err:
980         if (ccb != NULL) {
981                 sili_put_err_ccb(ccb);
982         }
983
984         /*
985          * If we failed to softreset make the port quiescent, otherwise
986          * make sure the port's start/stop state matches what it was on
987          * entry.
988          *
989          * Don't kill the port if the softreset is on a port multiplier
990          * target, that would kill all the targets!
991          */
992         kprintf("%s: END SOFTRESET %d prob=%d state=%d\n", PORTNAME(ap), error, ap->ap_probe, ap->ap_state);
993         if (error) {
994                 sili_port_hardstop(ap);
995                 /* ap_probe set to failed */
996         } else {
997                 ap->ap_probe = ATA_PROBE_NEED_IDENT;
998         }
999         crit_exit();
1000
1001         if (bootverbose)
1002                 kprintf("%s: END SOFTRESET\n", PORTNAME(ap));
1003
1004         return (error);
1005 }
1006
1007 /*
1008  * SILI port reset, Section 10.4.2
1009  *
1010  * This function does a hard reset of the port.  Note that the device
1011  * connected to the port could still end-up hung.
1012  */
1013 int
1014 sili_port_hardreset(struct sili_port *ap, int hard)
1015 {
1016         u_int32_t r;
1017         int     error;
1018         int     loop;
1019
1020         DPRINTF(SILI_D_VERBOSE, "%s: port reset\n", PORTNAME(ap));
1021
1022         ap->ap_state = AP_S_NORMAL;
1023         error = 0;
1024
1025         /*
1026          * Issue Device Reset.
1027          *
1028          * NOTE:  Unlike Port Reset, the port ready signal will not
1029          *        go active unless a device is established to be on
1030          *        the port.
1031          */
1032         sili_pwrite(ap, SILI_PREG_SERR, -1);
1033         sili_pwrite(ap, SILI_PREG_CTL_CLR, SILI_PREG_CTL_PMA);
1034         sili_pwrite(ap, SILI_PREG_CTL_CLR, SILI_PREG_CTL_RESUME);
1035         sili_pwrite(ap, SILI_PREG_CTL_SET, SILI_PREG_CTL_DEVRESET);
1036         if (sili_pwait_clr(ap, SILI_PREG_CTL_SET, SILI_PREG_CTL_DEVRESET)) {
1037                 kprintf("%s: hardreset failed to clear\n", PORTNAME(ap));
1038         }
1039
1040         /*
1041          * Try to determine if there is a device on the port.
1042          *
1043          * Give the device 3/10 second to at least be detected.
1044          */
1045         loop = 300;
1046         while (loop > 0) {
1047                 r = sili_pread(ap, SILI_PREG_SSTS);
1048                 if (r & SILI_PREG_SSTS_DET)
1049                         break;
1050                 loop -= sili_os_softsleep();
1051         }
1052         if (loop <= 0) {
1053                 if (bootverbose) {
1054                         kprintf("%s: Port appears to be unplugged\n",
1055                                 PORTNAME(ap));
1056                 }
1057                 error = ENODEV;
1058         }
1059
1060         /*
1061          * There is something on the port.  Give the device 3 seconds
1062          * to fully negotiate.
1063          */
1064         if (error == 0 &&
1065             sili_pwait_eq(ap, 3000, SILI_PREG_SSTS,
1066                           SILI_PREG_SSTS_DET, SILI_PREG_SSTS_DET_DEV)) {
1067                 if (bootverbose) {
1068                         kprintf("%s: Device may be powered down\n",
1069                                 PORTNAME(ap));
1070                 }
1071                 error = ENODEV;
1072         }
1073
1074         /*
1075          * Wait for the port to become ready.
1076          *
1077          * This can take more then a second, give it 3 seconds.  If we
1078          * succeed give the device another 3ms after that.
1079          *
1080          * NOTE: Port multipliers can do two things here.  First they can
1081          *       return device-ready if a device is on target 0 and also
1082          *       return the signature for that device.  If there is no
1083          *       device on target 0 then BSY/DRQ is never cleared and
1084          *       it never comes ready.
1085          */
1086         if (error == 0 && sili_pwait_set_to(ap, 3000, SILI_PREG_STATUS,
1087                                             SILI_PREG_STATUS_READY)) {
1088                 /*
1089                  * The device is bricked or its a port multiplier and will
1090                  * not unbusy until we do the pmprobe CLO softreset sequence.
1091                  */
1092                 error = sili_port_pmprobe(ap);
1093                 if (error) {
1094                         kprintf("%s: Device will not come ready\n",
1095                                 PORTNAME(ap));
1096                 } else {
1097                         ap->ap_type = ATA_PORT_T_PM;
1098                 }
1099         } else if (error == 0) {
1100                 /*
1101                  * The sili's hardreset doesn't return a signature (does it)?
1102                  * In anycase, set the type so the signature gets set by
1103                  * the softreset stage.
1104                  */
1105                 error = sili_port_pmprobe(ap);
1106                 if (error) {
1107                         ap->ap_type = ATA_PORT_T_NONE;
1108                         error = 0;
1109                 } else {
1110                         ap->ap_type = ATA_PORT_T_PM;
1111                         kprintf("%s: Port multiplier detected\n",
1112                                 PORTNAME(ap));
1113                 }
1114         }
1115
1116         /*
1117          * hard-stop the port if we failed.  This will set ap_probe
1118          * to FAILED.
1119          */
1120         if (error) {
1121                 sili_port_hardstop(ap);
1122                 /* ap_probe set to failed */
1123         } else {
1124                 if (ap->ap_type == ATA_PORT_T_PM)
1125                         ap->ap_probe = ATA_PROBE_GOOD;
1126                 else
1127                         ap->ap_probe = ATA_PROBE_NEED_SOFT_RESET;
1128         }
1129         return (error);
1130 }
1131
1132 /*
1133  * SILI port multiplier probe.  This routine is run by the hardreset code
1134  * if it gets past the device detect.
1135  *
1136  * All we do here is call sili_pm_softreset().  The Sili chip does all the
1137  * hard work for us.
1138  *
1139  * Return 0 on success, non-zero on failure.
1140  */
1141 int
1142 sili_port_pmprobe(struct sili_port *ap)
1143 {
1144         struct ata_port *at;
1145         int error;
1146         int i;
1147
1148         /*
1149          * If we don't support port multipliers don't try to detect one.
1150          */
1151         if ((ap->ap_sc->sc_flags & SILI_F_SPM) == 0)
1152                 return (ENODEV);
1153
1154         /*
1155          * The port may be unhappy from its hardreset if there's a PM
1156          * but no device at target 0.  If we try to shove the softreset
1157          * for target 15 down its throat it will pop a gasket.
1158          *
1159          * Reiniting the port.. kind of a soft reset of its command
1160          * processor which otherwise does not effect the port registers,
1161          * seems to fix the problem.
1162          */
1163         sili_pwrite(ap, SILI_PREG_CTL_SET, SILI_PREG_CTL_PMA);
1164         sili_port_reinit(ap);
1165         ap->ap_state = AP_S_NORMAL;
1166         error = sili_pm_softreset(ap, 15);
1167         if (error == 0) {
1168                 ap->ap_ata[15].at_probe = ATA_PROBE_GOOD;
1169         } else {
1170                 error = EBUSY;
1171         }
1172
1173         kprintf("PMPROBE3 %d\n", error);
1174
1175         if (error == 0 && sili_pm_identify(ap)) {
1176                 kprintf("%s: PM - cannot identify port multiplier\n",
1177                         PORTNAME(ap));
1178                 error = EBUSY;
1179         }
1180         kprintf("PMPROBE3 %d %d %d\n", error, ap->ap_probe, ap->ap_state);
1181
1182         /*
1183          * If we probed the PM reset the state for the targets behind
1184          * it so they get probed by the state machine.
1185          */
1186         if (error == 0) {
1187                 for (i = 0; i < SILI_MAX_PMPORTS; ++i) {
1188                         at = &ap->ap_ata[i];
1189                         at->at_probe = ATA_PROBE_NEED_INIT;
1190                         at->at_features |= ATA_PORT_F_RESCAN;
1191                         at->at_features &= ~ATA_PORT_F_READLOG;
1192                 }
1193         }
1194
1195         /*
1196          * If we failed turn off PMA, otherwise identify the port multiplier.
1197          * CAM will iterate the devices.
1198          */
1199         if (error)
1200                 sili_pwrite(ap, SILI_PREG_CTL_CLR, SILI_PREG_CTL_PMA);
1201         return(error);
1202 }
1203
1204 /*
1205  * Hard-stop on hot-swap device removal.  See 10.10.1
1206  *
1207  * Place the port in a mode that will allow it to detect hot-swap insertions.
1208  * This is a bit imprecise because just setting-up SCTL to DET_INIT doesn't
1209  * seem to do the job.
1210  */
1211 void
1212 sili_port_hardstop(struct sili_port *ap)
1213 {
1214         struct sili_ccb *ccb;
1215         struct ata_port *at;
1216         int i;
1217         int slot;
1218
1219         ap->ap_state = AP_S_FATAL_ERROR;
1220         ap->ap_probe = ATA_PROBE_FAILED;
1221         ap->ap_type = ATA_PORT_T_NONE;
1222
1223         /*
1224          * Clean up AT sub-ports on SATA port.
1225          */
1226         for (i = 0; ap->ap_ata && i < SILI_MAX_PMPORTS; ++i) {
1227                 at = &ap->ap_ata[i];
1228                 at->at_type = ATA_PORT_T_NONE;
1229                 at->at_probe = ATA_PROBE_FAILED;
1230                 at->at_features &= ~ATA_PORT_F_READLOG;
1231         }
1232
1233         /*
1234          * Kill the port.  Don't bother waiting for it to transition
1235          * back up.
1236          */
1237         sili_pwrite(ap, SILI_PREG_CTL_SET, SILI_PREG_CTL_RESET);
1238         if (sili_pread(ap, SILI_PREG_STATUS) & SILI_PREG_STATUS_READY) {
1239                 kprintf("%s: Port will not go into reset\n",
1240                         PORTNAME(ap));
1241         }
1242         sili_os_sleep(10);
1243         sili_pwrite(ap, SILI_PREG_CTL_CLR, SILI_PREG_CTL_RESUME);
1244         sili_pwrite(ap, SILI_PREG_CTL_CLR, SILI_PREG_CTL_RESET);
1245
1246         /*
1247          * Turn off port-multiplier control bit
1248          */
1249         sili_pwrite(ap, SILI_PREG_CTL_CLR, SILI_PREG_CTL_PMA);
1250
1251         /*
1252          * Clean up the command list.
1253          */
1254         while (ap->ap_active) {
1255                 slot = ffs(ap->ap_active) - 1;
1256                 ap->ap_active &= ~(1 << slot);
1257                 ap->ap_expired &= ~(1 << slot);
1258                 --ap->ap_active_cnt;
1259                 ccb = &ap->ap_ccbs[slot];
1260                 if (ccb->ccb_xa.flags & ATA_F_TIMEOUT_RUNNING) {
1261                         callout_stop(&ccb->ccb_timeout);
1262                         ccb->ccb_xa.flags &= ~ATA_F_TIMEOUT_RUNNING;
1263                 }
1264                 ccb->ccb_xa.flags &= ~(ATA_F_TIMEOUT_DESIRED |
1265                                        ATA_F_TIMEOUT_EXPIRED);
1266                 ccb->ccb_xa.state = ATA_S_TIMEOUT;
1267                 ccb->ccb_done(ccb);
1268                 ccb->ccb_xa.complete(&ccb->ccb_xa);
1269         }
1270         while ((ccb = TAILQ_FIRST(&ap->ap_ccb_pending)) != NULL) {
1271                 TAILQ_REMOVE(&ap->ap_ccb_pending, ccb, ccb_entry);
1272                 ccb->ccb_xa.state = ATA_S_TIMEOUT;
1273                 ccb->ccb_xa.flags &= ~ATA_F_TIMEOUT_DESIRED;
1274                 ccb->ccb_done(ccb);
1275                 ccb->ccb_xa.complete(&ccb->ccb_xa);
1276         }
1277         KKASSERT(ap->ap_active_cnt == 0);
1278
1279         /*
1280          * Put the port into a listen mode, we want to get insertion/removal
1281          * events.
1282          */
1283         sili_port_listen(ap);
1284 }
1285
1286 /*
1287  * Place port into a listen mode for hotplug events only.  The port has
1288  * already been reset and the command processor may not be ready due
1289  * to the lack of a device.
1290  */
1291 void
1292 sili_port_listen(struct sili_port *ap)
1293 {
1294         u_int32_t data;
1295
1296 #if 1
1297         data = SILI_PREG_SCTL_SPM_NONE |
1298                SILI_PREG_SCTL_IPM_NONE |
1299                SILI_PREG_SCTL_SPD_NONE |
1300                SILI_PREG_SCTL_DET_INIT;
1301         if (SiliForceGen1 & (1 << ap->ap_num)) {
1302                 data &= ~SILI_PREG_SCTL_SPD_NONE;
1303                 data |= SILI_PREG_SCTL_SPD_GEN1;
1304         }
1305 #endif
1306         sili_pwrite(ap, SILI_PREG_SERR, -1);
1307         sili_pwrite(ap, SILI_PREG_INT_ENABLE, SILI_PREG_INT_PHYRDYCHG |
1308                                               SILI_PREG_INT_DEVEXCHG);
1309 }
1310
1311 /*
1312  * Figure out what type of device is connected to the port, ATAPI or
1313  * DISK.
1314  */
1315 int
1316 sili_port_signature(struct sili_port *ap, struct ata_port *at, u_int32_t sig)
1317 {
1318         if (bootverbose)
1319                 kprintf("%s: sig %08x\n", ATANAME(ap, at), sig);
1320         if ((sig & 0xffff0000) == (SATA_SIGNATURE_ATAPI & 0xffff0000)) {
1321                 return(ATA_PORT_T_ATAPI);
1322         } else if ((sig & 0xffff0000) ==
1323                  (SATA_SIGNATURE_PORT_MULTIPLIER & 0xffff0000)) {
1324                 return(ATA_PORT_T_PM);
1325         } else {
1326                 return(ATA_PORT_T_DISK);
1327         }
1328 }
1329
1330 /*
1331  * Load the DMA descriptor table for a CCB's buffer.
1332  *
1333  * NOTE: ATA_F_PIO is auto-selected by sili part.
1334  */
1335 int
1336 sili_load_prb(struct sili_ccb *ccb)
1337 {
1338         struct sili_port                *ap = ccb->ccb_port;
1339         struct sili_softc               *sc = ap->ap_sc;
1340         struct ata_xfer                 *xa = &ccb->ccb_xa;
1341         struct sili_prb                 *prb = ccb->ccb_prb;
1342         struct sili_sge                 *sge;
1343         bus_dmamap_t                    dmap = ccb->ccb_dmamap;
1344         int                             error;
1345
1346         /*
1347          * Set up the PRB.  The PRB contains 2 SGE's (1 if it is an ATAPI
1348          * command).  The SGE must be set up to link to the rest of our
1349          * SGE array, in blocks of four SGEs (a SGE table) starting at
1350          */
1351         prb->prb_xfer_count = 0;
1352         prb->prb_control = 0;
1353         prb->prb_override = 0;
1354         sge = (ccb->ccb_xa.flags & ATA_F_PACKET) ?
1355                 &prb->prb_sge_packet : &prb->prb_sge_normal;
1356         if (xa->datalen == 0) {
1357                 sge->sge_flags = SILI_SGE_FLAGS_TRM | SILI_SGE_FLAGS_DRD;
1358                 sge->sge_count = 0;
1359                 return (0);
1360         }
1361
1362         if (ccb->ccb_xa.flags & ATA_F_READ)
1363                 prb->prb_control |= SILI_PRB_CTRL_READ;
1364         if (ccb->ccb_xa.flags & ATA_F_WRITE)
1365                 prb->prb_control |= SILI_PRB_CTRL_WRITE;
1366         sge->sge_flags = SILI_SGE_FLAGS_LNK;
1367         sge->sge_count = 0;
1368         sge->sge_paddr = ccb->ccb_prb_paddr +
1369                          offsetof(struct sili_prb, prb_sge[0]);
1370
1371         /*
1372          * Load our sge array.
1373          */
1374         error = bus_dmamap_load(sc->sc_tag_data, dmap,
1375                                 xa->data, xa->datalen,
1376                                 sili_load_prb_callback,
1377                                 ccb,
1378                                 ((xa->flags & ATA_F_NOWAIT) ?
1379                                     BUS_DMA_NOWAIT : BUS_DMA_WAITOK));
1380         if (error != 0) {
1381                 kprintf("%s: error %d loading dmamap\n", PORTNAME(ap), error);
1382                 return (1);
1383         }
1384
1385         bus_dmamap_sync(sc->sc_tag_data, dmap,
1386                         (xa->flags & ATA_F_READ) ?
1387                             BUS_DMASYNC_PREREAD : BUS_DMASYNC_PREWRITE);
1388
1389         return (0);
1390
1391 #ifdef DIAGNOSTIC
1392 diagerr:
1393         bus_dmamap_unload(sc->sc_tag_data, dmap);
1394         return (1);
1395 #endif
1396 }
1397
1398 /*
1399  * Callback from BUSDMA system to load the segment list.
1400  *
1401  * The scatter/gather table is loaded by the sili chip in blocks of
1402  * four SGE's.  If a continuance is required the last entry in each
1403  * block must point to the next block.
1404  */
1405 static
1406 void
1407 sili_load_prb_callback(void *info, bus_dma_segment_t *segs, int nsegs,
1408                         int error)
1409 {
1410         struct sili_ccb *ccb = info;
1411         struct sili_sge *sge;
1412         int sgi;
1413
1414         KKASSERT(nsegs <= SILI_MAX_SGET);
1415
1416         sgi = 0;
1417         sge = &ccb->ccb_prb->prb_sge[0];
1418         while (nsegs) {
1419                 if ((sgi & 3) == 3) {
1420                         sge->sge_paddr = htole64(ccb->ccb_prb_paddr +
1421                                                  offsetof(struct sili_prb,
1422                                                         prb_sge[sgi + 1]));
1423                         sge->sge_count = 0;
1424                         sge->sge_flags = SILI_SGE_FLAGS_LNK;
1425                 } else {
1426                         sge->sge_paddr = htole64(segs->ds_addr);
1427                         sge->sge_count = htole32(segs->ds_len);
1428                         sge->sge_flags = 0;
1429                         --nsegs;
1430                         ++segs;
1431                 }
1432                 ++sge;
1433                 ++sgi;
1434         }
1435         --sge;
1436         sge->sge_flags |= SILI_SGE_FLAGS_TRM;
1437 }
1438
1439 void
1440 sili_unload_prb(struct sili_ccb *ccb)
1441 {
1442         struct sili_port                *ap = ccb->ccb_port;
1443         struct sili_softc               *sc = ap->ap_sc;
1444         struct ata_xfer                 *xa = &ccb->ccb_xa;
1445         bus_dmamap_t                    dmap = ccb->ccb_dmamap;
1446
1447         if (xa->datalen != 0) {
1448                 bus_dmamap_sync(sc->sc_tag_data, dmap,
1449                                 (xa->flags & ATA_F_READ) ?
1450                                 BUS_DMASYNC_POSTREAD : BUS_DMASYNC_POSTWRITE);
1451
1452                 bus_dmamap_unload(sc->sc_tag_data, dmap);
1453
1454                 if (ccb->ccb_xa.flags & ATA_F_NCQ)
1455                         xa->resid = 0;
1456                 else
1457                         xa->resid = xa->datalen -
1458                                     le32toh(ccb->ccb_prb->prb_xfer_count);
1459         }
1460 }
1461
1462 /*
1463  * Start a command and poll for completion.
1464  *
1465  * timeout is in ms and only counts once the command gets on-chip.
1466  *
1467  * Returns ATA_S_* state, compare against ATA_S_COMPLETE to determine
1468  * that no error occured.
1469  *
1470  * NOTE: If the caller specifies a NULL timeout function the caller is
1471  *       responsible for clearing hardware state on failure, but we will
1472  *       deal with removing the ccb from any pending queue.
1473  *
1474  * NOTE: NCQ should never be used with this function.
1475  *
1476  * NOTE: If the port is in a failed state and stopped we do not try
1477  *       to activate the ccb.
1478  */
1479 int
1480 sili_poll(struct sili_ccb *ccb, int timeout,
1481           void (*timeout_fn)(struct sili_ccb *))
1482 {
1483         struct sili_port *ap = ccb->ccb_port;
1484
1485         if (ccb->ccb_port->ap_state == AP_S_FATAL_ERROR) {
1486                 ccb->ccb_xa.state = ATA_S_ERROR;
1487                 return(ccb->ccb_xa.state);
1488         }
1489
1490         sili_start(ccb);
1491
1492         do {
1493                 sili_port_intr(ap, 1);
1494                 switch(ccb->ccb_xa.state) {
1495                 case ATA_S_ONCHIP:
1496                         timeout -= sili_os_softsleep();
1497                         break;
1498                 case ATA_S_PENDING:
1499                         /*
1500                          * The packet can get stuck on the pending queue
1501                          * if the port refuses to come ready.
1502                          */
1503                         if (AP_F_EXCLUSIVE_ACCESS)
1504                                 timeout -= sili_os_softsleep();
1505                         else
1506                                 sili_os_softsleep();
1507                         sili_check_active_timeouts(ap);
1508                         break;
1509                 default:
1510                         return (ccb->ccb_xa.state);
1511                 }
1512         } while (timeout > 0);
1513
1514         kprintf("%s: Poll timeout slot %d\n",
1515                 ATANAME(ap, ccb->ccb_xa.at),
1516                 ccb->ccb_slot);
1517
1518         timeout_fn(ccb);
1519
1520         return(ccb->ccb_xa.state);
1521 }
1522
1523 /*
1524  * When polling we have to check if the currently active CCB(s)
1525  * have timed out as the callout will be deadlocked while we
1526  * hold the port lock.
1527  */
1528 void
1529 sili_check_active_timeouts(struct sili_port *ap)
1530 {
1531         struct sili_ccb *ccb;
1532         u_int32_t mask;
1533         int tag;
1534
1535         mask = ap->ap_active;
1536         while (mask) {
1537                 tag = ffs(mask) - 1;
1538                 mask &= ~(1 << tag);
1539                 ccb = &ap->ap_ccbs[tag];
1540                 if (ccb->ccb_xa.flags & ATA_F_TIMEOUT_EXPIRED) {
1541                         sili_core_timeout(ccb);
1542                 }
1543         }
1544 }
1545
1546 static
1547 __inline
1548 void
1549 sili_start_timeout(struct sili_ccb *ccb)
1550 {
1551         if (ccb->ccb_xa.flags & ATA_F_TIMEOUT_DESIRED) {
1552                 ccb->ccb_xa.flags |= ATA_F_TIMEOUT_RUNNING;
1553                 callout_reset(&ccb->ccb_timeout,
1554                               (ccb->ccb_xa.timeout * hz + 999) / 1000,
1555                               sili_ata_cmd_timeout_unserialized, ccb);
1556         }
1557 }
1558
1559 void
1560 sili_start(struct sili_ccb *ccb)
1561 {
1562         struct sili_port                *ap = ccb->ccb_port;
1563 #if 0
1564         struct sili_softc               *sc = ap->ap_sc;
1565 #endif
1566
1567         KKASSERT(ccb->ccb_xa.state == ATA_S_PENDING);
1568
1569         /*
1570          * Sync our SGE table and PRB
1571          */
1572         bus_dmamap_sync(ap->ap_dmamem_prbs->adm_tag,
1573                         ap->ap_dmamem_prbs->adm_map,
1574                         BUS_DMASYNC_PREWRITE);
1575
1576         /*
1577          * XXX dmamap for PRB XXX  BUS_DMASYNC_PREWRITE
1578          */
1579
1580         /*
1581          * Controller will update shared memory!
1582          * XXX bus_dmamap_sync ... BUS_DMASYNC_PREREAD ...
1583          */
1584         /* Prepare RFIS area for write by controller */
1585
1586         /*
1587          * There's no point trying to optimize this, it only shaves a few
1588          * nanoseconds so just queue the command and call our generic issue.
1589          */
1590         sili_issue_pending_commands(ap, ccb);
1591 }
1592
1593 /*
1594  * While holding the port lock acquire exclusive access to the port.
1595  *
1596  * This is used when running the state machine to initialize and identify
1597  * targets over a port multiplier.  Setting exclusive access prevents
1598  * sili_port_intr() from activating any requests sitting on the pending
1599  * queue.
1600  */
1601 void
1602 sili_beg_exclusive_access(struct sili_port *ap, struct ata_port *at)
1603 {
1604         KKASSERT((ap->ap_flags & AP_F_EXCLUSIVE_ACCESS) == 0);
1605         ap->ap_flags |= AP_F_EXCLUSIVE_ACCESS;
1606         while (ap->ap_active) {
1607                 sili_port_intr(ap, 1);
1608                 sili_os_softsleep();
1609         }
1610 }
1611
1612 void
1613 sili_end_exclusive_access(struct sili_port *ap, struct ata_port *at)
1614 {
1615         KKASSERT((ap->ap_flags & AP_F_EXCLUSIVE_ACCESS) != 0);
1616         ap->ap_flags &= ~AP_F_EXCLUSIVE_ACCESS;
1617         sili_issue_pending_commands(ap, NULL);
1618 }
1619
1620 /*
1621  * If ccb is not NULL enqueue and/or issue it.
1622  *
1623  * If ccb is NULL issue whatever we can from the queue.  However, nothing
1624  * new is issued if the exclusive access flag is set or expired ccb's are
1625  * present.
1626  *
1627  * If existing commands are still active (ap_active) we can only
1628  * issue matching new commands.
1629  */
1630 void
1631 sili_issue_pending_commands(struct sili_port *ap, struct sili_ccb *ccb)
1632 {
1633         /*
1634          * Enqueue the ccb.
1635          *
1636          * If just running the queue and in exclusive access mode we
1637          * just return.  Also in this case if there are any expired ccb's
1638          * we want to clear the queue so the port can be safely stopped.
1639          *
1640          * XXX sili chip - expiration needs to be per-target if PM supports
1641          *      FBSS?
1642          */
1643         if (ccb) {
1644                 TAILQ_INSERT_TAIL(&ap->ap_ccb_pending, ccb, ccb_entry);
1645         } else if ((ap->ap_flags & AP_F_EXCLUSIVE_ACCESS) || ap->ap_expired) {
1646                 return;
1647         }
1648
1649         /*
1650          * Pull the next ccb off the queue and run it if possible.
1651          * If the port is not ready to accept commands enable the
1652          * ready interrupt instead of starting a new command.
1653          *
1654          * XXX limit ncqdepth for attached devices behind PM
1655          */
1656         while ((ccb = TAILQ_FIRST(&ap->ap_ccb_pending)) != NULL) {
1657                 if ((sili_pread(ap, SILI_PREG_STATUS) &
1658                     SILI_PREG_STATUS_READY) == 0) {
1659                         kprintf("%s: slot %d NOT READY\n",
1660                                 ATANAME(ap, ccb->ccb_xa.at), ccb->ccb_slot);
1661                         sili_pwrite(ap, SILI_PREG_INT_ENABLE,
1662                                     SILI_PREG_INT_READY);
1663                         break;
1664                 }
1665                 TAILQ_REMOVE(&ap->ap_ccb_pending, ccb, ccb_entry);
1666                 ccb->ccb_xa.state = ATA_S_ONCHIP;
1667                 ap->ap_active |= 1 << ccb->ccb_slot;
1668                 ap->ap_active_cnt++;
1669
1670                 /*
1671                  * We can't use the CMD_FIFO method because it requires us
1672                  * building the PRB in the LRAM, and the LRAM is buggy.  So
1673                  * we use host memory for the PRB.
1674                  */
1675                 sili_pwrite(ap, SILI_PREG_CMDACT(ccb->ccb_slot),
1676                             (u_int32_t)ccb->ccb_prb_paddr);
1677                 sili_pwrite(ap, SILI_PREG_CMDACT(ccb->ccb_slot) + 4,
1678                             (u_int32_t)(ccb->ccb_prb_paddr >> 32));
1679                 /* sili_pwrite(ap, SILI_PREG_CMD_FIFO, ccb->ccb_slot); */
1680                 sili_start_timeout(ccb);
1681         }
1682 }
1683
1684 void
1685 sili_intr(void *arg)
1686 {
1687         struct sili_softc       *sc = arg;
1688         struct sili_port        *ap;
1689         u_int32_t               gint;
1690         int                     port;
1691
1692         /*
1693          * Check if the master enable is up, and whether any interrupts are
1694          * pending.
1695          *
1696          * Clear the ints we got.
1697          */
1698         if ((sc->sc_flags & SILI_F_INT_GOOD) == 0)
1699                 return;
1700         gint = sili_read(sc, SILI_REG_GINT);
1701         if (gint == 0 || gint == 0xffffffff)
1702                 return;
1703         sili_write(sc, SILI_REG_GINT, gint);
1704
1705         /*
1706          * Process interrupts for each port in a non-blocking fashion.
1707          */
1708         while (gint & SILI_REG_GINT_PORTMASK) {
1709                 port = ffs(gint) - 1;
1710                 ap = sc->sc_ports[port];
1711                 if (ap) {
1712                         if (sili_os_lock_port_nb(ap) == 0) {
1713                                 sili_port_intr(ap, 0);
1714                                 sili_os_unlock_port(ap);
1715                         } else {
1716                                 sili_port_interrupt_redisable(ap);
1717                                 sili_os_signal_port_thread(ap, AP_SIGF_PORTINT);
1718                         }
1719                 }
1720                 gint &= ~(1 << port);
1721         }
1722 }
1723
1724 /*
1725  * Core called from helper thread.
1726  */
1727 void
1728 sili_port_thread_core(struct sili_port *ap, int mask)
1729 {
1730         /*
1731          * Process any expired timedouts.
1732          */
1733         sili_os_lock_port(ap);
1734         if (mask & AP_SIGF_TIMEOUT) {
1735                 sili_check_active_timeouts(ap);
1736         }
1737
1738         /*
1739          * Process port interrupts which require a higher level of
1740          * intervention.
1741          */
1742         if (mask & AP_SIGF_PORTINT) {
1743                 sili_port_intr(ap, 1);
1744                 sili_port_interrupt_reenable(ap);
1745                 sili_os_unlock_port(ap);
1746         } else {
1747                 sili_os_unlock_port(ap);
1748         }
1749 }
1750
1751 /*
1752  * Core per-port interrupt handler.
1753  *
1754  * If blockable is 0 we cannot call sili_os_sleep() at all and we can only
1755  * deal with normal command completions which do not require blocking.
1756  */
1757 void
1758 sili_port_intr(struct sili_port *ap, int blockable)
1759 {
1760         struct sili_softc       *sc = ap->ap_sc;
1761         u_int32_t               is;
1762         int                     slot;
1763         struct sili_ccb         *ccb = NULL;
1764         struct ata_port         *ccb_at = NULL;
1765 #ifdef DIAGNOSTIC
1766         u_int32_t               tmp;
1767 #endif
1768         u_int32_t               active;
1769         const u_int32_t         blockable_mask = SILI_PREG_IST_PHYRDYCHG |
1770                                                  SILI_PREG_IST_DEVEXCHG |
1771                                                  SILI_PREG_IST_CERROR |
1772                                                  SILI_PREG_IST_DECODE |
1773                                                  SILI_PREG_IST_CRC |
1774                                                  SILI_PREG_IST_HANDSHK;
1775         const u_int32_t         fatal_mask     = SILI_PREG_IST_PHYRDYCHG |
1776                                                  SILI_PREG_IST_DEVEXCHG |
1777                                                  SILI_PREG_IST_DECODE |
1778                                                  SILI_PREG_IST_CRC |
1779                                                  SILI_PREG_IST_HANDSHK;
1780
1781         enum { NEED_NOTHING, NEED_HOTPLUG_INSERT,
1782                NEED_HOTPLUG_REMOVE } need = NEED_NOTHING;
1783
1784         /*
1785          * NOTE: CCOMPLETE was automatically cleared when we read INT_STATUS.
1786          */
1787         is = sili_pread(ap, SILI_PREG_INT_STATUS);
1788         is &= SILI_PREG_IST_MASK;
1789         if (is & SILI_PREG_IST_CCOMPLETE)
1790                 sili_pwrite(ap, SILI_PREG_INT_STATUS, SILI_PREG_IST_CCOMPLETE);
1791
1792         /*
1793          * If we can't block then we can't handle these here.  Disable
1794          * the interrupts in question so we don't live-lock, the helper
1795          * thread will re-enable them.
1796          *
1797          * If the port is in a completely failed state we do not want
1798          * to drop through to failed-command-processing if blockable is 0,
1799          * just let the thread deal with it all.
1800          *
1801          * Otherwise we fall through and still handle DHRS and any commands
1802          * which completed normally.  Even if we are errored we haven't
1803          * stopped the port yet so CI/SACT are still good.
1804          */
1805         if (blockable == 0) {
1806                 if (ap->ap_state == AP_S_FATAL_ERROR) {
1807                         sili_port_interrupt_redisable(ap);
1808                         sili_os_signal_port_thread(ap, AP_SIGF_PORTINT);
1809                         /*is &= ~blockable_mask;*/
1810                         return;
1811                 }
1812                 if (is & blockable_mask) {
1813                         sili_port_interrupt_redisable(ap);
1814                         sili_os_signal_port_thread(ap, AP_SIGF_PORTINT);
1815                         /*is &= ~blockable_mask;*/
1816                         return;
1817                 }
1818         }
1819
1820         if (is & SILI_PREG_IST_CERROR) {
1821                 /*
1822                  * Command failed (blockable).
1823                  *
1824                  * This stops command processing.  We can extract the PM
1825                  * target from the PMP field in SILI_PREG_CONTEXT.  The
1826                  * tag is not necessarily valid so don't use that.
1827                  *
1828                  * We must then expire all CCB's for that target and resume
1829                  * processing if any other targets have active commands.
1830                  * Particular error codes can be recovered by reading the LOG
1831                  * page.
1832                  *
1833                  * The expire handling code will do the rest, which is
1834                  * basically to reset the port once the only active
1835                  * commands remaining are all expired.
1836                  */
1837                 u_int32_t error;
1838                 int       target;
1839                 int       resume = 1;
1840
1841                 target = (sili_pread(ap, SILI_PREG_CONTEXT) >>
1842                           SILI_PREG_CONTEXT_PMPORT_SHIFT) &
1843                           SILI_PREG_CONTEXT_PMPORT_MASK;
1844                 sili_pwrite(ap, SILI_PREG_INT_STATUS, SILI_PREG_IST_CERROR);
1845                 active = ap->ap_active & ~ap->ap_expired;
1846                 error = sili_pread(ap, SILI_PREG_CERROR);
1847                 kprintf("%s.%d target error %d active=%08x hactive=%08x "
1848                         "SERR=%b\n",
1849                         PORTNAME(ap), target, error,
1850                         active, sili_pread(ap, SILI_PREG_SLOTST),
1851                         sili_pread(ap, SILI_PREG_SERR), SILI_PFMT_SERR);
1852
1853                 while (active) {
1854                         slot = ffs(active) - 1;
1855                         ccb = &ap->ap_ccbs[slot];
1856                         if ((ccb_at = ccb->ccb_xa.at) == NULL)
1857                                 ccb_at = &ap->ap_ata[0];
1858                         if (target == ccb_at->at_target) {
1859                                 kprintf("%s kill ccb slot %d\n",
1860                                         ATANAME(ap, ccb->ccb_xa.at), slot);
1861                                 if (ccb->ccb_xa.flags & ATA_F_NCQ &&
1862                                     (error == SILI_PREG_CERROR_DEVICE ||
1863                                      error == SILI_PREG_CERROR_SDBERROR)) {
1864                                         ccb_at->at_features |= ATA_PORT_F_READLOG;
1865                                 }
1866                                 if (sili_core_timeout(ccb) == 0)
1867                                         resume = 0;
1868                         }
1869                         active &= ~(1 << slot);
1870                 }
1871
1872                 /*
1873                  * Resume will be 0 if the timeout reinited and restarted
1874                  * the port.  Otherwise we resume the port to allow other
1875                  * commands to complete.
1876                  */
1877                 kprintf("%s.%d remain=%08x resume=%d\n",
1878                         PORTNAME(ap), target,
1879                         ap->ap_active & ~ap->ap_expired, resume);
1880                 if (resume)
1881                         sili_pwrite(ap, SILI_PREG_CTL_SET, SILI_PREG_CTL_RESUME);
1882         }
1883
1884         /*
1885          * Device notification to us (non-blocking)
1886          *
1887          * This is interrupt status SILIPREG_IST_SDB
1888          *
1889          * NOTE!  On some parts notification bits can get set without
1890          *        generating an interrupt.  It is unclear whether this is
1891          *        a bug in the PM (sending a DTOH device setbits with 'N' set
1892          *        and 'I' not set), or a bug in the host controller.
1893          *
1894          *        It only seems to occur under load.
1895          */
1896         if (sc->sc_flags & SILI_F_SSNTF) {
1897                 u_int32_t data;
1898                 const char *xstr;
1899
1900                 data = sili_pread(ap, SILI_PREG_SNTF);
1901                 if (is & SILI_PREG_IST_SDB) {
1902                         sili_pwrite(ap, SILI_PREG_INT_STATUS,
1903                                     SILI_PREG_IST_SDB);
1904                         is &= ~SILI_PREG_IST_SDB;
1905                         xstr = " (no SDBS!)";
1906                 } else {
1907                         xstr = "";
1908                 }
1909                 if (data) {
1910                         kprintf("%s: NOTIFY %08x%s\n",
1911                                 PORTNAME(ap), data, xstr);
1912                         sili_pwrite(ap, SILI_PREG_SNTF, data);
1913                         sili_cam_changed(ap, NULL, -1);
1914                 }
1915         }
1916
1917         /*
1918          * Port change (hot-plug) (blockable).
1919          *
1920          * A PCS interrupt will occur on hot-plug once communication is
1921          * established.
1922          *
1923          * A PRCS interrupt will occur on hot-unplug (and possibly also
1924          * on hot-plug).
1925          *
1926          * XXX We can then check the CPS (Cold Presence State) bit, if
1927          * supported, to determine if a device is plugged in or not and do
1928          * the right thing.
1929          *
1930          * WARNING:  A PCS interrupt is cleared by clearing DIAG_X, and
1931          *           can also occur if an unsolicited COMINIT is received.
1932          *           If this occurs command processing is automatically
1933          *           stopped (CR goes inactive) and the port must be stopped
1934          *           and restarted.
1935          */
1936         if (is & (SILI_PREG_IST_PHYRDYCHG | SILI_PREG_IST_DEVEXCHG)) {
1937                 /* XXX */
1938                 sili_pwrite(ap, SILI_PREG_SERR,
1939                         (SILI_PREG_SERR_DIAG_N | SILI_PREG_SERR_DIAG_X));
1940                 sili_pwrite(ap, SILI_PREG_INT_STATUS,
1941                     is & (SILI_PREG_IST_PHYRDYCHG | SILI_PREG_IST_DEVEXCHG));
1942
1943                 is &= ~(SILI_PREG_IST_PHYRDYCHG | SILI_PREG_IST_DEVEXCHG);
1944                 kprintf("%s: Port change\n", PORTNAME(ap));
1945
1946                 switch (sili_pread(ap, SILI_PREG_SSTS) & SILI_PREG_SSTS_DET) {
1947                 case SILI_PREG_SSTS_DET_DEV:
1948                         if (ap->ap_type == ATA_PORT_T_NONE &&
1949                             ap->ap_probe == ATA_PROBE_FAILED) {
1950                                 need = NEED_HOTPLUG_INSERT;
1951                                 goto fatal;
1952                         }
1953                         break;
1954                 default:
1955                         kprintf("%s: Device lost\n", PORTNAME(ap));
1956                         if (ap->ap_type != ATA_PORT_T_NONE) {
1957                                 need = NEED_HOTPLUG_REMOVE;
1958                                 goto fatal;
1959                         }
1960                         break;
1961                 }
1962         }
1963
1964         /*
1965          * Check for remaining errors - they are fatal. (blockable)
1966          */
1967         if (is & fatal_mask) {
1968                 u_int32_t serr;
1969
1970                 sili_pwrite(ap, SILI_PREG_INT_STATUS, is & fatal_mask);
1971
1972                 serr = sili_pread(ap, SILI_PREG_SERR);
1973                 kprintf("%s: Unrecoverable errors (IS: %b, SERR: %b), "
1974                         "disabling port.\n",
1975                         PORTNAME(ap),
1976                         is, SILI_PFMT_INT_STATUS,
1977                         serr, SILI_PFMT_SERR
1978                 );
1979                 is &= ~fatal_mask;
1980                 /* XXX try recovery first */
1981                 goto fatal;
1982         }
1983
1984         /*
1985          * Fail all outstanding commands if we know the port won't recover.
1986          *
1987          * We may have a ccb_at if the failed command is known and was
1988          * being sent to a device over a port multiplier (PM).  In this
1989          * case if the port itself has not completely failed we fail just
1990          * the commands related to that target.
1991          */
1992         if (ap->ap_state == AP_S_FATAL_ERROR && ap->ap_active) {
1993 fatal:
1994                 kprintf("%s: Interrupt, fatal error\n", PORTNAME(ap));
1995                 ap->ap_state = AP_S_FATAL_ERROR;
1996 /*failall:*/
1997                 /*
1998                  * Error all the active slots.  If running across a PM
1999                  * try to error out just the slots related to the target.
2000                  */
2001                 active = ap->ap_active & ~ap->ap_expired;
2002
2003                 while (active) {
2004                         slot = ffs(active) - 1;
2005                         kprintf("%s: Killing slot %d\n", PORTNAME(ap), slot);
2006                         active &= ~(1 << slot);
2007                         ccb = &ap->ap_ccbs[slot];
2008                         sili_core_timeout(ccb);
2009                 }
2010         }
2011
2012         /*
2013          * CCB completion (non blocking).
2014          *
2015          * CCB completion is detected by noticing the slot bit in
2016          * the port slot status register has cleared while the bit
2017          * is still set in our ap_active variable.
2018          *
2019          * When completing expired events we must remember to reinit
2020          * the port once everything is clear.
2021          */
2022         active = ap->ap_active & ~sili_pread(ap, SILI_PREG_SLOTST);
2023
2024         while (active) {
2025                 slot = ffs(active) - 1;
2026                 ccb = &ap->ap_ccbs[slot];
2027
2028                 DPRINTF(SILI_D_INTR, "%s: slot %d is complete%s\n",
2029                     PORTNAME(ap), slot, ccb->ccb_xa.state == ATA_S_ERROR ?
2030                     " (error)" : "");
2031
2032                 active &= ~(1 << slot);
2033
2034                 /*
2035                  * XXX sync POSTREAD for return data?
2036                  */
2037                 ap->ap_active &= ~(1 << ccb->ccb_slot);
2038                 --ap->ap_active_cnt;
2039
2040                 /*
2041                  * Complete the ccb.  If the ccb was marked expired it
2042                  * may or may not have been cleared from the port,
2043                  * make sure we mark it as having timed out.
2044                  */
2045                 if (ap->ap_expired & (1 << ccb->ccb_slot)) {
2046                         ap->ap_expired &= ~(1 << ccb->ccb_slot);
2047                         ccb->ccb_xa.state = ATA_S_TIMEOUT;
2048                         ccb->ccb_done(ccb);
2049                         ccb->ccb_xa.complete(&ccb->ccb_xa);
2050                 } else {
2051                         if (ccb->ccb_xa.state == ATA_S_ONCHIP)
2052                                 ccb->ccb_xa.state = ATA_S_COMPLETE;
2053                         ccb->ccb_done(ccb);
2054                 }
2055         }
2056         if (is & SILI_PREG_IST_READY) {
2057                 is &= ~SILI_PREG_IST_READY;
2058                 sili_pwrite(ap, SILI_PREG_INT_DISABLE, SILI_PREG_INT_READY);
2059                 sili_pwrite(ap, SILI_PREG_INT_STATUS, SILI_PREG_IST_READY);
2060         }
2061
2062         /*
2063          * If we had expired commands and were waiting for
2064          * remaining commands to complete, and they have now
2065          * completed, we can reinit the port.
2066          *
2067          * This will also clean out the expired commands.
2068          * The timeout code also calls sili_port_reinit() if
2069          * the only commands remaining after a timeout are all
2070          * now expired commands.
2071          *
2072          * Otherwise just reissue.
2073          */
2074         if (ap->ap_expired && ap->ap_active == ap->ap_expired)
2075                 sili_port_reinit(ap);
2076         else
2077                 sili_issue_pending_commands(ap, NULL);
2078
2079         /*
2080          * Cleanup.  Will not be set if non-blocking.
2081          */
2082         switch(need) {
2083         case NEED_HOTPLUG_INSERT:
2084                 /*
2085                  * A hot-plug insertion event has occured and all
2086                  * outstanding commands have already been revoked.
2087                  *
2088                  * Don't recurse if this occurs while we are
2089                  * resetting the port.
2090                  *
2091                  * Place the port in a continuous COMRESET state
2092                  * until the INIT code gets to it.
2093                  */
2094                 kprintf("%s: HOTPLUG - Device inserted\n",
2095                         PORTNAME(ap));
2096                 ap->ap_probe = ATA_PROBE_NEED_INIT;
2097                 sili_cam_changed(ap, NULL, -1);
2098                 break;
2099         case NEED_HOTPLUG_REMOVE:
2100                 /*
2101                  * A hot-plug removal event has occured and all
2102                  * outstanding commands have already been revoked.
2103                  *
2104                  * Don't recurse if this occurs while we are
2105                  * resetting the port.
2106                  */
2107                 kprintf("%s: HOTPLUG - Device removed\n",
2108                         PORTNAME(ap));
2109                 sili_port_hardstop(ap);
2110                 /* ap_probe set to failed */
2111                 sili_cam_changed(ap, NULL, -1);
2112                 break;
2113         default:
2114                 break;
2115         }
2116 }
2117
2118 struct sili_ccb *
2119 sili_get_ccb(struct sili_port *ap)
2120 {
2121         struct sili_ccb                 *ccb;
2122
2123         lockmgr(&ap->ap_ccb_lock, LK_EXCLUSIVE);
2124         ccb = TAILQ_FIRST(&ap->ap_ccb_free);
2125         if (ccb != NULL) {
2126                 KKASSERT(ccb->ccb_xa.state == ATA_S_PUT);
2127                 TAILQ_REMOVE(&ap->ap_ccb_free, ccb, ccb_entry);
2128                 ccb->ccb_xa.state = ATA_S_SETUP;
2129                 ccb->ccb_xa.at = NULL;
2130         }
2131         lockmgr(&ap->ap_ccb_lock, LK_RELEASE);
2132
2133         return (ccb);
2134 }
2135
2136 void
2137 sili_put_ccb(struct sili_ccb *ccb)
2138 {
2139         struct sili_port                *ap = ccb->ccb_port;
2140
2141 #ifdef DIAGNOSTIC
2142         if (ccb->ccb_xa.state != ATA_S_COMPLETE &&
2143             ccb->ccb_xa.state != ATA_S_TIMEOUT &&
2144             ccb->ccb_xa.state != ATA_S_ERROR) {
2145                 kprintf("%s: invalid ata_xfer state %02x in sili_put_ccb, "
2146                         "slot %d\n",
2147                         PORTNAME(ccb->ccb_port), ccb->ccb_xa.state,
2148                         ccb->ccb_slot);
2149         }
2150 #endif
2151
2152         ccb->ccb_xa.state = ATA_S_PUT;
2153         lockmgr(&ap->ap_ccb_lock, LK_EXCLUSIVE);
2154         TAILQ_INSERT_TAIL(&ap->ap_ccb_free, ccb, ccb_entry);
2155         lockmgr(&ap->ap_ccb_lock, LK_RELEASE);
2156 }
2157
2158 struct sili_ccb *
2159 sili_get_err_ccb(struct sili_port *ap)
2160 {
2161         struct sili_ccb *err_ccb;
2162
2163         KKASSERT(sili_pread(ap, SILI_PREG_CI) == 0);
2164         KKASSERT((ap->ap_flags & AP_F_ERR_CCB_RESERVED) == 0);
2165         ap->ap_flags |= AP_F_ERR_CCB_RESERVED;
2166
2167 #ifdef DIAGNOSTIC
2168         KKASSERT(ap->ap_err_busy == 0);
2169         ap->ap_err_busy = 1;
2170 #endif
2171         /*
2172          * Grab a CCB to use for error recovery.  This should never fail, as
2173          * we ask atascsi to reserve one for us at init time.
2174          */
2175         err_ccb = ap->ap_err_ccb;
2176         KKASSERT(err_ccb != NULL);
2177         err_ccb->ccb_xa.flags = 0;
2178         err_ccb->ccb_done = sili_empty_done;
2179
2180         return err_ccb;
2181 }
2182
2183 void
2184 sili_put_err_ccb(struct sili_ccb *ccb)
2185 {
2186         struct sili_port *ap = ccb->ccb_port;
2187
2188 #ifdef DIAGNOSTIC
2189         KKASSERT(ap->ap_err_busy);
2190 #endif
2191         KKASSERT((ap->ap_flags & AP_F_ERR_CCB_RESERVED) != 0);
2192
2193         KKASSERT(ccb == ap->ap_err_ccb);
2194
2195 #ifdef DIAGNOSTIC
2196         ap->ap_err_busy = 0;
2197 #endif
2198         ap->ap_flags &= ~AP_F_ERR_CCB_RESERVED;
2199 }
2200
2201 /*
2202  * Read log page to get NCQ error.
2203  */
2204 int
2205 sili_port_read_ncq_error(struct sili_port *ap, int target)
2206 {
2207         struct sili_ccb         *ccb;
2208         struct ata_fis_h2d      *fis;
2209         int                     rc = EIO;
2210
2211         DPRINTF(SILI_D_VERBOSE, "%s: read log page\n", PORTNAME(ap));
2212
2213         /* Prep error CCB for READ LOG EXT, page 10h, 1 sector. */
2214         ccb = sili_get_err_ccb(ap);
2215         ccb->ccb_done = sili_empty_done;
2216         ccb->ccb_xa.flags = ATA_F_NOWAIT | ATA_F_READ | ATA_F_POLL;
2217         ccb->ccb_xa.data = ap->ap_err_scratch;
2218         ccb->ccb_xa.datalen = 512;
2219         ccb->ccb_xa.complete = sili_dummy_done;
2220         ccb->ccb_xa.at = &ap->ap_ata[target];
2221         fis = &ccb->ccb_prb->prb_h2d;
2222         bzero(fis, sizeof(*fis));
2223
2224         fis->type = ATA_FIS_TYPE_H2D;
2225         fis->flags = ATA_H2D_FLAGS_CMD | target;
2226         fis->command = ATA_C_READ_LOG_EXT;
2227         fis->lba_low = 0x10;            /* queued error log page (10h) */
2228         fis->sector_count = 1;          /* number of sectors (1) */
2229         fis->sector_count_exp = 0;
2230         fis->lba_mid = 0;               /* starting offset */
2231         fis->lba_mid_exp = 0;
2232         fis->device = 0;
2233
2234         if (sili_load_prb(ccb) != 0) {
2235                 rc = ENOMEM;    /* XXX caller must abort all commands */
2236         } else {
2237                 ccb->ccb_xa.state = ATA_S_PENDING;
2238                 rc = sili_poll(ccb, 1000, sili_quick_timeout);
2239         }
2240
2241         /* Abort our command, if it failed, by stopping command DMA. */
2242         if (rc) {
2243                 kprintf("%s: log page read failed, slot %d was still active.\n",
2244                         ATANAME(ap, ccb->ccb_xa.at), ccb->ccb_slot);
2245         }
2246
2247         /* Done with the error CCB now. */
2248         sili_unload_prb(ccb);
2249         sili_put_err_ccb(ccb);
2250
2251         /* Extract failed register set and tags from the scratch space. */
2252         if (rc == 0) {
2253                 struct ata_log_page_10h         *log;
2254                 int                             err_slot;
2255
2256                 log = (struct ata_log_page_10h *)ap->ap_err_scratch;
2257                 if (log->err_regs.type & ATA_LOG_10H_TYPE_NOTQUEUED) {
2258                         /* Not queued bit was set - wasn't an NCQ error? */
2259                         kprintf("%s: read NCQ error page, but not an NCQ "
2260                                 "error?\n",
2261                                 PORTNAME(ap));
2262                         rc = ESRCH;
2263                 } else {
2264                         /* Copy back the log record as a D2H register FIS. */
2265                         err_slot = log->err_regs.type &
2266                                    ATA_LOG_10H_TYPE_TAG_MASK;
2267                         ccb = &ap->ap_ccbs[err_slot];
2268                         if (ap->ap_expired & (1 << ccb->ccb_slot)) {
2269                                 kprintf("%s: read NCQ error page ok\n",
2270                                         ATANAME(ap, ccb->ccb_xa.at));
2271                                 memcpy(&ccb->ccb_prb->prb_d2h, &log->err_regs,
2272                                         sizeof(struct ata_fis_d2h));
2273                                 ccb->ccb_prb->prb_d2h.type = ATA_FIS_TYPE_D2H;
2274                                 ccb->ccb_prb->prb_d2h.flags = 0;
2275                         } else {
2276                                 kprintf("%s: error log slot %d did not match a failed ccb!\n", ATANAME(ccb->ccb_port, ccb->ccb_xa.at), err_slot);
2277                         }
2278                 }
2279         }
2280
2281         return (rc);
2282 }
2283
2284 /*
2285  * Allocate memory for various structures DMAd by hardware.  The maximum
2286  * number of segments for these tags is 1 so the DMA memory will have a
2287  * single physical base address.
2288  */
2289 struct sili_dmamem *
2290 sili_dmamem_alloc(struct sili_softc *sc, bus_dma_tag_t tag)
2291 {
2292         struct sili_dmamem *adm;
2293         int     error;
2294
2295         adm = kmalloc(sizeof(*adm), M_DEVBUF, M_INTWAIT | M_ZERO);
2296
2297         error = bus_dmamem_alloc(tag, (void **)&adm->adm_kva,
2298                                  BUS_DMA_ZERO, &adm->adm_map);
2299         if (error == 0) {
2300                 adm->adm_tag = tag;
2301                 error = bus_dmamap_load(tag, adm->adm_map,
2302                                         adm->adm_kva,
2303                                         bus_dma_tag_getmaxsize(tag),
2304                                         sili_dmamem_saveseg, &adm->adm_busaddr,
2305                                         0);
2306         }
2307         if (error) {
2308                 if (adm->adm_map) {
2309                         bus_dmamap_destroy(tag, adm->adm_map);
2310                         adm->adm_map = NULL;
2311                         adm->adm_tag = NULL;
2312                         adm->adm_kva = NULL;
2313                 }
2314                 kfree(adm, M_DEVBUF);
2315                 adm = NULL;
2316         }
2317         return (adm);
2318 }
2319
2320 static
2321 void
2322 sili_dmamem_saveseg(void *info, bus_dma_segment_t *segs, int nsegs, int error)
2323 {
2324         KKASSERT(error == 0);
2325         KKASSERT(nsegs == 1);
2326         *(bus_addr_t *)info = segs->ds_addr;
2327 }
2328
2329
2330 void
2331 sili_dmamem_free(struct sili_softc *sc, struct sili_dmamem *adm)
2332 {
2333         if (adm->adm_map) {
2334                 bus_dmamap_unload(adm->adm_tag, adm->adm_map);
2335                 bus_dmamap_destroy(adm->adm_tag, adm->adm_map);
2336                 adm->adm_map = NULL;
2337                 adm->adm_tag = NULL;
2338                 adm->adm_kva = NULL;
2339         }
2340         kfree(adm, M_DEVBUF);
2341 }
2342
2343 u_int32_t
2344 sili_read(struct sili_softc *sc, bus_size_t r)
2345 {
2346         bus_space_barrier(sc->sc_iot, sc->sc_ioh, r, 4,
2347                           BUS_SPACE_BARRIER_READ);
2348         return (bus_space_read_4(sc->sc_iot, sc->sc_ioh, r));
2349 }
2350
2351 void
2352 sili_write(struct sili_softc *sc, bus_size_t r, u_int32_t v)
2353 {
2354         bus_space_write_4(sc->sc_iot, sc->sc_ioh, r, v);
2355         bus_space_barrier(sc->sc_iot, sc->sc_ioh, r, 4,
2356                           BUS_SPACE_BARRIER_WRITE);
2357 }
2358
2359 u_int32_t
2360 sili_pread(struct sili_port *ap, bus_size_t r)
2361 {
2362         bus_space_barrier(ap->ap_sc->sc_iot, ap->ap_ioh, r, 4,
2363                           BUS_SPACE_BARRIER_READ);
2364         return (bus_space_read_4(ap->ap_sc->sc_iot, ap->ap_ioh, r));
2365 }
2366
2367 void
2368 sili_pwrite(struct sili_port *ap, bus_size_t r, u_int32_t v)
2369 {
2370         bus_space_write_4(ap->ap_sc->sc_iot, ap->ap_ioh, r, v);
2371         bus_space_barrier(ap->ap_sc->sc_iot, ap->ap_ioh, r, 4,
2372                           BUS_SPACE_BARRIER_WRITE);
2373 }
2374
2375 /*
2376  * Wait up to (timeout) milliseconds for the masked port register to
2377  * match the target.
2378  *
2379  * Timeout is in milliseconds.
2380  */
2381 int
2382 sili_pwait_eq(struct sili_port *ap, int timeout,
2383               bus_size_t r, u_int32_t mask, u_int32_t target)
2384 {
2385         int     t;
2386
2387         /*
2388          * Loop hard up to 100uS
2389          */
2390         for (t = 0; t < 100; ++t) {
2391                 if ((sili_pread(ap, r) & mask) == target)
2392                         return (0);
2393                 sili_os_hardsleep(1);   /* us */
2394         }
2395
2396         do {
2397                 timeout -= sili_os_softsleep();
2398                 if ((sili_pread(ap, r) & mask) == target)
2399                         return (0);
2400         } while (timeout > 0);
2401         return (1);
2402 }
2403
2404 int
2405 sili_wait_ne(struct sili_softc *sc, bus_size_t r, u_int32_t mask,
2406              u_int32_t target)
2407 {
2408         int     t;
2409
2410         /*
2411          * Loop hard up to 100uS
2412          */
2413         for (t = 0; t < 100; ++t) {
2414                 if ((sili_read(sc, r) & mask) != target)
2415                         return (0);
2416                 sili_os_hardsleep(1);   /* us */
2417         }
2418
2419         /*
2420          * And one millisecond the slow way
2421          */
2422         t = 1000;
2423         do {
2424                 t -= sili_os_softsleep();
2425                 if ((sili_read(sc, r) & mask) != target)
2426                         return (0);
2427         } while (t > 0);
2428
2429         return (1);
2430 }
2431
2432
2433 /*
2434  * Acquire an ata transfer.
2435  *
2436  * Pass a NULL at for direct-attached transfers, and a non-NULL at for
2437  * targets that go through the port multiplier.
2438  */
2439 struct ata_xfer *
2440 sili_ata_get_xfer(struct sili_port *ap, struct ata_port *at)
2441 {
2442         struct sili_ccb         *ccb;
2443
2444         ccb = sili_get_ccb(ap);
2445         if (ccb == NULL) {
2446                 DPRINTF(SILI_D_XFER, "%s: sili_ata_get_xfer: NULL ccb\n",
2447                     PORTNAME(ap));
2448                 return (NULL);
2449         }
2450
2451         DPRINTF(SILI_D_XFER, "%s: sili_ata_get_xfer got slot %d\n",
2452             PORTNAME(ap), ccb->ccb_slot);
2453
2454         bzero(ccb->ccb_xa.fis, sizeof(*ccb->ccb_xa.fis));
2455         ccb->ccb_xa.at = at;
2456         ccb->ccb_xa.fis->type = ATA_FIS_TYPE_H2D;
2457
2458         return (&ccb->ccb_xa);
2459 }
2460
2461 void
2462 sili_ata_put_xfer(struct ata_xfer *xa)
2463 {
2464         struct sili_ccb                 *ccb = (struct sili_ccb *)xa;
2465
2466         DPRINTF(SILI_D_XFER, "sili_ata_put_xfer slot %d\n", ccb->ccb_slot);
2467
2468         sili_put_ccb(ccb);
2469 }
2470
2471 int
2472 sili_ata_cmd(struct ata_xfer *xa)
2473 {
2474         struct sili_ccb                 *ccb = (struct sili_ccb *)xa;
2475
2476         KKASSERT(xa->state == ATA_S_SETUP);
2477
2478         if (ccb->ccb_port->ap_state == AP_S_FATAL_ERROR)
2479                 goto failcmd;
2480 #if 0
2481         kprintf("%s: started std command %b ccb %d ccb_at %p %d\n",
2482                 ATANAME(ccb->ccb_port, ccb->ccb_xa.at),
2483                 sili_pread(ccb->ccb_port, SILI_PREG_CMD), SILI_PFMT_CMD,
2484                 ccb->ccb_slot,
2485                 ccb->ccb_xa.at,
2486                 ccb->ccb_xa.at ? ccb->ccb_xa.at->at_target : -1);
2487 #endif
2488
2489         ccb->ccb_done = sili_ata_cmd_done;
2490
2491         if (sili_load_prb(ccb) != 0)
2492                 goto failcmd;
2493
2494         xa->state = ATA_S_PENDING;
2495
2496         if (xa->flags & ATA_F_POLL)
2497                 return (sili_poll(ccb, xa->timeout, sili_ata_cmd_timeout));
2498
2499         crit_enter();
2500         KKASSERT((xa->flags & ATA_F_TIMEOUT_EXPIRED) == 0);
2501         xa->flags |= ATA_F_TIMEOUT_DESIRED;
2502         sili_start(ccb);
2503         crit_exit();
2504         return (xa->state);
2505
2506 failcmd:
2507         crit_enter();
2508         xa->state = ATA_S_ERROR;
2509         xa->complete(xa);
2510         crit_exit();
2511         return (ATA_S_ERROR);
2512 }
2513
2514 static void
2515 sili_ata_cmd_done(struct sili_ccb *ccb)
2516 {
2517         struct ata_xfer                 *xa = &ccb->ccb_xa;
2518
2519         /*
2520          * NOTE: callout does not lock port and may race us modifying
2521          * the flags, so make sure its stopped.
2522          */
2523         if (xa->flags & ATA_F_TIMEOUT_RUNNING) {
2524                 callout_stop(&ccb->ccb_timeout);
2525                 xa->flags &= ~ATA_F_TIMEOUT_RUNNING;
2526         }
2527         xa->flags &= ~(ATA_F_TIMEOUT_DESIRED | ATA_F_TIMEOUT_EXPIRED);
2528
2529         KKASSERT(xa->state != ATA_S_ONCHIP);
2530         sili_unload_prb(ccb);
2531
2532 #ifdef DIAGNOSTIC
2533         else if (xa->state != ATA_S_ERROR && xa->state != ATA_S_TIMEOUT)
2534                 kprintf("%s: invalid ata_xfer state %02x in sili_ata_cmd_done, "
2535                         "slot %d\n",
2536                         PORTNAME(ccb->ccb_port), xa->state, ccb->ccb_slot);
2537 #endif
2538         if (xa->state != ATA_S_TIMEOUT)
2539                 xa->complete(xa);
2540 }
2541
2542 /*
2543  * Timeout from callout, MPSAFE - nothing can mess with the CCB's flags
2544  * while the callout is runing.
2545  *
2546  * We can't safely get the port lock here or delay, we could block
2547  * the callout thread.
2548  */
2549 static void
2550 sili_ata_cmd_timeout_unserialized(void *arg)
2551 {
2552         struct sili_ccb         *ccb = arg;
2553         struct sili_port        *ap = ccb->ccb_port;
2554
2555         ccb->ccb_xa.flags &= ~ATA_F_TIMEOUT_RUNNING;
2556         ccb->ccb_xa.flags |= ATA_F_TIMEOUT_EXPIRED;
2557         sili_os_signal_port_thread(ap, AP_SIGF_TIMEOUT);
2558 }
2559
2560 void
2561 sili_ata_cmd_timeout(struct sili_ccb *ccb)
2562 {
2563         sili_core_timeout(ccb);
2564 }
2565
2566 /*
2567  * Timeout code, typically called when the port command processor is running.
2568  *
2569  * Returns 0 if all timeout processing completed, non-zero if it is still
2570  * in progress.
2571  */
2572 static
2573 int
2574 sili_core_timeout(struct sili_ccb *ccb)
2575 {
2576         struct ata_xfer         *xa = &ccb->ccb_xa;
2577         struct sili_port        *ap = ccb->ccb_port;
2578         struct ata_port         *at;
2579
2580         at = ccb->ccb_xa.at;
2581
2582         kprintf("%s: CMD TIMEOUT state=%d slot=%d\n"
2583                 "\t active=%08x\n"
2584                 "\texpired=%08x\n"
2585                 "\thactive=%08x\n",
2586                 ATANAME(ap, at),
2587                 ccb->ccb_xa.state, ccb->ccb_slot,
2588                 ap->ap_active,
2589                 ap->ap_expired,
2590                 sili_pread(ap, SILI_PREG_SLOTST)
2591         );
2592
2593         /*
2594          * NOTE: Timeout will not be running if the command was polled.
2595          *       If we got here at least one of these flags should be set.
2596          *
2597          *       However, it might be running if we are called from the
2598          *       interrupt error handling code.
2599          */
2600         KKASSERT(xa->flags & (ATA_F_POLL | ATA_F_TIMEOUT_DESIRED |
2601                               ATA_F_TIMEOUT_RUNNING));
2602         if (xa->flags & ATA_F_TIMEOUT_RUNNING) {
2603                 callout_stop(&ccb->ccb_timeout);
2604                 xa->flags &= ~ATA_F_TIMEOUT_RUNNING;
2605         }
2606         xa->flags &= ~ATA_F_TIMEOUT_EXPIRED;
2607
2608         if (ccb->ccb_xa.state == ATA_S_PENDING) {
2609                 TAILQ_REMOVE(&ap->ap_ccb_pending, ccb, ccb_entry);
2610                 ccb->ccb_xa.state = ATA_S_TIMEOUT;
2611                 ccb->ccb_done(ccb);
2612                 xa->complete(xa);
2613                 sili_issue_pending_commands(ap, NULL);
2614                 return(1);
2615         }
2616         if (ccb->ccb_xa.state != ATA_S_ONCHIP) {
2617                 kprintf("%s: Unexpected state during timeout: %d\n",
2618                         ATANAME(ap, at), ccb->ccb_xa.state);
2619                 return(1);
2620         }
2621
2622         /*
2623          * We can't process timeouts while other commands are running.
2624          */
2625         ap->ap_expired |= 1 << ccb->ccb_slot;
2626
2627         if (ap->ap_active != ap->ap_expired) {
2628                 kprintf("%s: Deferred timeout until its safe, slot %d\n",
2629                         ATANAME(ap, at), ccb->ccb_slot);
2630                 return(1);
2631         }
2632
2633         /*
2634          * We have to issue a Port reinit.  We don't read an error log
2635          * page for timeouts.  Reiniting the port will clear all pending
2636          * commands.
2637          */
2638         sili_port_reinit(ap);
2639         return(0);
2640 }
2641
2642 /*
2643  * Used by the softreset, pmprobe, and read_ncq_error only, in very
2644  * specialized, controlled circumstances.
2645  */
2646 void
2647 sili_quick_timeout(struct sili_ccb *ccb)
2648 {
2649         struct sili_port *ap = ccb->ccb_port;
2650
2651         switch (ccb->ccb_xa.state) {
2652         case ATA_S_PENDING:
2653                 TAILQ_REMOVE(&ap->ap_ccb_pending, ccb, ccb_entry);
2654                 ccb->ccb_xa.state = ATA_S_TIMEOUT;
2655                 break;
2656         case ATA_S_ONCHIP:
2657                 KKASSERT((ap->ap_active & ~ap->ap_expired) ==
2658                          (1 << ccb->ccb_slot));
2659                 ccb->ccb_xa.state = ATA_S_TIMEOUT;
2660                 ap->ap_active &= ~(1 << ccb->ccb_slot);
2661                 KKASSERT(ap->ap_active_cnt > 0);
2662                 --ap->ap_active_cnt;
2663                 sili_port_reinit(ap);
2664                 break;
2665         default:
2666                 panic("%s: sili_quick_timeout: ccb in bad state %d",
2667                       ATANAME(ap, ccb->ccb_xa.at), ccb->ccb_xa.state);
2668         }
2669 }
2670
2671 static void
2672 sili_dummy_done(struct ata_xfer *xa)
2673 {
2674 }
2675
2676 static void
2677 sili_empty_done(struct sili_ccb *ccb)
2678 {
2679 }