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