]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/dev/hpt27xx/hpt27xx_osm_bsd.c
ping(8): Fix a mandoc related issue
[FreeBSD/FreeBSD.git] / sys / dev / hpt27xx / hpt27xx_osm_bsd.c
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2011 HighPoint Technologies, Inc.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  *
28  * $FreeBSD$
29  */
30
31 #include <dev/hpt27xx/hpt27xx_config.h>
32
33 #include <dev/hpt27xx/os_bsd.h>
34 #include <dev/hpt27xx/hptintf.h>
35
36 static HIM *hpt_match(device_t dev, int scan)
37 {
38         PCI_ID pci_id;
39         HIM *him;
40         int i;
41
42         for (him = him_list; him; him = him->next) {
43                 for (i=0; him->get_supported_device_id(i, &pci_id); i++) {
44                         if (scan && him->get_controller_count)
45                                 him->get_controller_count(&pci_id,0,0);
46                         if ((pci_get_vendor(dev) == pci_id.vid) &&
47                                 (pci_get_device(dev) == pci_id.did)){
48                                 return (him);
49                         }
50                 }
51         }
52         return (NULL);
53 }
54
55 static int hpt_probe(device_t dev)
56 {
57         HIM *him;
58
59         him = hpt_match(dev, 0);
60         if (him != NULL) {
61                 KdPrint(("hpt_probe: adapter at PCI %d:%d:%d, IRQ %d",
62                         pci_get_bus(dev), pci_get_slot(dev), pci_get_function(dev), pci_get_irq(dev)
63                         ));
64                 device_set_desc(dev, him->name);
65                 return (BUS_PROBE_DEFAULT);
66         }
67
68         return (ENXIO);
69 }
70
71 static int hpt_attach(device_t dev)
72 {
73         PHBA hba = (PHBA)device_get_softc(dev);
74         HIM *him;
75         PCI_ID pci_id;
76         HPT_UINT size;
77         PVBUS vbus;
78         PVBUS_EXT vbus_ext;
79         
80         KdPrint(("hpt_attach(%d/%d/%d)", pci_get_bus(dev), pci_get_slot(dev), pci_get_function(dev)));
81
82         him = hpt_match(dev, 1);
83         hba->ext_type = EXT_TYPE_HBA;
84         hba->ldm_adapter.him = him;
85         pci_enable_busmaster(dev);
86
87         pci_id.vid = pci_get_vendor(dev);
88         pci_id.did = pci_get_device(dev);
89         pci_id.rev = pci_get_revid(dev);
90         pci_id.subsys = (HPT_U32)(pci_get_subdevice(dev)) << 16 | pci_get_subvendor(dev);
91
92         size = him->get_adapter_size(&pci_id);
93         hba->ldm_adapter.him_handle = malloc(size, M_DEVBUF, M_WAITOK);
94         if (!hba->ldm_adapter.him_handle)
95                 return ENXIO;
96
97         hba->pcidev = dev;
98         hba->pciaddr.tree = 0;
99         hba->pciaddr.bus = pci_get_bus(dev);
100         hba->pciaddr.device = pci_get_slot(dev);
101         hba->pciaddr.function = pci_get_function(dev);
102
103         if (!him->create_adapter(&pci_id, hba->pciaddr, hba->ldm_adapter.him_handle, hba)) {
104                 free(hba->ldm_adapter.him_handle, M_DEVBUF);
105                 return ENXIO;
106         }
107
108         os_printk("adapter at PCI %d:%d:%d, IRQ %d",
109                 hba->pciaddr.bus, hba->pciaddr.device, hba->pciaddr.function, pci_get_irq(dev));
110
111         if (!ldm_register_adapter(&hba->ldm_adapter)) {
112                 size = ldm_get_vbus_size();
113                 vbus_ext = malloc(sizeof(VBUS_EXT) + size, M_DEVBUF, M_WAITOK);
114                 if (!vbus_ext) {
115                         free(hba->ldm_adapter.him_handle, M_DEVBUF);
116                         return ENXIO;
117                 }
118                 memset(vbus_ext, 0, sizeof(VBUS_EXT));
119                 vbus_ext->ext_type = EXT_TYPE_VBUS;
120                 ldm_create_vbus((PVBUS)vbus_ext->vbus, vbus_ext);
121                 ldm_register_adapter(&hba->ldm_adapter);
122         }
123
124         ldm_for_each_vbus(vbus, vbus_ext) {
125                 if (hba->ldm_adapter.vbus==vbus) {
126                         hba->vbus_ext = vbus_ext;
127                         hba->next = vbus_ext->hba_list;
128                         vbus_ext->hba_list = hba;
129                         break;
130                 }
131         }
132         return 0;
133 }
134
135 /*
136  * Maybe we'd better to use the bus_dmamem_alloc to alloc DMA memory,
137  * but there are some problems currently (alignment, etc).
138  */
139 static __inline void *__get_free_pages(int order)
140 {
141         /* don't use low memory - other devices may get starved */
142         return contigmalloc(PAGE_SIZE<<order, 
143                         M_DEVBUF, M_WAITOK, BUS_SPACE_MAXADDR_24BIT, BUS_SPACE_MAXADDR, PAGE_SIZE, 0);
144 }
145
146 static __inline void free_pages(void *p, int order)
147 {
148         contigfree(p, PAGE_SIZE<<order, M_DEVBUF);
149 }
150
151 static int hpt_alloc_mem(PVBUS_EXT vbus_ext)
152 {
153         PHBA hba;
154         struct freelist *f;
155         HPT_UINT i;
156         void **p;
157
158         for (hba = vbus_ext->hba_list; hba; hba = hba->next)
159                 hba->ldm_adapter.him->get_meminfo(hba->ldm_adapter.him_handle);
160
161         ldm_get_mem_info((PVBUS)vbus_ext->vbus, 0);
162
163         for (f=vbus_ext->freelist_head; f; f=f->next) {
164                 KdPrint(("%s: %d*%d=%d bytes",
165                         f->tag, f->count, f->size, f->count*f->size));
166                 for (i=0; i<f->count; i++) {
167                         p = (void **)malloc(f->size, M_DEVBUF, M_WAITOK);
168                         if (!p) return (ENXIO);
169                         *p = f->head;
170                         f->head = p;
171                 }
172         }
173
174         for (f=vbus_ext->freelist_dma_head; f; f=f->next) {
175                 int order, size, j;
176
177                 HPT_ASSERT((f->size & (f->alignment-1))==0);
178
179                 for (order=0, size=PAGE_SIZE; size<f->size; order++, size<<=1)
180                         ;
181
182                 KdPrint(("%s: %d*%d=%d bytes, order %d",
183                         f->tag, f->count, f->size, f->count*f->size, order));
184                 HPT_ASSERT(f->alignment<=PAGE_SIZE);
185
186                 for (i=0; i<f->count;) {
187                         p = (void **)__get_free_pages(order);
188                         if (!p) return -1;
189                         for (j = size/f->size; j && i<f->count; i++,j--) {
190                                 *p = f->head;
191                                 *(BUS_ADDRESS *)(p+1) = (BUS_ADDRESS)vtophys(p);
192                                 f->head = p;
193                                 p = (void **)((unsigned long)p + f->size);
194                         }
195                 }
196         }
197         
198         HPT_ASSERT(PAGE_SIZE==DMAPOOL_PAGE_SIZE);
199
200         for (i=0; i<os_max_cache_pages; i++) {
201                 p = (void **)__get_free_pages(0);
202                 if (!p) return -1;
203                 HPT_ASSERT(((HPT_UPTR)p & (DMAPOOL_PAGE_SIZE-1))==0);
204                 dmapool_put_page((PVBUS)vbus_ext->vbus, p, (BUS_ADDRESS)vtophys(p));
205         }
206
207         return 0;
208 }
209
210 static void hpt_free_mem(PVBUS_EXT vbus_ext)
211 {
212         struct freelist *f;
213         void *p;
214         int i;
215         BUS_ADDRESS bus;
216
217         for (f=vbus_ext->freelist_head; f; f=f->next) {
218 #if DBG
219                 if (f->count!=f->reserved_count) {
220                         KdPrint(("memory leak for freelist %s (%d/%d)", f->tag, f->count, f->reserved_count));
221                 }
222 #endif
223                 while ((p=freelist_get(f)))
224                         free(p, M_DEVBUF);
225         }
226
227         for (i=0; i<os_max_cache_pages; i++) {
228                 p = dmapool_get_page((PVBUS)vbus_ext->vbus, &bus);
229                 HPT_ASSERT(p);
230                 free_pages(p, 0);
231         }
232
233         for (f=vbus_ext->freelist_dma_head; f; f=f->next) {
234                 int order, size;
235 #if DBG
236                 if (f->count!=f->reserved_count) {
237                         KdPrint(("memory leak for dma freelist %s (%d/%d)", f->tag, f->count, f->reserved_count));
238                 }
239 #endif
240                 for (order=0, size=PAGE_SIZE; size<f->size; order++, size<<=1) ;
241
242                 while ((p=freelist_get_dma(f, &bus))) {
243                         if (order)
244                                 free_pages(p, order);
245                         else {
246                         /* can't free immediately since other blocks in this page may still be in the list */
247                                 if (((HPT_UPTR)p & (PAGE_SIZE-1))==0)
248                                         dmapool_put_page((PVBUS)vbus_ext->vbus, p, bus);
249                         }
250                 }
251         }
252         
253         while ((p = dmapool_get_page((PVBUS)vbus_ext->vbus, &bus)))
254                 free_pages(p, 0);
255 }
256
257 static int hpt_init_vbus(PVBUS_EXT vbus_ext)
258 {
259         PHBA hba;
260
261         for (hba = vbus_ext->hba_list; hba; hba = hba->next)
262                 if (!hba->ldm_adapter.him->initialize(hba->ldm_adapter.him_handle)) {
263                         KdPrint(("fail to initialize %p", hba));
264                         return -1;
265                 }
266
267         ldm_initialize_vbus((PVBUS)vbus_ext->vbus, &vbus_ext->hba_list->ldm_adapter);
268         return 0;
269 }
270
271 static void hpt_flush_done(PCOMMAND pCmd)
272 {
273         PVDEV vd = pCmd->target;
274
275         if (mIsArray(vd->type) && vd->u.array.transform && vd!=vd->u.array.transform->target) {
276                 vd = vd->u.array.transform->target;
277                 HPT_ASSERT(vd);
278                 pCmd->target = vd;
279                 pCmd->Result = RETURN_PENDING;
280                 vdev_queue_cmd(pCmd);
281                 return;
282         }
283
284         *(int *)pCmd->priv = 1;
285         wakeup(pCmd);
286 }
287
288 /*
289  * flush a vdev (without retry).
290  */
291 static int hpt_flush_vdev(PVBUS_EXT vbus_ext, PVDEV vd)
292 {
293         PCOMMAND pCmd;
294         int result = 0, done;
295         HPT_UINT count;
296
297         KdPrint(("flusing dev %p", vd));
298
299         hpt_lock_vbus(vbus_ext);
300
301         if (mIsArray(vd->type) && vd->u.array.transform)
302                 count = max(vd->u.array.transform->source->cmds_per_request,
303                                         vd->u.array.transform->target->cmds_per_request);
304         else
305                 count = vd->cmds_per_request;
306
307         pCmd = ldm_alloc_cmds(vd->vbus, count);
308
309         if (!pCmd) {
310                 hpt_unlock_vbus(vbus_ext);
311                 return -1;
312         }
313
314         pCmd->type = CMD_TYPE_FLUSH;
315         pCmd->flags.hard_flush = 1;
316         pCmd->target = vd;
317         pCmd->done = hpt_flush_done;
318         done = 0;
319         pCmd->priv = &done;
320
321         ldm_queue_cmd(pCmd);
322         
323         if (!done) {
324                 while (hpt_sleep(vbus_ext, pCmd, PPAUSE, "hptfls", HPT_OSM_TIMEOUT)) {
325                         ldm_reset_vbus(vd->vbus);
326                 }
327         }
328
329         KdPrint(("flush result %d", pCmd->Result));
330
331         if (pCmd->Result!=RETURN_SUCCESS)
332                 result = -1;
333
334         ldm_free_cmds(pCmd);
335
336         hpt_unlock_vbus(vbus_ext);
337
338         return result;
339 }
340
341 static void hpt_stop_tasks(PVBUS_EXT vbus_ext);
342 static void hpt_shutdown_vbus(PVBUS_EXT vbus_ext, int howto)
343 {
344         PVBUS     vbus = (PVBUS)vbus_ext->vbus;
345         PHBA hba;
346         int i;
347         
348         KdPrint(("hpt_shutdown_vbus"));
349
350         /* stop all ctl tasks and disable the worker taskqueue */
351         hpt_stop_tasks(vbus_ext);
352         vbus_ext->worker.ta_context = 0;
353
354         /* flush devices */
355         for (i=0; i<osm_max_targets; i++) {
356                 PVDEV vd = ldm_find_target(vbus, i);
357                 if (vd) {
358                         /* retry once */
359                         if (hpt_flush_vdev(vbus_ext, vd))
360                                 hpt_flush_vdev(vbus_ext, vd);
361                 }
362         }
363
364         hpt_lock_vbus(vbus_ext);
365         ldm_shutdown(vbus);
366         hpt_unlock_vbus(vbus_ext);
367
368         ldm_release_vbus(vbus);
369
370         for (hba=vbus_ext->hba_list; hba; hba=hba->next)
371                 bus_teardown_intr(hba->pcidev, hba->irq_res, hba->irq_handle);
372
373         hpt_free_mem(vbus_ext);
374
375         while ((hba=vbus_ext->hba_list)) {
376                 vbus_ext->hba_list = hba->next;
377                 free(hba->ldm_adapter.him_handle, M_DEVBUF);
378         }
379 #if (__FreeBSD_version >= 1000510)
380         callout_drain(&vbus_ext->timer);
381         mtx_destroy(&vbus_ext->lock);
382 #endif
383         free(vbus_ext, M_DEVBUF);
384         KdPrint(("hpt_shutdown_vbus done"));
385 }
386
387 static void __hpt_do_tasks(PVBUS_EXT vbus_ext)
388 {
389         OSM_TASK *tasks;
390
391         tasks = vbus_ext->tasks;
392         vbus_ext->tasks = 0;
393
394         while (tasks) {
395                 OSM_TASK *t = tasks;
396                 tasks = t->next;
397                 t->next = 0;
398                 t->func(vbus_ext->vbus, t->data);
399         }
400 }
401
402 static void hpt_do_tasks(PVBUS_EXT vbus_ext, int pending)
403 {
404         if(vbus_ext){
405                 hpt_lock_vbus(vbus_ext);
406                 __hpt_do_tasks(vbus_ext);
407                 hpt_unlock_vbus(vbus_ext);
408         }
409 }
410
411 static void hpt_action(struct cam_sim *sim, union ccb *ccb);
412 static void hpt_poll(struct cam_sim *sim);
413 static void hpt_async(void * callback_arg, u_int32_t code, struct cam_path * path, void * arg);
414 static void hpt_pci_intr(void *arg);
415
416 static __inline POS_CMDEXT cmdext_get(PVBUS_EXT vbus_ext)
417 {
418         POS_CMDEXT p = vbus_ext->cmdext_list;
419         if (p)
420                 vbus_ext->cmdext_list = p->next;
421         return p;
422 }
423
424 static __inline void cmdext_put(POS_CMDEXT p)
425 {
426         p->next = p->vbus_ext->cmdext_list;
427         p->vbus_ext->cmdext_list = p;
428 }
429
430 static void hpt_timeout(void *arg)
431 {
432         PCOMMAND pCmd = (PCOMMAND)arg;
433         POS_CMDEXT ext = (POS_CMDEXT)pCmd->priv;
434         
435         KdPrint(("pCmd %p timeout", pCmd));
436         
437         ldm_reset_vbus((PVBUS)ext->vbus_ext->vbus);
438 }
439
440 static void os_cmddone(PCOMMAND pCmd)
441 {
442         POS_CMDEXT ext = (POS_CMDEXT)pCmd->priv;
443         union ccb *ccb = ext->ccb;
444
445         KdPrint(("<8>os_cmddone(%p, %d)", pCmd, pCmd->Result));
446 #if (__FreeBSD_version >= 1000510)      
447         callout_stop(&ext->timeout);
448 #else 
449         untimeout(hpt_timeout, pCmd, ccb->ccb_h.timeout_ch);
450 #endif
451         switch(pCmd->Result) {
452         case RETURN_SUCCESS:
453                 ccb->ccb_h.status = CAM_REQ_CMP;
454                 break;
455         case RETURN_BAD_DEVICE:
456                 ccb->ccb_h.status = CAM_DEV_NOT_THERE;
457                 break;
458         case RETURN_DEVICE_BUSY:
459                 ccb->ccb_h.status = CAM_BUSY;
460                 break;
461         case RETURN_INVALID_REQUEST:
462                 ccb->ccb_h.status = CAM_REQ_INVALID;
463                 break;
464         case RETURN_SELECTION_TIMEOUT:
465                 ccb->ccb_h.status = CAM_SEL_TIMEOUT;
466                 break;
467         case RETURN_RETRY:
468                 ccb->ccb_h.status = CAM_BUSY;
469                 break;
470         default:
471                 ccb->ccb_h.status = CAM_SCSI_STATUS_ERROR;
472                 break;
473         }
474
475         if (pCmd->flags.data_in) {
476                 bus_dmamap_sync(ext->vbus_ext->io_dmat, ext->dma_map, BUS_DMASYNC_POSTREAD);
477         }
478         else if (pCmd->flags.data_out) {
479                 bus_dmamap_sync(ext->vbus_ext->io_dmat, ext->dma_map, BUS_DMASYNC_POSTWRITE);
480         }
481         
482         bus_dmamap_unload(ext->vbus_ext->io_dmat, ext->dma_map);
483
484         cmdext_put(ext);
485         ldm_free_cmds(pCmd);
486         xpt_done(ccb);
487 }
488
489 static int os_buildsgl(PCOMMAND pCmd, PSG pSg, int logical)
490 {
491         POS_CMDEXT ext = (POS_CMDEXT)pCmd->priv;
492         union ccb *ccb = ext->ccb;
493 #if (__FreeBSD_version >= 1000510)
494         if(logical)     {
495                 os_set_sgptr(pSg, (HPT_U8 *)ccb->csio.data_ptr);
496                 pSg->size = ccb->csio.dxfer_len;
497                 pSg->eot = 1;
498                 return TRUE;
499         }
500 #else 
501         bus_dma_segment_t *sgList = (bus_dma_segment_t *)ccb->csio.data_ptr;
502         int idx;
503
504         if(logical)     {
505                 if (ccb->ccb_h.flags & CAM_DATA_PHYS)
506                         panic("physical address unsupported");
507
508                 if (ccb->ccb_h.flags & CAM_SCATTER_VALID) {
509                         if (ccb->ccb_h.flags & CAM_SG_LIST_PHYS)
510                                 panic("physical address unsupported");
511         
512                         for (idx = 0; idx < ccb->csio.sglist_cnt; idx++) {
513                                 os_set_sgptr(&pSg[idx], (HPT_U8 *)(HPT_UPTR)sgList[idx].ds_addr);
514                                 pSg[idx].size = sgList[idx].ds_len;
515                                 pSg[idx].eot = (idx==ccb->csio.sglist_cnt-1)? 1 : 0;
516                         }
517                 }
518                 else {
519                         os_set_sgptr(pSg, (HPT_U8 *)ccb->csio.data_ptr);
520                         pSg->size = ccb->csio.dxfer_len;
521                         pSg->eot = 1;
522                 }
523                 return TRUE;
524         }
525 #endif
526         /* since we have provided physical sg, nobody will ask us to build physical sg */
527         HPT_ASSERT(0);
528         return FALSE;
529 }
530
531 static void hpt_io_dmamap_callback(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
532 {
533         PCOMMAND pCmd = (PCOMMAND)arg;
534         POS_CMDEXT ext = (POS_CMDEXT)pCmd->priv;
535         PSG psg = pCmd->psg;
536         int idx;
537         
538         HPT_ASSERT(pCmd->flags.physical_sg);
539         
540         if (error)
541                 panic("busdma error");
542                 
543         HPT_ASSERT(nsegs<=os_max_sg_descriptors);
544
545         if (nsegs != 0) {
546                 for (idx = 0; idx < nsegs; idx++, psg++) {
547                         psg->addr.bus = segs[idx].ds_addr;
548                         psg->size = segs[idx].ds_len;
549                         psg->eot = 0;
550                 }
551                 psg[-1].eot = 1;
552         
553                 if (pCmd->flags.data_in) {
554                         bus_dmamap_sync(ext->vbus_ext->io_dmat, ext->dma_map,
555                             BUS_DMASYNC_PREREAD);
556                 }
557                 else if (pCmd->flags.data_out) {
558                         bus_dmamap_sync(ext->vbus_ext->io_dmat, ext->dma_map,
559                             BUS_DMASYNC_PREWRITE);
560                 }
561         }
562 #if (__FreeBSD_version >= 1000510)      
563         callout_reset(&ext->timeout, HPT_OSM_TIMEOUT, hpt_timeout, pCmd);
564 #else 
565         ext->ccb->ccb_h.timeout_ch = timeout(hpt_timeout, pCmd, HPT_OSM_TIMEOUT);
566 #endif
567         ldm_queue_cmd(pCmd);
568 }
569
570 static void hpt_scsi_io(PVBUS_EXT vbus_ext, union ccb *ccb)
571 {
572         PVBUS vbus = (PVBUS)vbus_ext->vbus;
573         PVDEV vd;
574         PCOMMAND pCmd;
575         POS_CMDEXT ext;
576         HPT_U8 *cdb;
577
578         if (ccb->ccb_h.flags & CAM_CDB_POINTER)
579                 cdb = ccb->csio.cdb_io.cdb_ptr;
580         else
581                 cdb = ccb->csio.cdb_io.cdb_bytes;
582         
583         KdPrint(("<8>hpt_scsi_io: ccb %x id %d lun %d cdb %x-%x-%x",
584                 ccb,
585                 ccb->ccb_h.target_id, ccb->ccb_h.target_lun,
586                 *(HPT_U32 *)&cdb[0], *(HPT_U32 *)&cdb[4], *(HPT_U32 *)&cdb[8]
587         ));
588
589         /* ccb->ccb_h.path_id is not our bus id - don't check it */
590         if (ccb->ccb_h.target_lun != 0 ||
591                 ccb->ccb_h.target_id >= osm_max_targets ||
592                 (ccb->ccb_h.flags & CAM_CDB_PHYS))
593         {
594                 ccb->ccb_h.status = CAM_TID_INVALID;
595                 xpt_done(ccb);
596                 return;
597         }
598
599         vd = ldm_find_target(vbus, ccb->ccb_h.target_id);
600
601         if (!vd) {
602                 ccb->ccb_h.status = CAM_SEL_TIMEOUT;
603                 xpt_done(ccb);
604                 return;
605         }
606    
607         switch (cdb[0]) {
608         case TEST_UNIT_READY:
609         case START_STOP_UNIT:
610         case SYNCHRONIZE_CACHE:
611                 ccb->ccb_h.status = CAM_REQ_CMP;
612                 break;
613
614         case INQUIRY:
615                 {
616                         PINQUIRYDATA inquiryData;
617                         memset(ccb->csio.data_ptr, 0, ccb->csio.dxfer_len);
618                         inquiryData = (PINQUIRYDATA)ccb->csio.data_ptr;
619                 
620                         inquiryData->AdditionalLength = 31;
621                         inquiryData->CommandQueue = 1;
622                         memcpy(&inquiryData->VendorId, "HPT     ", 8);
623                         memcpy(&inquiryData->ProductId, "DISK 0_0        ", 16);
624         
625                         if (vd->target_id / 10) {
626                                 inquiryData->ProductId[7] = (vd->target_id % 100) / 10 + '0';
627                                 inquiryData->ProductId[8] = (vd->target_id % 100) % 10 + '0';
628                         }
629                         else
630                                 inquiryData->ProductId[7] = (vd->target_id % 100) % 10 + '0';
631         
632                         memcpy(&inquiryData->ProductRevisionLevel, "4.00", 4);
633         
634                         ccb->ccb_h.status = CAM_REQ_CMP;
635                 }
636                 break;
637
638         case READ_CAPACITY:
639         {
640                 HPT_U8 *rbuf = ccb->csio.data_ptr;
641                 HPT_U32 cap;
642                 HPT_U8 sector_size_shift = 0;
643                 HPT_U64 new_cap;
644                 HPT_U32 sector_size = 0;
645
646                 if (mIsArray(vd->type))
647                         sector_size_shift = vd->u.array.sector_size_shift;
648                 else{
649                         if(vd->type == VD_RAW){
650                                 sector_size = vd->u.raw.logical_sector_size;
651                         }
652                 
653                         switch (sector_size) {
654                                 case 0x1000:
655                                         KdPrint(("set 4k setctor size in READ_CAPACITY"));
656                                         sector_size_shift = 3;
657                                         break;
658                                 default:
659                                         break;
660                         }                       
661                 }
662                 new_cap = vd->capacity >> sector_size_shift;
663                 
664                 if (new_cap > 0xfffffffful)
665                         cap = 0xffffffff;
666                 else
667                         cap = new_cap - 1;
668                         
669                 rbuf[0] = (HPT_U8)(cap>>24);
670                 rbuf[1] = (HPT_U8)(cap>>16);
671                 rbuf[2] = (HPT_U8)(cap>>8);
672                 rbuf[3] = (HPT_U8)cap;
673                 rbuf[4] = 0;
674                 rbuf[5] = 0;
675                 rbuf[6] = 2 << sector_size_shift;
676                 rbuf[7] = 0;
677
678                 ccb->ccb_h.status = CAM_REQ_CMP;
679                 break;
680         }
681         case REPORT_LUNS:
682         {
683                 HPT_U8 *rbuf = ccb->csio.data_ptr;
684                 memset(rbuf, 0, 16);
685                 rbuf[3] = 8;
686                 ccb->ccb_h.status = CAM_REQ_CMP;
687                 break;                          
688         }
689         case SERVICE_ACTION_IN: 
690         {
691                 HPT_U8 *rbuf = ccb->csio.data_ptr;
692                 HPT_U64 cap = 0;
693                 HPT_U8 sector_size_shift = 0;
694                 HPT_U32 sector_size = 0;
695
696                 if(mIsArray(vd->type))
697                         sector_size_shift = vd->u.array.sector_size_shift;
698                 else{
699                         if(vd->type == VD_RAW){
700                                 sector_size = vd->u.raw.logical_sector_size;
701                         }
702                 
703                         switch (sector_size) {
704                                 case 0x1000:
705                                         KdPrint(("set 4k setctor size in SERVICE_ACTION_IN"));
706                                         sector_size_shift = 3;
707                                         break;
708                                 default:
709                                         break;
710                         }                       
711                 }
712                 cap = (vd->capacity >> sector_size_shift) - 1;
713                                         
714                 rbuf[0] = (HPT_U8)(cap>>56);
715                 rbuf[1] = (HPT_U8)(cap>>48);
716                 rbuf[2] = (HPT_U8)(cap>>40);
717                 rbuf[3] = (HPT_U8)(cap>>32);
718                 rbuf[4] = (HPT_U8)(cap>>24);
719                 rbuf[5] = (HPT_U8)(cap>>16);
720                 rbuf[6] = (HPT_U8)(cap>>8);
721                 rbuf[7] = (HPT_U8)cap;
722                 rbuf[8] = 0;
723                 rbuf[9] = 0;
724                 rbuf[10] = 2 << sector_size_shift;
725                 rbuf[11] = 0;
726                 
727                 ccb->ccb_h.status = CAM_REQ_CMP;
728                 break;  
729         }
730         
731         case READ_6:
732         case READ_10:
733         case READ_16:
734         case WRITE_6:
735         case WRITE_10:
736         case WRITE_16:
737         case 0x13:
738         case 0x2f:
739         case 0x8f: /* VERIFY_16 */
740         {
741                 HPT_U8 sector_size_shift = 0;
742                 HPT_U32 sector_size = 0;
743                 pCmd = ldm_alloc_cmds(vbus, vd->cmds_per_request);
744                 if(!pCmd){
745                         KdPrint(("Failed to allocate command!"));
746                         ccb->ccb_h.status = CAM_BUSY;
747                         break;
748                 }
749
750                 switch (cdb[0]) {
751                 case READ_6:
752                 case WRITE_6:
753                 case 0x13:
754                         pCmd->uCmd.Ide.Lba =  ((HPT_U32)cdb[1] << 16) | ((HPT_U32)cdb[2] << 8) | (HPT_U32)cdb[3];
755                         pCmd->uCmd.Ide.nSectors = (HPT_U16) cdb[4];
756                         break;
757                 case READ_16:
758                 case WRITE_16:
759                 case 0x8f: /* VERIFY_16 */
760                 {
761                         HPT_U64 block =
762                                 ((HPT_U64)cdb[2]<<56) |
763                                 ((HPT_U64)cdb[3]<<48) |
764                                 ((HPT_U64)cdb[4]<<40) |
765                                 ((HPT_U64)cdb[5]<<32) |
766                                 ((HPT_U64)cdb[6]<<24) |
767                                 ((HPT_U64)cdb[7]<<16) |
768                                 ((HPT_U64)cdb[8]<<8) |
769                                 ((HPT_U64)cdb[9]);
770                         pCmd->uCmd.Ide.Lba = block;
771                         pCmd->uCmd.Ide.nSectors = (HPT_U16)cdb[13] | ((HPT_U16)cdb[12]<<8);
772                         break;
773                 }
774                 
775                 default:
776                         pCmd->uCmd.Ide.Lba = (HPT_U32)cdb[5] | ((HPT_U32)cdb[4] << 8) | ((HPT_U32)cdb[3] << 16) | ((HPT_U32)cdb[2] << 24);
777                         pCmd->uCmd.Ide.nSectors = (HPT_U16) cdb[8] | ((HPT_U16)cdb[7]<<8);
778                         break;
779                 }
780
781                 if(mIsArray(vd->type)) {
782                         sector_size_shift = vd->u.array.sector_size_shift;
783                 }
784                 else{
785                         if(vd->type == VD_RAW){
786                                 sector_size = vd->u.raw.logical_sector_size;
787                         }
788                         
789                         switch (sector_size) {
790                                 case 0x1000:
791                                         KdPrint(("<8>resize sector size from 4k to 512"));
792                                         sector_size_shift = 3;
793                                         break;
794                                 default:
795                                         break;
796                         }                       
797                 }
798                 pCmd->uCmd.Ide.Lba <<= sector_size_shift;
799                 pCmd->uCmd.Ide.nSectors <<= sector_size_shift;
800
801                 
802                 switch (cdb[0]) {
803                 case READ_6:
804                 case READ_10:
805                 case READ_16:
806                         pCmd->flags.data_in = 1;
807                         break;
808                 case WRITE_6:
809                 case WRITE_10:
810                 case WRITE_16:
811                         pCmd->flags.data_out = 1;
812                         break;
813                 }
814                 pCmd->priv = ext = cmdext_get(vbus_ext);
815                 HPT_ASSERT(ext);
816                 ext->ccb = ccb;
817                 pCmd->target = vd;
818                 pCmd->done = os_cmddone;
819                 pCmd->buildsgl = os_buildsgl;
820
821                 pCmd->psg = ext->psg;
822 #if (__FreeBSD_version < 1000510)                       
823                 if (ccb->ccb_h.flags & CAM_SCATTER_VALID) {
824                         int idx;
825                         bus_dma_segment_t *sgList = (bus_dma_segment_t *)ccb->csio.data_ptr;
826                         
827                         if (ccb->ccb_h.flags & CAM_SG_LIST_PHYS)
828                                 pCmd->flags.physical_sg = 1;
829                                 
830                         for (idx = 0; idx < ccb->csio.sglist_cnt; idx++) {
831                                 pCmd->psg[idx].addr.bus = sgList[idx].ds_addr;
832                                 pCmd->psg[idx].size = sgList[idx].ds_len;
833                                 pCmd->psg[idx].eot = (idx==ccb->csio.sglist_cnt-1)? 1 : 0;
834                         }
835
836                         ccb->ccb_h.timeout_ch = timeout(hpt_timeout, pCmd, HPT_OSM_TIMEOUT);
837                         ldm_queue_cmd(pCmd);
838                 }
839                 else 
840 #endif
841                 {
842                         int error;
843                         pCmd->flags.physical_sg = 1;
844 #if (__FreeBSD_version >= 1000510)
845                         error = bus_dmamap_load_ccb(vbus_ext->io_dmat,
846                                                 ext->dma_map, ccb,
847                                                 hpt_io_dmamap_callback, pCmd,
848                                                 BUS_DMA_WAITOK
849                                         );
850 #else 
851                         error = bus_dmamap_load(vbus_ext->io_dmat, 
852                                                 ext->dma_map, 
853                                                 ccb->csio.data_ptr, ccb->csio.dxfer_len, 
854                                                 hpt_io_dmamap_callback, pCmd,
855                                         BUS_DMA_WAITOK
856                                         );
857 #endif
858                         KdPrint(("<8>bus_dmamap_load return %d", error));
859                         if (error && error!=EINPROGRESS) {
860                                 os_printk("bus_dmamap_load error %d", error);
861                                 cmdext_put(ext);
862                                 ldm_free_cmds(pCmd);
863                                 ccb->ccb_h.status = CAM_REQ_CMP_ERR;
864                                 xpt_done(ccb);
865                         }
866                 }
867                 return;
868         }
869
870         default:
871                 ccb->ccb_h.status = CAM_REQ_INVALID;
872                 break;
873         }
874
875         xpt_done(ccb);
876         return;
877 }
878
879 static void hpt_action(struct cam_sim *sim, union ccb *ccb)
880 {
881         PVBUS_EXT vbus_ext = (PVBUS_EXT)cam_sim_softc(sim);
882
883         KdPrint(("<8>hpt_action(fn=%d, id=%d)", ccb->ccb_h.func_code, ccb->ccb_h.target_id));
884
885 #if (__FreeBSD_version >= 1000510)
886         hpt_assert_vbus_locked(vbus_ext);
887 #endif
888         switch (ccb->ccb_h.func_code) {
889
890 #if (__FreeBSD_version < 1000510)       
891         case XPT_SCSI_IO:
892                 hpt_lock_vbus(vbus_ext);
893                 hpt_scsi_io(vbus_ext, ccb);
894                 hpt_unlock_vbus(vbus_ext);
895                 return;
896
897         case XPT_RESET_BUS:
898                 hpt_lock_vbus(vbus_ext);
899                 ldm_reset_vbus((PVBUS)vbus_ext->vbus);
900                 hpt_unlock_vbus(vbus_ext);
901                 break;
902 #else 
903         case XPT_SCSI_IO:
904                 hpt_scsi_io(vbus_ext, ccb);
905                 return;
906
907         case XPT_RESET_BUS:
908                 ldm_reset_vbus((PVBUS)vbus_ext->vbus);
909                 break;
910 #endif
911         case XPT_GET_TRAN_SETTINGS:
912         case XPT_SET_TRAN_SETTINGS:
913                 ccb->ccb_h.status = CAM_FUNC_NOTAVAIL;
914                 break;
915
916         case XPT_CALC_GEOMETRY:
917                 ccb->ccg.heads = 255;
918                 ccb->ccg.secs_per_track = 63;
919                 ccb->ccg.cylinders = ccb->ccg.volume_size / (ccb->ccg.heads * ccb->ccg.secs_per_track);
920                 ccb->ccb_h.status = CAM_REQ_CMP;
921                 break;
922
923         case XPT_PATH_INQ:
924         {
925                 struct ccb_pathinq *cpi = &ccb->cpi;
926
927                 cpi->version_num = 1;
928                 cpi->hba_inquiry = PI_SDTR_ABLE;
929                 cpi->target_sprt = 0;
930                 cpi->hba_misc = PIM_NOBUSRESET;
931                 cpi->hba_eng_cnt = 0;
932                 cpi->max_target = osm_max_targets;
933                 cpi->max_lun = 0;
934                 cpi->unit_number = cam_sim_unit(sim);
935                 cpi->bus_id = cam_sim_bus(sim);
936                 cpi->initiator_id = osm_max_targets;
937                 cpi->base_transfer_speed = 3300;
938
939                 strlcpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
940                 strlcpy(cpi->hba_vid, "HPT   ", HBA_IDLEN);
941                 strlcpy(cpi->dev_name, cam_sim_name(sim), DEV_IDLEN);
942                 cpi->transport = XPORT_SPI;
943                 cpi->transport_version = 2;
944                 cpi->protocol = PROTO_SCSI;
945                 cpi->protocol_version = SCSI_REV_2;
946                 cpi->ccb_h.status = CAM_REQ_CMP;
947                 break;
948         }
949
950         default:
951                 ccb->ccb_h.status = CAM_REQ_INVALID;
952                 break;
953         }
954
955         xpt_done(ccb);
956         return;
957 }
958
959 static void hpt_pci_intr(void *arg)
960 {       
961         PVBUS_EXT vbus_ext = (PVBUS_EXT)arg;
962         hpt_lock_vbus(vbus_ext);
963         ldm_intr((PVBUS)vbus_ext->vbus);
964         hpt_unlock_vbus(vbus_ext);
965 }
966
967 static void hpt_poll(struct cam_sim *sim)
968 {
969 #if (__FreeBSD_version < 1000510)
970         hpt_pci_intr(cam_sim_softc(sim));
971 #else 
972         PVBUS_EXT vbus_ext = (PVBUS_EXT)cam_sim_softc(sim);
973
974         hpt_assert_vbus_locked(vbus_ext);
975         ldm_intr((PVBUS)vbus_ext->vbus);
976 #endif
977 }
978
979 static void hpt_async(void * callback_arg, u_int32_t code, struct cam_path * path, void * arg)
980 {
981         KdPrint(("<8>hpt_async"));
982 }
983
984 static int hpt_shutdown(device_t dev)
985 {
986         KdPrint(("hpt_shutdown(dev=%p)", dev));
987         return 0;
988 }
989
990 static int hpt_detach(device_t dev)
991 {
992         /* we don't allow the driver to be unloaded. */
993         return EBUSY;
994 }
995
996 static void hpt_ioctl_done(struct _IOCTL_ARG *arg)
997 {
998         arg->ioctl_cmnd = 0;
999         wakeup(arg);
1000 }
1001
1002 static void __hpt_do_ioctl(PVBUS_EXT vbus_ext, IOCTL_ARG *ioctl_args)
1003 {
1004         ioctl_args->result = -1;
1005         ioctl_args->done = hpt_ioctl_done;
1006         ioctl_args->ioctl_cmnd = (void *)1;
1007
1008         hpt_lock_vbus(vbus_ext);
1009         ldm_ioctl((PVBUS)vbus_ext->vbus, ioctl_args);
1010
1011         while (ioctl_args->ioctl_cmnd) {
1012                 if (hpt_sleep(vbus_ext, ioctl_args, PPAUSE, "hptctl", HPT_OSM_TIMEOUT)==0)
1013                         break;
1014                 ldm_reset_vbus((PVBUS)vbus_ext->vbus);
1015                 __hpt_do_tasks(vbus_ext);
1016         }
1017
1018         /* KdPrint(("ioctl %x result %d", ioctl_args->dwIoControlCode, ioctl_args->result)); */
1019
1020         hpt_unlock_vbus(vbus_ext);
1021 }
1022
1023 static void hpt_do_ioctl(IOCTL_ARG *ioctl_args)
1024 {
1025         PVBUS vbus;
1026         PVBUS_EXT vbus_ext;
1027         
1028         ldm_for_each_vbus(vbus, vbus_ext) {
1029                 __hpt_do_ioctl(vbus_ext, ioctl_args);
1030                 if (ioctl_args->result!=HPT_IOCTL_RESULT_WRONG_VBUS)
1031                         return;
1032         }
1033 }
1034
1035 #define HPT_DO_IOCTL(code, inbuf, insize, outbuf, outsize) ({\
1036         IOCTL_ARG arg;\
1037         arg.dwIoControlCode = code;\
1038         arg.lpInBuffer = inbuf;\
1039         arg.lpOutBuffer = outbuf;\
1040         arg.nInBufferSize = insize;\
1041         arg.nOutBufferSize = outsize;\
1042         arg.lpBytesReturned = 0;\
1043         hpt_do_ioctl(&arg);\
1044         arg.result;\
1045 })
1046
1047 #define DEVICEID_VALID(id) ((id) && ((HPT_U32)(id)!=0xffffffff))
1048
1049 static int hpt_get_logical_devices(DEVICEID * pIds, int nMaxCount)
1050 {
1051         int i;
1052         HPT_U32 count = nMaxCount-1;
1053         
1054         if (HPT_DO_IOCTL(HPT_IOCTL_GET_LOGICAL_DEVICES,
1055                         &count, sizeof(HPT_U32), pIds, sizeof(DEVICEID)*nMaxCount))
1056                 return -1;
1057
1058         nMaxCount = (int)pIds[0];
1059         for (i=0; i<nMaxCount; i++) pIds[i] = pIds[i+1];
1060         return nMaxCount;
1061 }
1062
1063 static int hpt_get_device_info_v3(DEVICEID id, PLOGICAL_DEVICE_INFO_V3 pInfo)
1064 {
1065         return HPT_DO_IOCTL(HPT_IOCTL_GET_DEVICE_INFO_V3,
1066                                 &id, sizeof(DEVICEID), pInfo, sizeof(LOGICAL_DEVICE_INFO_V3));
1067 }
1068
1069 /* not belong to this file logically, but we want to use ioctl interface */
1070 static int __hpt_stop_tasks(PVBUS_EXT vbus_ext, DEVICEID id)
1071 {
1072         LOGICAL_DEVICE_INFO_V3 devinfo;
1073         int i, result;
1074         DEVICEID param[2] = { id, 0 };
1075         
1076         if (hpt_get_device_info_v3(id, &devinfo))
1077                 return -1;
1078                 
1079         if (devinfo.Type!=LDT_ARRAY)
1080                 return -1;
1081                 
1082         if (devinfo.u.array.Flags & ARRAY_FLAG_REBUILDING)
1083                 param[1] = AS_REBUILD_ABORT;
1084         else if (devinfo.u.array.Flags & ARRAY_FLAG_VERIFYING)
1085                 param[1] = AS_VERIFY_ABORT;
1086         else if (devinfo.u.array.Flags & ARRAY_FLAG_INITIALIZING)
1087                 param[1] = AS_INITIALIZE_ABORT;
1088         else if (devinfo.u.array.Flags & ARRAY_FLAG_TRANSFORMING)
1089                 param[1] = AS_TRANSFORM_ABORT;
1090         else
1091                 return -1;
1092
1093         KdPrint(("SET_ARRAY_STATE(%x, %d)", param[0], param[1]));
1094         result = HPT_DO_IOCTL(HPT_IOCTL_SET_ARRAY_STATE,
1095                                 param, sizeof(param), 0, 0);
1096                                 
1097         for (i=0; i<devinfo.u.array.nDisk; i++)
1098                 if (DEVICEID_VALID(devinfo.u.array.Members[i]))
1099                         __hpt_stop_tasks(vbus_ext, devinfo.u.array.Members[i]);
1100                         
1101         return result;
1102 }
1103
1104 static void hpt_stop_tasks(PVBUS_EXT vbus_ext)
1105 {
1106         DEVICEID ids[32];
1107         int i, count;
1108
1109         count = hpt_get_logical_devices((DEVICEID *)&ids, sizeof(ids)/sizeof(ids[0]));
1110         
1111         for (i=0; i<count; i++)
1112                 __hpt_stop_tasks(vbus_ext, ids[i]);
1113 }
1114
1115 static  d_open_t        hpt_open;
1116 static  d_close_t       hpt_close;
1117 static  d_ioctl_t       hpt_ioctl;
1118 static  int             hpt_rescan_bus(void);
1119
1120 static struct cdevsw hpt_cdevsw = {
1121         .d_open =       hpt_open,
1122         .d_close =      hpt_close,
1123         .d_ioctl =      hpt_ioctl,
1124         .d_name =       driver_name,
1125         .d_version =    D_VERSION,
1126 };
1127
1128 static struct intr_config_hook hpt_ich;
1129
1130 /*
1131  * hpt_final_init will be called after all hpt_attach.
1132  */
1133 static void hpt_final_init(void *dummy)
1134 {
1135         int       i,unit_number=0;
1136         PVBUS_EXT vbus_ext;
1137         PVBUS vbus;
1138         PHBA hba;
1139
1140         /* Clear the config hook */
1141         config_intrhook_disestablish(&hpt_ich);
1142
1143         /* allocate memory */
1144         i = 0;
1145         ldm_for_each_vbus(vbus, vbus_ext) {
1146                 if (hpt_alloc_mem(vbus_ext)) {
1147                         os_printk("out of memory");
1148                         return;
1149                 }
1150                 i++;
1151         }
1152
1153         if (!i) {
1154                 if (bootverbose)
1155                         os_printk("no controller detected.");
1156                 return;
1157         }
1158
1159         /* initializing hardware */
1160         ldm_for_each_vbus(vbus, vbus_ext) {
1161                 /* make timer available here */
1162                 mtx_init(&vbus_ext->lock, "hptsleeplock", NULL, MTX_DEF);
1163 #if (__FreeBSD_version < 1000510)
1164                 callout_handle_init(&vbus_ext->timer);
1165 #else 
1166                 callout_init_mtx(&vbus_ext->timer, &vbus_ext->lock, 0);
1167 #endif
1168                 if (hpt_init_vbus(vbus_ext)) {
1169                         os_printk("fail to initialize hardware");
1170                         break; /* FIXME */
1171                 }
1172         }
1173
1174         /* register CAM interface */
1175         ldm_for_each_vbus(vbus, vbus_ext) {
1176                 struct cam_devq *devq;
1177                 struct ccb_setasync     ccb;
1178                 
1179                 if (bus_dma_tag_create(NULL,/* parent */
1180                                 4,      /* alignment */
1181                                 BUS_SPACE_MAXADDR_32BIT+1, /* boundary */
1182                                 BUS_SPACE_MAXADDR,      /* lowaddr */
1183                                 BUS_SPACE_MAXADDR,      /* highaddr */
1184                                 NULL, NULL,             /* filter, filterarg */
1185                                 PAGE_SIZE * (os_max_sg_descriptors-1),  /* maxsize */
1186                                 os_max_sg_descriptors,  /* nsegments */
1187                                 0x10000,        /* maxsegsize */
1188                                 BUS_DMA_WAITOK,         /* flags */
1189                                 busdma_lock_mutex,      /* lockfunc */
1190                                 &vbus_ext->lock,                /* lockfuncarg */
1191                                 &vbus_ext->io_dmat      /* tag */))
1192                 {
1193                         return ;
1194                 }
1195
1196                 for (i=0; i<os_max_queue_comm; i++) {
1197                         POS_CMDEXT ext = (POS_CMDEXT)malloc(sizeof(OS_CMDEXT), M_DEVBUF, M_WAITOK);
1198                         if (!ext) {
1199                                 os_printk("Can't alloc cmdext(%d)", i);
1200                                 return ;
1201                         }
1202                         ext->vbus_ext = vbus_ext;
1203                         ext->next = vbus_ext->cmdext_list;
1204                         vbus_ext->cmdext_list = ext;
1205         
1206                         if (bus_dmamap_create(vbus_ext->io_dmat, 0, &ext->dma_map)) {
1207                                 os_printk("Can't create dma map(%d)", i);
1208                                 return ;
1209                         }
1210 #if (__FreeBSD_version >= 1000510)      
1211                         callout_init_mtx(&ext->timeout, &vbus_ext->lock, 0);
1212 #endif
1213                 }
1214
1215                 if ((devq = cam_simq_alloc(os_max_queue_comm)) == NULL) {
1216                         os_printk("cam_simq_alloc failed");
1217                         return ;
1218                 }
1219 #if (__FreeBSD_version >= 1000510)      
1220                 vbus_ext->sim = cam_sim_alloc(hpt_action, hpt_poll, driver_name,
1221                                 vbus_ext, unit_number, &vbus_ext->lock, os_max_queue_comm, /*tagged*/8,  devq);
1222
1223 #else 
1224                 vbus_ext->sim = cam_sim_alloc(hpt_action, hpt_poll, driver_name,
1225                                 vbus_ext, unit_number, &Giant, os_max_queue_comm, /*tagged*/8,  devq);
1226 #endif
1227                 unit_number++;
1228                 if (!vbus_ext->sim) {
1229                         os_printk("cam_sim_alloc failed");
1230                         cam_simq_free(devq);
1231                         return ;
1232                 }
1233
1234                 hpt_lock_vbus(vbus_ext);
1235                 if (xpt_bus_register(vbus_ext->sim, NULL, 0) != CAM_SUCCESS) {
1236                         hpt_unlock_vbus(vbus_ext);
1237                         os_printk("xpt_bus_register failed");
1238                         cam_sim_free(vbus_ext->sim, /*free devq*/ TRUE);
1239                         vbus_ext->sim = NULL;
1240                         return ;
1241                 }
1242         
1243                 if (xpt_create_path(&vbus_ext->path, /*periph */ NULL,
1244                                 cam_sim_path(vbus_ext->sim), CAM_TARGET_WILDCARD,
1245                                 CAM_LUN_WILDCARD) != CAM_REQ_CMP)
1246                 {
1247                         hpt_unlock_vbus(vbus_ext);
1248                         os_printk("xpt_create_path failed");
1249                         xpt_bus_deregister(cam_sim_path(vbus_ext->sim));
1250                         cam_sim_free(vbus_ext->sim, /*free_devq*/TRUE);
1251                         vbus_ext->sim = NULL;
1252                         return ;
1253                 }
1254
1255                 xpt_setup_ccb(&ccb.ccb_h, vbus_ext->path, /*priority*/5);
1256                 ccb.ccb_h.func_code = XPT_SASYNC_CB;
1257                 ccb.event_enable = AC_LOST_DEVICE;
1258                 ccb.callback = hpt_async;
1259                 ccb.callback_arg = vbus_ext;
1260                 xpt_action((union ccb *)&ccb);
1261                 hpt_unlock_vbus(vbus_ext);
1262
1263                 for (hba = vbus_ext->hba_list; hba; hba = hba->next) {
1264                         int rid = 0;
1265                         if ((hba->irq_res = bus_alloc_resource_any(hba->pcidev,
1266                                 SYS_RES_IRQ, &rid, RF_SHAREABLE | RF_ACTIVE)) == NULL)
1267                         {
1268                                 os_printk("can't allocate interrupt");
1269                                 return ;
1270                         }
1271 #if (__FreeBSD_version >= 1000510)
1272                         if (bus_setup_intr(hba->pcidev, hba->irq_res, INTR_TYPE_CAM | INTR_MPSAFE,
1273 #else 
1274                         if (bus_setup_intr(hba->pcidev, hba->irq_res, INTR_TYPE_CAM,
1275 #endif
1276                                 NULL, hpt_pci_intr, vbus_ext, &hba->irq_handle)) 
1277                         {
1278                                 os_printk("can't set up interrupt");
1279                                 return ;
1280                         }
1281                         hba->ldm_adapter.him->intr_control(hba->ldm_adapter.him_handle, HPT_TRUE);
1282
1283                 }
1284
1285                 vbus_ext->shutdown_eh = EVENTHANDLER_REGISTER(shutdown_final, 
1286                                                                         hpt_shutdown_vbus, vbus_ext, SHUTDOWN_PRI_DEFAULT);
1287                 if (!vbus_ext->shutdown_eh)
1288                         os_printk("Shutdown event registration failed");
1289         }
1290         
1291         ldm_for_each_vbus(vbus, vbus_ext) {
1292                 TASK_INIT(&vbus_ext->worker, 0, (task_fn_t *)hpt_do_tasks, vbus_ext);
1293                 if (vbus_ext->tasks)
1294                         TASK_ENQUEUE(&vbus_ext->worker);
1295         }       
1296
1297         make_dev(&hpt_cdevsw, DRIVER_MINOR, UID_ROOT, GID_OPERATOR,
1298             S_IRUSR | S_IWUSR, "%s", driver_name);
1299 }
1300
1301 #if defined(KLD_MODULE)
1302
1303 typedef struct driverlink *driverlink_t;
1304 struct driverlink {
1305         kobj_class_t    driver;
1306         TAILQ_ENTRY(driverlink) link;   /* list of drivers in devclass */
1307 };
1308
1309 typedef TAILQ_HEAD(driver_list, driverlink) driver_list_t;
1310
1311 struct devclass {
1312         TAILQ_ENTRY(devclass) link;
1313         devclass_t      parent;         /* parent in devclass hierarchy */
1314         driver_list_t   drivers;     /* bus devclasses store drivers for bus */
1315         char            *name;
1316         device_t        *devices;       /* array of devices indexed by unit */
1317         int             maxunit;        /* size of devices array */
1318 };
1319
1320 static void override_kernel_driver(void)
1321 {
1322         driverlink_t dl, dlfirst;
1323         driver_t *tmpdriver;
1324         devclass_t dc = devclass_find("pci");
1325         
1326         if (dc){
1327                 dlfirst = TAILQ_FIRST(&dc->drivers);
1328                 for (dl = dlfirst; dl; dl = TAILQ_NEXT(dl, link)) {
1329                         if(strcmp(dl->driver->name, driver_name) == 0) {
1330                                 tmpdriver=dl->driver;
1331                                 dl->driver=dlfirst->driver;
1332                                 dlfirst->driver=tmpdriver;
1333                                 break;
1334                         }
1335                 }
1336         }
1337 }
1338
1339 #else 
1340 #define override_kernel_driver()
1341 #endif
1342
1343 static void hpt_init(void *dummy)
1344 {
1345         if (bootverbose)
1346                 os_printk("%s %s", driver_name_long, driver_ver);
1347
1348         override_kernel_driver();
1349         init_config();
1350
1351         hpt_ich.ich_func = hpt_final_init;
1352         hpt_ich.ich_arg = NULL;
1353         if (config_intrhook_establish(&hpt_ich) != 0) {
1354                 printf("%s: cannot establish configuration hook\n",
1355                     driver_name_long);
1356         }
1357
1358 }
1359 SYSINIT(hptinit, SI_SUB_CONFIGURE, SI_ORDER_FIRST, hpt_init, NULL);
1360
1361 /*
1362  * CAM driver interface
1363  */
1364 static device_method_t driver_methods[] = {
1365         /* Device interface */
1366         DEVMETHOD(device_probe,         hpt_probe),
1367         DEVMETHOD(device_attach,        hpt_attach),
1368         DEVMETHOD(device_detach,        hpt_detach),
1369         DEVMETHOD(device_shutdown,      hpt_shutdown),
1370         { 0, 0 }
1371 };
1372
1373 static driver_t hpt_pci_driver = {
1374         driver_name,
1375         driver_methods,
1376         sizeof(HBA)
1377 };
1378
1379 static devclass_t       hpt_devclass;
1380
1381 #ifndef TARGETNAME
1382 #error "no TARGETNAME found"
1383 #endif
1384
1385 /* use this to make TARGETNAME be expanded */
1386 #define __DRIVER_MODULE(p1, p2, p3, p4, p5, p6) DRIVER_MODULE(p1, p2, p3, p4, p5, p6)
1387 #define __MODULE_VERSION(p1, p2) MODULE_VERSION(p1, p2)
1388 #define __MODULE_DEPEND(p1, p2, p3, p4, p5) MODULE_DEPEND(p1, p2, p3, p4, p5)
1389 __DRIVER_MODULE(TARGETNAME, pci, hpt_pci_driver, hpt_devclass, 0, 0);
1390 __MODULE_VERSION(TARGETNAME, 1);
1391 __MODULE_DEPEND(TARGETNAME, cam, 1, 1, 1);
1392
1393 static int hpt_open(struct cdev *dev, int flags, int devtype, struct thread *td)
1394 {
1395         return 0;
1396 }
1397
1398 static int hpt_close(struct cdev *dev, int flags, int devtype, struct thread *td)
1399 {
1400         return 0;
1401 }
1402
1403 static int hpt_ioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag, struct thread *td)
1404 {
1405         PHPT_IOCTL_PARAM piop=(PHPT_IOCTL_PARAM)data;
1406         IOCTL_ARG ioctl_args;
1407         HPT_U32 bytesReturned = 0;
1408
1409         switch (cmd){
1410         case HPT_DO_IOCONTROL:
1411         {       
1412                 if (piop->Magic == HPT_IOCTL_MAGIC || piop->Magic == HPT_IOCTL_MAGIC32) {
1413                         KdPrint(("<8>ioctl=%x in=%p len=%d out=%p len=%d\n",
1414                                 piop->dwIoControlCode,
1415                                 piop->lpInBuffer,
1416                                 piop->nInBufferSize,
1417                                 piop->lpOutBuffer,
1418                                 piop->nOutBufferSize));
1419                         
1420                 memset(&ioctl_args, 0, sizeof(ioctl_args));
1421                 
1422                 ioctl_args.dwIoControlCode = piop->dwIoControlCode;
1423                 ioctl_args.nInBufferSize = piop->nInBufferSize;
1424                 ioctl_args.nOutBufferSize = piop->nOutBufferSize;
1425                 ioctl_args.lpBytesReturned = &bytesReturned;
1426
1427                 if (ioctl_args.nInBufferSize) {
1428                         ioctl_args.lpInBuffer = malloc(ioctl_args.nInBufferSize, M_DEVBUF, M_WAITOK);
1429                         if (!ioctl_args.lpInBuffer)
1430                                 goto invalid;
1431                         if (copyin((void*)piop->lpInBuffer,
1432                                         ioctl_args.lpInBuffer, piop->nInBufferSize))
1433                                 goto invalid;
1434                 }
1435         
1436                 if (ioctl_args.nOutBufferSize) {
1437                         ioctl_args.lpOutBuffer = malloc(ioctl_args.nOutBufferSize, M_DEVBUF, M_WAITOK | M_ZERO);
1438                         if (!ioctl_args.lpOutBuffer)
1439                                 goto invalid;
1440                 }
1441                 
1442 #if __FreeBSD_version < 1000510
1443                 mtx_lock(&Giant);
1444 #endif
1445
1446                 hpt_do_ioctl(&ioctl_args);
1447         
1448 #if __FreeBSD_version < 1000510
1449                 mtx_unlock(&Giant);
1450 #endif
1451
1452                 if (ioctl_args.result==HPT_IOCTL_RESULT_OK) {
1453                         if (piop->nOutBufferSize) {
1454                                 if (copyout(ioctl_args.lpOutBuffer,
1455                                         (void*)piop->lpOutBuffer, piop->nOutBufferSize))
1456                                         goto invalid;
1457                         }
1458                         if (piop->lpBytesReturned) {
1459                                 if (copyout(&bytesReturned,
1460                                         (void*)piop->lpBytesReturned, sizeof(HPT_U32)))
1461                                         goto invalid;
1462                         }
1463                         if (ioctl_args.lpInBuffer) free(ioctl_args.lpInBuffer, M_DEVBUF);
1464                         if (ioctl_args.lpOutBuffer) free(ioctl_args.lpOutBuffer, M_DEVBUF);
1465                         return 0;
1466                 }
1467 invalid:
1468                 if (ioctl_args.lpInBuffer) free(ioctl_args.lpInBuffer, M_DEVBUF);
1469                 if (ioctl_args.lpOutBuffer) free(ioctl_args.lpOutBuffer, M_DEVBUF);
1470                 return EFAULT;
1471         }
1472         return EFAULT;
1473         }
1474
1475         case HPT_SCAN_BUS:
1476         {
1477                 return hpt_rescan_bus();
1478         }
1479         default:
1480                 KdPrint(("invalid command!"));
1481                 return EFAULT;
1482         }       
1483
1484 }
1485
1486 static int      hpt_rescan_bus(void)
1487 {
1488         union ccb                       *ccb;
1489         PVBUS                           vbus;
1490         PVBUS_EXT                       vbus_ext;       
1491 #if (__FreeBSD_version < 1000510)               
1492         mtx_lock(&Giant);
1493 #endif
1494         ldm_for_each_vbus(vbus, vbus_ext) {
1495                 if ((ccb = xpt_alloc_ccb()) == NULL)
1496                 {
1497                         return(ENOMEM);
1498                 }
1499 #if (__FreeBSD_version < 1000510)
1500                 if (xpt_create_path(&ccb->ccb_h.path, xpt_periph, cam_sim_path(vbus_ext->sim),
1501 #else 
1502                 if (xpt_create_path(&ccb->ccb_h.path, NULL, cam_sim_path(vbus_ext->sim),
1503 #endif
1504                         CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD) != CAM_REQ_CMP)  
1505                 {
1506                         xpt_free_ccb(ccb);
1507                         return(EIO);
1508                 }
1509                 xpt_rescan(ccb);
1510         }
1511 #if (__FreeBSD_version < 1000510)
1512         mtx_unlock(&Giant);
1513 #endif
1514         return(0);      
1515 }
1516