]> CyberLeo.Net >> Repos - FreeBSD/releng/10.0.git/blob - sys/dev/hyperv/storvsc/hv_storvsc_drv_freebsd.c
- Copy stable/10 (r259064) to releng/10.0 as part of the
[FreeBSD/releng/10.0.git] / sys / dev / hyperv / storvsc / hv_storvsc_drv_freebsd.c
1 /*-
2  * Copyright (c) 2009-2012 Microsoft Corp.
3  * Copyright (c) 2012 NetApp Inc.
4  * Copyright (c) 2012 Citrix 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 unmodified, this list of conditions, and the following
12  *    disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28
29 /**
30  * StorVSC driver for Hyper-V.  This driver presents a SCSI HBA interface
31  * to the Comman Access Method (CAM) layer.  CAM control blocks (CCBs) are
32  * converted into VSCSI protocol messages which are delivered to the parent
33  * partition StorVSP driver over the Hyper-V VMBUS.
34  */
35 #include <sys/cdefs.h>
36 __FBSDID("$FreeBSD$");
37
38 #include <sys/param.h>
39 #include <sys/proc.h>
40 #include <sys/condvar.h>
41 #include <sys/systm.h>
42 #include <sys/sockio.h>
43 #include <sys/mbuf.h>
44 #include <sys/malloc.h>
45 #include <sys/module.h>
46 #include <sys/kernel.h>
47 #include <sys/queue.h>
48 #include <sys/lock.h>
49 #include <sys/sx.h>
50 #include <sys/taskqueue.h>
51 #include <sys/bus.h>
52 #include <sys/mutex.h>
53 #include <sys/callout.h>
54 #include <vm/vm.h>
55 #include <vm/pmap.h>
56 #include <sys/lock.h>
57 #include <sys/sema.h>
58
59 #include <cam/cam.h>
60 #include <cam/cam_ccb.h>
61 #include <cam/cam_periph.h>
62 #include <cam/cam_sim.h>
63 #include <cam/cam_xpt_sim.h>
64 #include <cam/cam_xpt_internal.h>
65 #include <cam/cam_debug.h>
66 #include <cam/scsi/scsi_all.h>
67 #include <cam/scsi/scsi_message.h>
68
69
70 #include <dev/hyperv/include/hyperv.h>
71 #include "hv_vstorage.h"
72
73 #define STORVSC_RINGBUFFER_SIZE         (20*PAGE_SIZE)
74 #define STORVSC_MAX_LUNS_PER_TARGET     (64)
75 #define STORVSC_MAX_IO_REQUESTS         (STORVSC_MAX_LUNS_PER_TARGET * 2)
76 #define BLKVSC_MAX_IDE_DISKS_PER_TARGET (1)
77 #define BLKVSC_MAX_IO_REQUESTS          STORVSC_MAX_IO_REQUESTS
78 #define STORVSC_MAX_TARGETS             (1)
79
80 struct storvsc_softc;
81
82 enum storvsc_request_type {
83         WRITE_TYPE,
84         READ_TYPE,
85         UNKNOWN_TYPE
86 };
87
88 struct hv_storvsc_request {
89         LIST_ENTRY(hv_storvsc_request) link;
90         struct vstor_packet     vstor_packet;
91         hv_vmbus_multipage_buffer data_buf;
92         void *sense_data;
93         uint8_t sense_info_len;
94         uint8_t retries;
95         union ccb *ccb;
96         struct storvsc_softc *softc;
97         struct callout callout;
98         struct sema synch_sema; /*Synchronize the request/response if needed */
99 };
100
101 struct storvsc_softc {
102         struct hv_device                *hs_dev;
103         LIST_HEAD(, hv_storvsc_request) hs_free_list;
104         struct mtx                      hs_lock;
105         struct storvsc_driver_props     *hs_drv_props;
106         int                             hs_unit;
107         uint32_t                        hs_frozen;
108         struct cam_sim                  *hs_sim;
109         struct cam_path                 *hs_path;
110         uint32_t                        hs_num_out_reqs;
111         boolean_t                       hs_destroy;
112         boolean_t                       hs_drain_notify;
113         struct sema                     hs_drain_sema;  
114         struct hv_storvsc_request       hs_init_req;
115         struct hv_storvsc_request       hs_reset_req;
116 };
117
118
119 /**
120  * HyperV storvsc timeout testing cases:
121  * a. IO returned after first timeout;
122  * b. IO returned after second timeout and queue freeze;
123  * c. IO returned while timer handler is running
124  * The first can be tested by "sg_senddiag -vv /dev/daX",
125  * and the second and third can be done by
126  * "sg_wr_mode -v -p 08 -c 0,1a -m 0,ff /dev/daX".
127  */ 
128 #define HVS_TIMEOUT_TEST 0
129
130 /*
131  * Bus/adapter reset functionality on the Hyper-V host is
132  * buggy and it will be disabled until
133  * it can be further tested.
134  */
135 #define HVS_HOST_RESET 0
136
137 struct storvsc_driver_props {
138         char            *drv_name;
139         char            *drv_desc;
140         uint8_t         drv_max_luns_per_target;
141         uint8_t         drv_max_ios_per_target; 
142         uint32_t        drv_ringbuffer_size;
143 };
144
145 enum hv_storage_type {
146         DRIVER_BLKVSC,
147         DRIVER_STORVSC,
148         DRIVER_UNKNOWN
149 };
150
151 #define HS_MAX_ADAPTERS 10
152
153 /* {ba6163d9-04a1-4d29-b605-72e2ffb1dc7f} */
154 static const hv_guid gStorVscDeviceType={
155         .data = {0xd9, 0x63, 0x61, 0xba, 0xa1, 0x04, 0x29, 0x4d,
156                  0xb6, 0x05, 0x72, 0xe2, 0xff, 0xb1, 0xdc, 0x7f}
157 };
158
159 /* {32412632-86cb-44a2-9b5c-50d1417354f5} */
160 static const hv_guid gBlkVscDeviceType={
161         .data = {0x32, 0x26, 0x41, 0x32, 0xcb, 0x86, 0xa2, 0x44,
162                  0x9b, 0x5c, 0x50, 0xd1, 0x41, 0x73, 0x54, 0xf5}
163 };
164
165 static struct storvsc_driver_props g_drv_props_table[] = {
166         {"blkvsc", "Hyper-V IDE Storage Interface",
167          BLKVSC_MAX_IDE_DISKS_PER_TARGET, BLKVSC_MAX_IO_REQUESTS,
168          STORVSC_RINGBUFFER_SIZE},
169         {"storvsc", "Hyper-V SCSI Storage Interface",
170          STORVSC_MAX_LUNS_PER_TARGET, STORVSC_MAX_IO_REQUESTS,
171          STORVSC_RINGBUFFER_SIZE}
172 };
173
174 static struct storvsc_softc *hs_softc[HS_MAX_ADAPTERS];
175
176 /* static functions */
177 static int storvsc_probe(device_t dev);
178 static int storvsc_attach(device_t dev);
179 static int storvsc_detach(device_t dev);
180 static void storvsc_poll(struct cam_sim * sim);
181 static void storvsc_action(struct cam_sim * sim, union ccb * ccb);
182 static void scan_for_luns(struct storvsc_softc * sc);
183 static void create_storvsc_request(union ccb *ccb, struct hv_storvsc_request *reqp);
184 static void storvsc_free_request(struct storvsc_softc *sc, struct hv_storvsc_request *reqp);
185 static enum hv_storage_type storvsc_get_storage_type(device_t dev);
186 static void hv_storvsc_on_channel_callback(void *context);
187 static void hv_storvsc_on_iocompletion( struct storvsc_softc *sc,
188                                         struct vstor_packet *vstor_packet,
189                                         struct hv_storvsc_request *request);
190 static int hv_storvsc_connect_vsp(struct hv_device *device);
191 static void storvsc_io_done(struct hv_storvsc_request *reqp);
192
193 static device_method_t storvsc_methods[] = {
194         /* Device interface */
195         DEVMETHOD(device_probe,         storvsc_probe),
196         DEVMETHOD(device_attach,        storvsc_attach),
197         DEVMETHOD(device_detach,        storvsc_detach),
198         DEVMETHOD(device_shutdown,      bus_generic_shutdown),
199         DEVMETHOD_END
200 };
201
202 static driver_t storvsc_driver = {
203         "storvsc", storvsc_methods, sizeof(struct storvsc_softc),
204 };
205
206 static devclass_t storvsc_devclass;
207 DRIVER_MODULE(storvsc, vmbus, storvsc_driver, storvsc_devclass, 0, 0);
208 MODULE_VERSION(storvsc, 1);
209 MODULE_DEPEND(storvsc, vmbus, 1, 1, 1);
210
211
212 /**
213  * The host is capable of sending messages to us that are 
214  * completely unsolicited. So, we need to address the race
215  * condition where we may be in the process of unloading the
216  * driver when the host may send us an unsolicited message.
217  * We address this issue by implementing a sequentially
218  * consistent protocol:
219  *
220  * 1. Channel callback is invoked while holding the the channel lock
221  *    and an unloading driver will reset the channel callback under
222  *    the protection of this channel lock.
223  *
224  * 2. To ensure bounded wait time for unloading a driver, we don't
225  *    permit outgoing traffic once the device is marked as being
226  *    destroyed.
227  *
228  * 3. Once the device is marked as being destroyed, we only
229  *    permit incoming traffic to properly account for 
230  *    packets already sent out.
231  */
232 static inline struct storvsc_softc *
233 get_stor_device(struct hv_device *device,
234                                 boolean_t outbound)
235 {
236         struct storvsc_softc *sc;
237
238         sc = device_get_softc(device->device);
239         if (sc == NULL) {
240                 return NULL;
241         }
242
243         if (outbound) {
244                 /*
245                  * Here we permit outgoing I/O only
246                  * if the device is not being destroyed.
247                  */
248
249                 if (sc->hs_destroy) {
250                         sc = NULL;
251                 }
252         } else {
253                 /*
254                  * inbound case; if being destroyed
255                  * only permit to account for
256                  * messages already sent out.
257                  */
258                 if (sc->hs_destroy && (sc->hs_num_out_reqs == 0)) {
259                         sc = NULL;
260                 }
261         }
262         return sc;
263 }
264
265 /**
266  * @brief initialize channel connection to parent partition
267  *
268  * @param dev  a Hyper-V device pointer
269  * @returns  0 on success, non-zero error on failure
270  */
271 static int
272 hv_storvsc_channel_init(struct hv_device *dev)
273 {
274         int ret = 0;
275         struct hv_storvsc_request *request;
276         struct vstor_packet *vstor_packet;
277         struct storvsc_softc *sc;
278
279         sc = get_stor_device(dev, TRUE);
280         if (sc == NULL) {
281                 return ENODEV;
282         }
283
284         request = &sc->hs_init_req;
285         memset(request, 0, sizeof(struct hv_storvsc_request));
286         vstor_packet = &request->vstor_packet;
287         request->softc = sc;
288
289         /**
290          * Initiate the vsc/vsp initialization protocol on the open channel
291          */
292         sema_init(&request->synch_sema, 0, ("stor_synch_sema"));
293
294         vstor_packet->operation = VSTOR_OPERATION_BEGININITIALIZATION;
295         vstor_packet->flags = REQUEST_COMPLETION_FLAG;
296
297
298         ret = hv_vmbus_channel_send_packet(
299                         dev->channel,
300                         vstor_packet,
301                         sizeof(struct vstor_packet),
302                         (uint64_t)request,
303                         HV_VMBUS_PACKET_TYPE_DATA_IN_BAND,
304                         HV_VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
305
306         if (ret != 0) {
307                 goto cleanup;
308         }
309
310         ret = sema_timedwait(&request->synch_sema, 500); /* KYS 5 seconds */
311
312         if (ret != 0) {
313                 goto cleanup;
314         }
315
316         if (vstor_packet->operation != VSTOR_OPERATION_COMPLETEIO ||
317                 vstor_packet->status != 0) {
318                 goto cleanup;
319         }
320
321         /* reuse the packet for version range supported */
322
323         memset(vstor_packet, 0, sizeof(struct vstor_packet));
324         vstor_packet->operation = VSTOR_OPERATION_QUERYPROTOCOLVERSION;
325         vstor_packet->flags = REQUEST_COMPLETION_FLAG;
326
327         vstor_packet->u.version.major_minor = VMSTOR_PROTOCOL_VERSION_CURRENT;
328
329         /* revision is only significant for Windows guests */
330         vstor_packet->u.version.revision = 0;
331
332         ret = hv_vmbus_channel_send_packet(
333                         dev->channel,
334                         vstor_packet,
335                         sizeof(struct vstor_packet),
336                         (uint64_t)request,
337                         HV_VMBUS_PACKET_TYPE_DATA_IN_BAND,
338                         HV_VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
339
340         if (ret != 0) {
341                 goto cleanup;
342         }
343
344         ret = sema_timedwait(&request->synch_sema, 500); /* KYS 5 seconds */
345
346         if (ret) {
347                 goto cleanup;
348         }
349
350         /* TODO: Check returned version */
351         if (vstor_packet->operation != VSTOR_OPERATION_COMPLETEIO ||
352                 vstor_packet->status != 0) {
353                 goto cleanup;
354         }
355
356         /**
357          * Query channel properties
358          */
359         memset(vstor_packet, 0, sizeof(struct vstor_packet));
360         vstor_packet->operation = VSTOR_OPERATION_QUERYPROPERTIES;
361         vstor_packet->flags = REQUEST_COMPLETION_FLAG;
362
363         ret = hv_vmbus_channel_send_packet(
364                                 dev->channel,
365                                 vstor_packet,
366                                 sizeof(struct vstor_packet),
367                                 (uint64_t)request,
368                                 HV_VMBUS_PACKET_TYPE_DATA_IN_BAND,
369                                 HV_VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
370
371         if ( ret != 0) {
372                 goto cleanup;
373         }
374
375         ret = sema_timedwait(&request->synch_sema, 500); /* KYS 5 seconds */
376
377         if (ret != 0) {
378                 goto cleanup;
379         }
380
381         /* TODO: Check returned version */
382         if (vstor_packet->operation != VSTOR_OPERATION_COMPLETEIO ||
383                 vstor_packet->status != 0) {
384                 goto cleanup;
385         }
386
387         memset(vstor_packet, 0, sizeof(struct vstor_packet));
388         vstor_packet->operation = VSTOR_OPERATION_ENDINITIALIZATION;
389         vstor_packet->flags = REQUEST_COMPLETION_FLAG;
390
391         ret = hv_vmbus_channel_send_packet(
392                         dev->channel,
393                         vstor_packet,
394                         sizeof(struct vstor_packet),
395                         (uint64_t)request,
396                         HV_VMBUS_PACKET_TYPE_DATA_IN_BAND,
397                         HV_VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
398
399         if (ret != 0) {
400                 goto cleanup;
401         }
402
403         ret = sema_timedwait(&request->synch_sema, 500); /* KYS 5 seconds */
404
405         if (ret != 0) {
406                 goto cleanup;
407         }
408
409         if (vstor_packet->operation != VSTOR_OPERATION_COMPLETEIO ||
410                 vstor_packet->status != 0) {
411                 goto cleanup;
412         }
413
414 cleanup:
415         sema_destroy(&request->synch_sema);
416         return (ret);
417 }
418
419 /**
420  * @brief Open channel connection to paraent partition StorVSP driver
421  *
422  * Open and initialize channel connection to parent partition StorVSP driver.
423  *
424  * @param pointer to a Hyper-V device
425  * @returns 0 on success, non-zero error on failure
426  */
427 static int
428 hv_storvsc_connect_vsp(struct hv_device *dev)
429 {       
430         int ret = 0;
431         struct vmstor_chan_props props;
432         struct storvsc_softc *sc;
433
434         sc = device_get_softc(dev->device);
435                 
436         memset(&props, 0, sizeof(struct vmstor_chan_props));
437
438         /*
439          * Open the channel
440          */
441
442         ret = hv_vmbus_channel_open(
443                 dev->channel,
444                 sc->hs_drv_props->drv_ringbuffer_size,
445                 sc->hs_drv_props->drv_ringbuffer_size,
446                 (void *)&props,
447                 sizeof(struct vmstor_chan_props),
448                 hv_storvsc_on_channel_callback,
449                 dev);
450
451
452         if (ret != 0) {
453                 return ret;
454         }
455
456         ret = hv_storvsc_channel_init(dev);
457
458         return (ret);
459 }
460
461 #if HVS_HOST_RESET
462 static int
463 hv_storvsc_host_reset(struct hv_device *dev)
464 {
465         int ret = 0;
466         struct storvsc_softc *sc;
467
468         struct hv_storvsc_request *request;
469         struct vstor_packet *vstor_packet;
470
471         sc = get_stor_device(dev, TRUE);
472         if (sc == NULL) {
473                 return ENODEV;
474         }
475
476         request = &sc->hs_reset_req;
477         request->softc = sc;
478         vstor_packet = &request->vstor_packet;
479
480         sema_init(&request->synch_sema, 0, "stor synch sema");
481
482         vstor_packet->operation = VSTOR_OPERATION_RESETBUS;
483         vstor_packet->flags = REQUEST_COMPLETION_FLAG;
484
485         ret = hv_vmbus_channel_send_packet(dev->channel,
486                         vstor_packet,
487                         sizeof(struct vstor_packet),
488                         (uint64_t)&sc->hs_reset_req,
489                         HV_VMBUS_PACKET_TYPE_DATA_IN_BAND,
490                         HV_VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
491
492         if (ret != 0) {
493                 goto cleanup;
494         }
495
496         ret = sema_timedwait(&request->synch_sema, 500); /* KYS 5 seconds */
497
498         if (ret) {
499                 goto cleanup;
500         }
501
502
503         /*
504          * At this point, all outstanding requests in the adapter 
505          * should have been flushed out and return to us
506          */
507
508 cleanup:
509         sema_destroy(&request->synch_sema);
510         return (ret);
511 }
512 #endif /* HVS_HOST_RESET */
513
514 /**
515  * @brief Function to initiate an I/O request
516  *
517  * @param device Hyper-V device pointer
518  * @param request pointer to a request structure
519  * @returns 0 on success, non-zero error on failure
520  */
521 static int
522 hv_storvsc_io_request(struct hv_device *device,
523                                           struct hv_storvsc_request *request)
524 {
525         struct storvsc_softc *sc;
526         struct vstor_packet *vstor_packet = &request->vstor_packet;
527         int ret = 0;
528
529         sc = get_stor_device(device, TRUE);
530
531         if (sc == NULL) {
532                 return ENODEV;
533         }
534
535         vstor_packet->flags |= REQUEST_COMPLETION_FLAG;
536
537         vstor_packet->u.vm_srb.length = sizeof(struct vmscsi_req);
538         
539         vstor_packet->u.vm_srb.sense_info_len = SENSE_BUFFER_SIZE;
540
541         vstor_packet->u.vm_srb.transfer_len = request->data_buf.length;
542
543         vstor_packet->operation = VSTOR_OPERATION_EXECUTESRB;
544
545
546         mtx_unlock(&request->softc->hs_lock);
547         if (request->data_buf.length) {
548                 ret = hv_vmbus_channel_send_packet_multipagebuffer(
549                                 device->channel,
550                                 &request->data_buf,
551                                 vstor_packet, 
552                                 sizeof(struct vstor_packet), 
553                                 (uint64_t)request);
554
555         } else {
556                 ret = hv_vmbus_channel_send_packet(
557                         device->channel,
558                         vstor_packet,
559                         sizeof(struct vstor_packet),
560                         (uint64_t)request,
561                         HV_VMBUS_PACKET_TYPE_DATA_IN_BAND,
562                         HV_VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
563         }
564         mtx_lock(&request->softc->hs_lock);
565
566         if (ret != 0) {
567                 printf("Unable to send packet %p ret %d", vstor_packet, ret);
568         } else {
569                 atomic_add_int(&sc->hs_num_out_reqs, 1);
570         }
571
572         return (ret);
573 }
574
575
576 /**
577  * Process IO_COMPLETION_OPERATION and ready
578  * the result to be completed for upper layer
579  * processing by the CAM layer.
580  */
581 static void
582 hv_storvsc_on_iocompletion(struct storvsc_softc *sc,
583                            struct vstor_packet *vstor_packet,
584                            struct hv_storvsc_request *request)
585 {
586         struct vmscsi_req *vm_srb;
587
588         vm_srb = &vstor_packet->u.vm_srb;
589
590         request->sense_info_len = 0;
591         if (((vm_srb->scsi_status & 0xFF) == SCSI_STATUS_CHECK_COND) &&
592                         (vm_srb->srb_status & SRB_STATUS_AUTOSENSE_VALID)) {
593                 /* Autosense data available */
594
595                 KASSERT(vm_srb->sense_info_len <= request->sense_info_len,
596                                 ("vm_srb->sense_info_len <= "
597                                  "request->sense_info_len"));
598
599                 memcpy(request->sense_data, vm_srb->u.sense_data,
600                         vm_srb->sense_info_len);
601
602                 request->sense_info_len = vm_srb->sense_info_len;
603         }
604
605         /* Complete request by passing to the CAM layer */
606         storvsc_io_done(request);
607         atomic_subtract_int(&sc->hs_num_out_reqs, 1);
608         if (sc->hs_drain_notify && (sc->hs_num_out_reqs == 0)) {
609                 sema_post(&sc->hs_drain_sema);
610         }
611 }
612
613 static void
614 hv_storvsc_on_channel_callback(void *context)
615 {
616         int ret = 0;
617         struct hv_device *device = (struct hv_device *)context;
618         struct storvsc_softc *sc;
619         uint32_t bytes_recvd;
620         uint64_t request_id;
621         uint8_t packet[roundup2(sizeof(struct vstor_packet), 8)];
622         struct hv_storvsc_request *request;
623         struct vstor_packet *vstor_packet;
624
625         sc = get_stor_device(device, FALSE);
626         if (sc == NULL) {
627                 return;
628         }
629
630         KASSERT(device, ("device"));
631
632         ret = hv_vmbus_channel_recv_packet(
633                         device->channel,
634                         packet,
635                         roundup2(sizeof(struct vstor_packet), 8),
636                         &bytes_recvd,
637                         &request_id);
638
639         while ((ret == 0) && (bytes_recvd > 0)) {
640                 request = (struct hv_storvsc_request *)request_id;
641                 KASSERT(request, ("request"));
642
643                 if ((request == &sc->hs_init_req) ||
644                         (request == &sc->hs_reset_req)) {
645                         memcpy(&request->vstor_packet, packet,
646                                    sizeof(struct vstor_packet));
647                         sema_post(&request->synch_sema); 
648                 } else {
649                         vstor_packet = (struct vstor_packet *)packet;
650                         switch(vstor_packet->operation) {
651                         case VSTOR_OPERATION_COMPLETEIO:
652                                 hv_storvsc_on_iocompletion(sc,
653                                                         vstor_packet, request);
654                                 break;
655                         case VSTOR_OPERATION_REMOVEDEVICE:
656                                 /* TODO: implement */
657                                 break;
658                         default:
659                                 break;
660                         }                       
661                 }
662                 ret = hv_vmbus_channel_recv_packet(
663                                 device->channel,
664                                 packet,
665                                 roundup2(sizeof(struct vstor_packet), 8),
666                                 &bytes_recvd,
667                                 &request_id);
668         }
669 }
670
671 /**
672  * @brief callback function for completing a single LUN scan
673  *
674  * This function is responsible for waking up the executer of
675  * the scan LUN CCB action (cam_periph_runccb.)  cam_periph_ccbwait
676  * sleeps on the mutex being signaled.
677  *
678  * @param periph a pointer to a CAM peripheral
679  * @param done_ccb pointer to CAM control block
680  */
681 static void
682 storvsc_xptdone(struct cam_periph *periph, union ccb *done_ccb)
683 {
684         wakeup(&done_ccb->ccb_h.cbfcnp);
685 }
686
687 /**
688  * @brief scan for attached logical unit numbers (LUNs)
689  *
690  * In Hyper-V there is no backend changed device operation which
691  * presents FreeBSD with a list of devices to connect.  The result is
692  * that we have to scan for a list of luns in the storvsc_attach()
693  * routine.  There is only one SCSI target, so scan for the maximum
694  * number of luns.
695  *
696  * @param pointer to softc
697  */
698 static void
699 scan_for_luns(struct storvsc_softc *sc)
700 {
701         union ccb *request_ccb;
702         struct cam_path *path = sc->hs_path;
703         struct cam_path *my_path = NULL;
704         cam_status status;
705         int lun_nb = 0;
706         int error;
707
708         request_ccb = malloc(sizeof(union ccb), M_CAMXPT, M_WAITOK);
709         my_path = malloc(sizeof(*my_path), M_CAMXPT, M_WAITOK);
710
711         mtx_lock(&sc->hs_lock);
712         do {
713                 /*
714                  * Scan the next LUN. Reuse path and ccb structs.
715                  */
716                 bzero(my_path, sizeof(*my_path));
717                 bzero(request_ccb, sizeof(*request_ccb));
718                 status = xpt_compile_path(my_path,
719                                   xpt_periph,
720                                   path->bus->path_id,
721                                   0,
722                                   lun_nb);
723
724                 if (status != CAM_REQ_CMP) {
725                         mtx_unlock(&sc->hs_lock);
726                         xpt_print(path, "scan_for_lunYYY: can't compile"
727                                          " path, 0x%p can't continue\n",
728                                          sc->hs_path);
729                         free(request_ccb, M_CAMXPT);
730                         free(my_path, M_CAMXPT);
731                         return;
732                 }
733
734                 xpt_setup_ccb(&request_ccb->ccb_h, my_path, 5);
735                 request_ccb->ccb_h.func_code = XPT_SCAN_LUN;
736                 request_ccb->ccb_h.cbfcnp    = storvsc_xptdone;
737                 request_ccb->crcn.flags      = CAM_FLAG_NONE;
738
739                 error = cam_periph_runccb(request_ccb, NULL, 
740                                                 CAM_FLAG_NONE, 0, NULL);
741                 KASSERT(error == 0, ("cam_periph_runccb failed %d\n", error));
742                 xpt_release_path(my_path);
743         } while ( ++lun_nb < sc->hs_drv_props->drv_max_luns_per_target);
744         mtx_unlock(&sc->hs_lock);
745         free(request_ccb, M_CAMXPT);
746         free(my_path, M_CAMXPT);
747 }
748
749 /**
750  * @brief StorVSC probe function
751  *
752  * Device probe function.  Returns 0 if the input device is a StorVSC
753  * device.  Otherwise, a ENXIO is returned.  If the input device is
754  * for BlkVSC (paravirtual IDE) device and this support is disabled in
755  * favor of the emulated ATA/IDE device, return ENXIO.
756  *
757  * @param a device
758  * @returns 0 on success, ENXIO if not a matcing StorVSC device
759  */
760 static int
761 storvsc_probe(device_t dev)
762 {
763         int ata_disk_enable = 0;
764         int ret = ENXIO;
765
766         switch (storvsc_get_storage_type(dev)) {
767         case DRIVER_BLKVSC:
768                 if(bootverbose)
769                         device_printf(dev, "DRIVER_BLKVSC-Emulated ATA/IDE probe\n");
770                 if (!getenv_int("hw.ata.disk_enable", &ata_disk_enable)) {
771                         if(bootverbose)
772                                 device_printf(dev,
773                                         "Enlightened ATA/IDE detected\n");
774                         ret = 0;
775                 } else if(bootverbose)
776                         device_printf(dev, "Emulated ATA/IDE set (hw.ata.disk_enable set)\n");
777                 break;
778         case DRIVER_STORVSC:
779                 if(bootverbose)
780                         device_printf(dev, "Enlightened SCSI device detected\n");
781                 ret = 0;
782                 break;
783         default:
784                 ret = ENXIO;
785         }
786         return (ret);
787 }
788
789 /**
790  * @brief StorVSC attach function
791  *
792  * Function responsible for allocating per-device structures,
793  * setting up CAM interfaces and scanning for available LUNs to
794  * be used for SCSI device peripherals.
795  *
796  * @param a device
797  * @returns 0 on success or an error on failure
798  */
799 static int
800 storvsc_attach(device_t dev)
801 {
802         struct hv_device *hv_dev = vmbus_get_devctx(dev);
803         enum hv_storage_type stor_type;
804         struct storvsc_softc *sc;
805         struct cam_devq *devq;
806         int ret, i;
807         struct hv_storvsc_request *reqp;
808         struct root_hold_token *root_mount_token = NULL;
809
810         /*
811          * We need to serialize storvsc attach calls.
812          */
813         root_mount_token = root_mount_hold("storvsc");
814
815         sc = device_get_softc(dev);
816         if (sc == NULL) {
817                 ret = ENOMEM;
818                 goto cleanup;
819         }
820
821         stor_type = storvsc_get_storage_type(dev);
822
823         if (stor_type == DRIVER_UNKNOWN) {
824                 ret = ENODEV;
825                 goto cleanup;
826         }
827
828         bzero(sc, sizeof(struct storvsc_softc));
829
830         /* fill in driver specific properties */
831         sc->hs_drv_props = &g_drv_props_table[stor_type];
832
833         /* fill in device specific properties */
834         sc->hs_unit     = device_get_unit(dev);
835         sc->hs_dev      = hv_dev;
836         device_set_desc(dev, g_drv_props_table[stor_type].drv_desc);
837
838         LIST_INIT(&sc->hs_free_list);
839         mtx_init(&sc->hs_lock, "hvslck", NULL, MTX_DEF);
840
841         for (i = 0; i < sc->hs_drv_props->drv_max_ios_per_target; ++i) {
842                 reqp = malloc(sizeof(struct hv_storvsc_request),
843                                  M_DEVBUF, M_WAITOK|M_ZERO);
844                 reqp->softc = sc;
845
846                 LIST_INSERT_HEAD(&sc->hs_free_list, reqp, link);
847         }
848
849         sc->hs_destroy = FALSE;
850         sc->hs_drain_notify = FALSE;
851         sema_init(&sc->hs_drain_sema, 0, "Store Drain Sema");
852
853         ret = hv_storvsc_connect_vsp(hv_dev);
854         if (ret != 0) {
855                 goto cleanup;
856         }
857
858         /*
859          * Create the device queue.
860          * Hyper-V maps each target to one SCSI HBA
861          */
862         devq = cam_simq_alloc(sc->hs_drv_props->drv_max_ios_per_target);
863         if (devq == NULL) {
864                 device_printf(dev, "Failed to alloc device queue\n");
865                 ret = ENOMEM;
866                 goto cleanup;
867         }
868
869         sc->hs_sim = cam_sim_alloc(storvsc_action,
870                                 storvsc_poll,
871                                 sc->hs_drv_props->drv_name,
872                                 sc,
873                                 sc->hs_unit,
874                                 &sc->hs_lock, 1,
875                                 sc->hs_drv_props->drv_max_ios_per_target,
876                                 devq);
877
878         if (sc->hs_sim == NULL) {
879                 device_printf(dev, "Failed to alloc sim\n");
880                 cam_simq_free(devq);
881                 ret = ENOMEM;
882                 goto cleanup;
883         }
884
885         mtx_lock(&sc->hs_lock);
886         /* bus_id is set to 0, need to get it from VMBUS channel query? */
887         if (xpt_bus_register(sc->hs_sim, dev, 0) != CAM_SUCCESS) {
888                 cam_sim_free(sc->hs_sim, /*free_devq*/TRUE);
889                 mtx_unlock(&sc->hs_lock);
890                 device_printf(dev, "Unable to register SCSI bus\n");
891                 ret = ENXIO;
892                 goto cleanup;
893         }
894
895         if (xpt_create_path(&sc->hs_path, /*periph*/NULL,
896                  cam_sim_path(sc->hs_sim),
897                 CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
898                 xpt_bus_deregister(cam_sim_path(sc->hs_sim));
899                 cam_sim_free(sc->hs_sim, /*free_devq*/TRUE);
900                 mtx_unlock(&sc->hs_lock);
901                 device_printf(dev, "Unable to create path\n");
902                 ret = ENXIO;
903                 goto cleanup;
904         }
905
906         mtx_unlock(&sc->hs_lock);
907         scan_for_luns(sc);
908         for (i = 0; (hs_softc[i] != NULL) && (i < HS_MAX_ADAPTERS); i++);
909         KASSERT(i < HS_MAX_ADAPTERS, ("storvsc_attach: hs_softc full\n"));
910         hs_softc[i] = sc;
911
912         root_mount_rel(root_mount_token);
913         return (0);
914
915
916 cleanup:
917         root_mount_rel(root_mount_token);
918         while (!LIST_EMPTY(&sc->hs_free_list)) {
919                 reqp = LIST_FIRST(&sc->hs_free_list);
920                 LIST_REMOVE(reqp, link);
921                 free(reqp, M_DEVBUF);
922         }
923         return (ret);
924 }
925
926 /**
927  * @brief StorVSC device detach function
928  *
929  * This function is responsible for safely detaching a
930  * StorVSC device.  This includes waiting for inbound responses
931  * to complete and freeing associated per-device structures.
932  *
933  * @param dev a device
934  * returns 0 on success
935  */
936 static int
937 storvsc_detach(device_t dev)
938 {
939         struct storvsc_softc *sc = device_get_softc(dev);
940         struct hv_storvsc_request *reqp = NULL;
941         struct hv_device *hv_device = vmbus_get_devctx(dev);
942
943         mtx_lock(&hv_device->channel->inbound_lock);
944         sc->hs_destroy = TRUE;
945         mtx_unlock(&hv_device->channel->inbound_lock);
946
947         /*
948          * At this point, all outbound traffic should be disabled. We
949          * only allow inbound traffic (responses) to proceed so that
950          * outstanding requests can be completed.
951          */
952
953         sc->hs_drain_notify = TRUE;
954         sema_wait(&sc->hs_drain_sema);
955         sc->hs_drain_notify = FALSE;
956
957         /*
958          * Since we have already drained, we don't need to busy wait.
959          * The call to close the channel will reset the callback
960          * under the protection of the incoming channel lock.
961          */
962
963         hv_vmbus_channel_close(hv_device->channel);
964
965         mtx_lock(&sc->hs_lock);
966         while (!LIST_EMPTY(&sc->hs_free_list)) {
967                 reqp = LIST_FIRST(&sc->hs_free_list);
968                 LIST_REMOVE(reqp, link);
969
970                 free(reqp, M_DEVBUF);
971         }
972         mtx_unlock(&sc->hs_lock);
973         return (0);
974 }
975
976 #if HVS_TIMEOUT_TEST
977 /**
978  * @brief unit test for timed out operations
979  *
980  * This function provides unit testing capability to simulate
981  * timed out operations.  Recompilation with HV_TIMEOUT_TEST=1
982  * is required.
983  *
984  * @param reqp pointer to a request structure
985  * @param opcode SCSI operation being performed
986  * @param wait if 1, wait for I/O to complete
987  */
988 static void
989 storvsc_timeout_test(struct hv_storvsc_request *reqp,
990                 uint8_t opcode, int wait)
991 {
992         int ret;
993         union ccb *ccb = reqp->ccb;
994         struct storvsc_softc *sc = reqp->softc;
995
996         if (reqp->vstor_packet.vm_srb.cdb[0] != opcode) {
997                 return;
998         }
999
1000         if (wait) {
1001                 mtx_lock(&reqp->event.mtx);
1002         }
1003         ret = hv_storvsc_io_request(sc->hs_dev, reqp);
1004         if (ret != 0) {
1005                 if (wait) {
1006                         mtx_unlock(&reqp->event.mtx);
1007                 }
1008                 printf("%s: io_request failed with %d.\n",
1009                                 __func__, ret);
1010                 ccb->ccb_h.status = CAM_PROVIDE_FAIL;
1011                 mtx_lock(&sc->hs_lock);
1012                 storvsc_free_request(sc, reqp);
1013                 xpt_done(ccb);
1014                 mtx_unlock(&sc->hs_lock);
1015                 return;
1016         }
1017
1018         if (wait) {
1019                 xpt_print(ccb->ccb_h.path,
1020                                 "%u: %s: waiting for IO return.\n",
1021                                 ticks, __func__);
1022                 ret = cv_timedwait(&reqp->event.cv, &reqp->event.mtx, 60*hz);
1023                 mtx_unlock(&reqp->event.mtx);
1024                 xpt_print(ccb->ccb_h.path, "%u: %s: %s.\n",
1025                                 ticks, __func__, (ret == 0)?
1026                                 "IO return detected" :
1027                                 "IO return not detected");
1028                 /* 
1029                  * Now both the timer handler and io done are running
1030                  * simultaneously. We want to confirm the io done always
1031                  * finishes after the timer handler exits. So reqp used by
1032                  * timer handler is not freed or stale. Do busy loop for
1033                  * another 1/10 second to make sure io done does
1034                  * wait for the timer handler to complete.
1035                  */
1036                 DELAY(100*1000);
1037                 mtx_lock(&sc->hs_lock);
1038                 xpt_print(ccb->ccb_h.path,
1039                                 "%u: %s: finishing, queue frozen %d, "
1040                                 "ccb status 0x%x scsi_status 0x%x.\n",
1041                                 ticks, __func__, sc->hs_frozen,
1042                                 ccb->ccb_h.status,
1043                                 ccb->csio.scsi_status);
1044                 mtx_unlock(&sc->hs_lock);
1045         }
1046 }
1047 #endif /* HVS_TIMEOUT_TEST */
1048
1049 /**
1050  * @brief timeout handler for requests
1051  *
1052  * This function is called as a result of a callout expiring.
1053  *
1054  * @param arg pointer to a request
1055  */
1056 static void
1057 storvsc_timeout(void *arg)
1058 {
1059         struct hv_storvsc_request *reqp = arg;
1060         struct storvsc_softc *sc = reqp->softc;
1061         union ccb *ccb = reqp->ccb;
1062
1063         if (reqp->retries == 0) {
1064                 mtx_lock(&sc->hs_lock);
1065                 xpt_print(ccb->ccb_h.path,
1066                     "%u: IO timed out (req=0x%p), wait for another %u secs.\n",
1067                     ticks, reqp, ccb->ccb_h.timeout / 1000);
1068                 cam_error_print(ccb, CAM_ESF_ALL, CAM_EPF_ALL);
1069                 mtx_unlock(&sc->hs_lock);
1070
1071                 reqp->retries++;
1072                 callout_reset(&reqp->callout,
1073                                 (ccb->ccb_h.timeout * hz) / 1000,
1074                                 storvsc_timeout, reqp);
1075 #if HVS_TIMEOUT_TEST
1076                 storvsc_timeout_test(reqp, SEND_DIAGNOSTIC, 0);
1077 #endif
1078                 return;
1079         }
1080
1081         mtx_lock(&sc->hs_lock);
1082         xpt_print(ccb->ccb_h.path,
1083                 "%u: IO (reqp = 0x%p) did not return for %u seconds, %s.\n",
1084                 ticks, reqp, ccb->ccb_h.timeout * (reqp->retries+1) / 1000,
1085                 (sc->hs_frozen == 0)?
1086                 "freezing the queue" : "the queue is already frozen");
1087         if (sc->hs_frozen == 0) {
1088                 sc->hs_frozen = 1;
1089                 xpt_freeze_simq(xpt_path_sim(ccb->ccb_h.path), 1);
1090         }
1091         mtx_unlock(&sc->hs_lock);
1092         
1093 #if HVS_TIMEOUT_TEST
1094         storvsc_timeout_test(reqp, MODE_SELECT_10, 1);
1095 #endif
1096 }
1097
1098 /**
1099  * @brief StorVSC device poll function
1100  *
1101  * This function is responsible for servicing requests when
1102  * interrupts are disabled (i.e when we are dumping core.)
1103  *
1104  * @param sim a pointer to a CAM SCSI interface module
1105  */
1106 static void
1107 storvsc_poll(struct cam_sim *sim)
1108 {
1109         struct storvsc_softc *sc = cam_sim_softc(sim);
1110
1111         mtx_assert(&sc->hs_lock, MA_OWNED);
1112         mtx_unlock(&sc->hs_lock);
1113         hv_storvsc_on_channel_callback(sc->hs_dev);
1114         mtx_lock(&sc->hs_lock);
1115 }
1116
1117 /**
1118  * @brief StorVSC device action function
1119  *
1120  * This function is responsible for handling SCSI operations which
1121  * are passed from the CAM layer.  The requests are in the form of
1122  * CAM control blocks which indicate the action being performed.
1123  * Not all actions require converting the request to a VSCSI protocol
1124  * message - these actions can be responded to by this driver.
1125  * Requests which are destined for a backend storage device are converted
1126  * to a VSCSI protocol message and sent on the channel connection associated
1127  * with this device.
1128  *
1129  * @param sim pointer to a CAM SCSI interface module
1130  * @param ccb pointer to a CAM control block
1131  */
1132 static void
1133 storvsc_action(struct cam_sim *sim, union ccb *ccb)
1134 {
1135         struct storvsc_softc *sc = cam_sim_softc(sim);
1136         int res;
1137
1138         mtx_assert(&sc->hs_lock, MA_OWNED);
1139         switch (ccb->ccb_h.func_code) {
1140         case XPT_PATH_INQ: {
1141                 struct ccb_pathinq *cpi = &ccb->cpi;
1142
1143                 cpi->version_num = 1;
1144                 cpi->hba_inquiry = PI_TAG_ABLE|PI_SDTR_ABLE;
1145                 cpi->target_sprt = 0;
1146                 cpi->hba_misc = PIM_NOBUSRESET;
1147                 cpi->hba_eng_cnt = 0;
1148                 cpi->max_target = STORVSC_MAX_TARGETS;
1149                 cpi->max_lun = sc->hs_drv_props->drv_max_luns_per_target;
1150                 cpi->initiator_id = 0;
1151                 cpi->bus_id = cam_sim_bus(sim);
1152                 cpi->base_transfer_speed = 300000;
1153                 cpi->transport = XPORT_SAS;
1154                 cpi->transport_version = 0;
1155                 cpi->protocol = PROTO_SCSI;
1156                 cpi->protocol_version = SCSI_REV_SPC2;
1157                 strncpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
1158                 strncpy(cpi->hba_vid, sc->hs_drv_props->drv_name, HBA_IDLEN);
1159                 strncpy(cpi->dev_name, cam_sim_name(sim), DEV_IDLEN);
1160                 cpi->unit_number = cam_sim_unit(sim);
1161
1162                 ccb->ccb_h.status = CAM_REQ_CMP;
1163                 xpt_done(ccb);
1164                 return;
1165         }
1166         case XPT_GET_TRAN_SETTINGS: {
1167                 struct  ccb_trans_settings *cts = &ccb->cts;
1168
1169                 cts->transport = XPORT_SAS;
1170                 cts->transport_version = 0;
1171                 cts->protocol = PROTO_SCSI;
1172                 cts->protocol_version = SCSI_REV_SPC2;
1173
1174                 /* enable tag queuing and disconnected mode */
1175                 cts->proto_specific.valid = CTS_SCSI_VALID_TQ;
1176                 cts->proto_specific.scsi.valid = CTS_SCSI_VALID_TQ;
1177                 cts->proto_specific.scsi.flags = CTS_SCSI_FLAGS_TAG_ENB;
1178                 cts->xport_specific.valid = CTS_SPI_VALID_DISC;
1179                 cts->xport_specific.spi.flags = CTS_SPI_FLAGS_DISC_ENB;
1180                         
1181                 ccb->ccb_h.status = CAM_REQ_CMP;
1182                 xpt_done(ccb);
1183                 return;
1184         }
1185         case XPT_SET_TRAN_SETTINGS:     {
1186                 ccb->ccb_h.status = CAM_REQ_CMP;
1187                 xpt_done(ccb);
1188                 return;
1189         }
1190         case XPT_CALC_GEOMETRY:{
1191                 cam_calc_geometry(&ccb->ccg, 1);
1192                 xpt_done(ccb);
1193                 return;
1194         }
1195         case  XPT_RESET_BUS:
1196         case  XPT_RESET_DEV:{
1197 #if HVS_HOST_RESET
1198                 if ((res = hv_storvsc_host_reset(sc->hs_dev)) != 0) {
1199                         xpt_print(ccb->ccb_h.path,
1200                                 "hv_storvsc_host_reset failed with %d\n", res);
1201                         ccb->ccb_h.status = CAM_PROVIDE_FAIL;
1202                         xpt_done(ccb);
1203                         return;
1204                 }
1205                 ccb->ccb_h.status = CAM_REQ_CMP;
1206                 xpt_done(ccb);
1207                 return;
1208 #else
1209                 xpt_print(ccb->ccb_h.path,
1210                                   "%s reset not supported.\n",
1211                                   (ccb->ccb_h.func_code == XPT_RESET_BUS)?
1212                                   "bus" : "dev");
1213                 ccb->ccb_h.status = CAM_REQ_INVALID;
1214                 xpt_done(ccb);
1215                 return;
1216 #endif  /* HVS_HOST_RESET */
1217         }
1218         case XPT_SCSI_IO:
1219         case XPT_IMMED_NOTIFY: {
1220                 struct hv_storvsc_request *reqp = NULL;
1221
1222                 if (ccb->csio.cdb_len == 0) {
1223                         panic("cdl_len is 0\n");
1224                 }
1225
1226                 if (LIST_EMPTY(&sc->hs_free_list)) {
1227                         ccb->ccb_h.status = CAM_REQUEUE_REQ;
1228                         if (sc->hs_frozen == 0) {
1229                                 sc->hs_frozen = 1;
1230                                 xpt_freeze_simq(sim, /* count*/1);
1231                         }
1232                         xpt_done(ccb);
1233                         return;
1234                 }
1235
1236                 reqp = LIST_FIRST(&sc->hs_free_list);
1237                 LIST_REMOVE(reqp, link);
1238
1239                 bzero(reqp, sizeof(struct hv_storvsc_request));
1240                 reqp->softc = sc;
1241
1242                 ccb->ccb_h.status |= CAM_SIM_QUEUED;        
1243                 create_storvsc_request(ccb, reqp);
1244
1245                 if (ccb->ccb_h.timeout != CAM_TIME_INFINITY) {
1246                         callout_init(&reqp->callout, CALLOUT_MPSAFE);
1247                         callout_reset(&reqp->callout,
1248                                         (ccb->ccb_h.timeout * hz) / 1000,
1249                                         storvsc_timeout, reqp);
1250 #if HVS_TIMEOUT_TEST
1251                         cv_init(&reqp->event.cv, "storvsc timeout cv");
1252                         mtx_init(&reqp->event.mtx, "storvsc timeout mutex",
1253                                         NULL, MTX_DEF);
1254                         switch (reqp->vstor_packet.vm_srb.cdb[0]) {
1255                                 case MODE_SELECT_10:
1256                                 case SEND_DIAGNOSTIC:
1257                                         /* To have timer send the request. */
1258                                         return;
1259                                 default:
1260                                         break;
1261                         }
1262 #endif /* HVS_TIMEOUT_TEST */
1263                 }
1264
1265                 if ((res = hv_storvsc_io_request(sc->hs_dev, reqp)) != 0) {
1266                         xpt_print(ccb->ccb_h.path,
1267                                 "hv_storvsc_io_request failed with %d\n", res);
1268                         ccb->ccb_h.status = CAM_PROVIDE_FAIL;
1269                         storvsc_free_request(sc, reqp);
1270                         xpt_done(ccb);
1271                         return;
1272                 }
1273                 return;
1274         }
1275
1276         default:
1277                 ccb->ccb_h.status = CAM_REQ_INVALID;
1278                 xpt_done(ccb);
1279                 return;
1280         }
1281 }
1282
1283 /**
1284  * @brief Fill in a request structure based on a CAM control block
1285  *
1286  * Fills in a request structure based on the contents of a CAM control
1287  * block.  The request structure holds the payload information for
1288  * VSCSI protocol request.
1289  *
1290  * @param ccb pointer to a CAM contorl block
1291  * @param reqp pointer to a request structure
1292  */
1293 static void
1294 create_storvsc_request(union ccb *ccb, struct hv_storvsc_request *reqp)
1295 {
1296         struct ccb_scsiio *csio = &ccb->csio;
1297         uint64_t phys_addr;
1298         uint32_t bytes_to_copy = 0;
1299         uint32_t pfn_num = 0;
1300         uint32_t pfn;
1301         
1302         /* refer to struct vmscsi_req for meanings of these two fields */
1303         reqp->vstor_packet.u.vm_srb.port =
1304                 cam_sim_unit(xpt_path_sim(ccb->ccb_h.path));
1305         reqp->vstor_packet.u.vm_srb.path_id =
1306                 cam_sim_bus(xpt_path_sim(ccb->ccb_h.path));
1307
1308         reqp->vstor_packet.u.vm_srb.target_id = ccb->ccb_h.target_id;
1309         reqp->vstor_packet.u.vm_srb.lun = ccb->ccb_h.target_lun;
1310
1311         reqp->vstor_packet.u.vm_srb.cdb_len = csio->cdb_len;
1312         if(ccb->ccb_h.flags & CAM_CDB_POINTER) {
1313                 memcpy(&reqp->vstor_packet.u.vm_srb.u.cdb, csio->cdb_io.cdb_ptr,
1314                         csio->cdb_len);
1315         } else {
1316                 memcpy(&reqp->vstor_packet.u.vm_srb.u.cdb, csio->cdb_io.cdb_bytes,
1317                         csio->cdb_len);
1318         }
1319
1320         switch (ccb->ccb_h.flags & CAM_DIR_MASK) {
1321         case CAM_DIR_OUT: 
1322                 reqp->vstor_packet.u.vm_srb.data_in = WRITE_TYPE;
1323                 break;
1324         case CAM_DIR_IN:
1325                 reqp->vstor_packet.u.vm_srb.data_in = READ_TYPE;
1326                 break;
1327         case CAM_DIR_NONE:
1328                 reqp->vstor_packet.u.vm_srb.data_in = UNKNOWN_TYPE;
1329                 break;
1330         default:
1331                 reqp->vstor_packet.u.vm_srb.data_in = UNKNOWN_TYPE;
1332                 break;
1333         }
1334
1335         reqp->sense_data     = &csio->sense_data;
1336         reqp->sense_info_len = csio->sense_len;
1337
1338         reqp->ccb = ccb;
1339         /*
1340         KASSERT((ccb->ccb_h.flags & CAM_SCATTER_VALID) == 0,
1341                         ("ccb is scatter gather valid\n"));
1342         */
1343         if (csio->dxfer_len != 0) {
1344                 reqp->data_buf.length = csio->dxfer_len;
1345                 bytes_to_copy = csio->dxfer_len;
1346                 phys_addr = vtophys(csio->data_ptr);
1347                 reqp->data_buf.offset = phys_addr - trunc_page(phys_addr);
1348         }
1349
1350         while (bytes_to_copy != 0) {
1351                 int bytes, page_offset;
1352                 phys_addr = vtophys(&csio->data_ptr[reqp->data_buf.length -
1353                                                     bytes_to_copy]);
1354                 pfn = phys_addr >> PAGE_SHIFT;
1355                 reqp->data_buf.pfn_array[pfn_num] = pfn;
1356                 page_offset = phys_addr - trunc_page(phys_addr);
1357
1358                 bytes = min(PAGE_SIZE - page_offset, bytes_to_copy);
1359
1360                 bytes_to_copy -= bytes;
1361                 pfn_num++;
1362         }
1363 }
1364
1365 /**
1366  * @brief completion function before returning to CAM
1367  *
1368  * I/O process has been completed and the result needs
1369  * to be passed to the CAM layer.
1370  * Free resources related to this request.
1371  *
1372  * @param reqp pointer to a request structure
1373  */
1374 static void
1375 storvsc_io_done(struct hv_storvsc_request *reqp)
1376 {
1377         union ccb *ccb = reqp->ccb;
1378         struct ccb_scsiio *csio = &ccb->csio;
1379         struct storvsc_softc *sc = reqp->softc;
1380         struct vmscsi_req *vm_srb = &reqp->vstor_packet.u.vm_srb;
1381         
1382         if (reqp->retries > 0) {
1383                 mtx_lock(&sc->hs_lock);
1384 #if HVS_TIMEOUT_TEST
1385                 xpt_print(ccb->ccb_h.path,
1386                         "%u: IO returned after timeout, "
1387                         "waking up timer handler if any.\n", ticks);
1388                 mtx_lock(&reqp->event.mtx);
1389                 cv_signal(&reqp->event.cv);
1390                 mtx_unlock(&reqp->event.mtx);
1391 #endif
1392                 reqp->retries = 0;
1393                 xpt_print(ccb->ccb_h.path,
1394                         "%u: IO returned after timeout, "
1395                         "stopping timer if any.\n", ticks);
1396                 mtx_unlock(&sc->hs_lock);
1397         }
1398
1399         /* 
1400          * callout_drain() will wait for the timer handler to finish
1401          * if it is running. So we don't need any lock to synchronize
1402          * between this routine and the timer handler.
1403          * Note that we need to make sure reqp is not freed when timer
1404          * handler is using or will use it.
1405          */
1406         if (ccb->ccb_h.timeout != CAM_TIME_INFINITY) {
1407                 callout_drain(&reqp->callout);
1408         }
1409
1410         ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
1411         ccb->ccb_h.status &= ~CAM_STATUS_MASK;
1412         if (vm_srb->scsi_status == SCSI_STATUS_OK) {
1413                 ccb->ccb_h.status |= CAM_REQ_CMP;
1414          } else {
1415                 mtx_lock(&sc->hs_lock);
1416                 xpt_print(ccb->ccb_h.path,
1417                         "srovsc scsi_status = %d\n",
1418                         vm_srb->scsi_status);
1419                 mtx_unlock(&sc->hs_lock);
1420                 ccb->ccb_h.status |= CAM_SCSI_STATUS_ERROR;
1421         }
1422
1423         ccb->csio.scsi_status = (vm_srb->scsi_status & 0xFF);
1424         ccb->csio.resid = ccb->csio.dxfer_len - vm_srb->transfer_len;
1425
1426         if (reqp->sense_info_len != 0) {
1427                 csio->sense_resid = csio->sense_len - reqp->sense_info_len;
1428                 ccb->ccb_h.status |= CAM_AUTOSNS_VALID;
1429         }
1430
1431         mtx_lock(&sc->hs_lock);
1432         if (reqp->softc->hs_frozen == 1) {
1433                 xpt_print(ccb->ccb_h.path,
1434                         "%u: storvsc unfreezing softc 0x%p.\n",
1435                         ticks, reqp->softc);
1436                 ccb->ccb_h.status |= CAM_RELEASE_SIMQ;
1437                 reqp->softc->hs_frozen = 0;
1438         }
1439         storvsc_free_request(sc, reqp);
1440         xpt_done(ccb);
1441         mtx_unlock(&sc->hs_lock);
1442 }
1443
1444 /**
1445  * @brief Free a request structure
1446  *
1447  * Free a request structure by returning it to the free list
1448  *
1449  * @param sc pointer to a softc
1450  * @param reqp pointer to a request structure
1451  */     
1452 static void
1453 storvsc_free_request(struct storvsc_softc *sc, struct hv_storvsc_request *reqp)
1454 {
1455
1456         LIST_INSERT_HEAD(&sc->hs_free_list, reqp, link);
1457 }
1458
1459 /**
1460  * @brief Determine type of storage device from GUID
1461  *
1462  * Using the type GUID, determine if this is a StorVSC (paravirtual
1463  * SCSI or BlkVSC (paravirtual IDE) device.
1464  *
1465  * @param dev a device
1466  * returns an enum
1467  */
1468 static enum hv_storage_type
1469 storvsc_get_storage_type(device_t dev)
1470 {
1471         const char *p = vmbus_get_type(dev);
1472
1473         if (!memcmp(p, &gBlkVscDeviceType, sizeof(hv_guid))) {
1474                 return DRIVER_BLKVSC;
1475         } else if (!memcmp(p, &gStorVscDeviceType, sizeof(hv_guid))) {
1476                 return DRIVER_STORVSC;
1477         }
1478         return (DRIVER_UNKNOWN);
1479 }
1480