This commit was manufactured by cvs2svn to create branch 'vserver'.
[linux-2.6.git] / drivers / scsi / ibmvscsi / ibmvscsi.c
1 /* ------------------------------------------------------------
2  * ibmvscsi.c
3  * (C) Copyright IBM Corporation 1994, 2004
4  * Authors: Colin DeVilbiss (devilbis@us.ibm.com)
5  *          Santiago Leon (santil@us.ibm.com)
6  *          Dave Boutcher (sleddog@us.ibm.com)
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
21  * USA
22  *
23  * ------------------------------------------------------------
24  * Emulation of a SCSI host adapter for Virtual I/O devices
25  *
26  * This driver supports the SCSI adapter implemented by the IBM
27  * Power5 firmware.  That SCSI adapter is not a physical adapter,
28  * but allows Linux SCSI peripheral drivers to directly
29  * access devices in another logical partition on the physical system.
30  *
31  * The virtual adapter(s) are present in the open firmware device
32  * tree just like real adapters.
33  *
34  * One of the capabilities provided on these systems is the ability
35  * to DMA between partitions.  The architecture states that for VSCSI,
36  * the server side is allowed to DMA to and from the client.  The client
37  * is never trusted to DMA to or from the server directly.
38  *
39  * Messages are sent between partitions on a "Command/Response Queue" 
40  * (CRQ), which is just a buffer of 16 byte entries in the receiver's 
41  * Senders cannot access the buffer directly, but send messages by
42  * making a hypervisor call and passing in the 16 bytes.  The hypervisor
43  * puts the message in the next 16 byte space in round-robbin fashion,
44  * turns on the high order bit of the message (the valid bit), and 
45  * generates an interrupt to the receiver (if interrupts are turned on.) 
46  * The receiver just turns off the valid bit when they have copied out
47  * the message.
48  *
49  * The VSCSI client builds a SCSI Remote Protocol (SRP) Information Unit
50  * (IU) (as defined in the T10 standard available at www.t10.org), gets 
51  * a DMA address for the message, and sends it to the server as the
52  * payload of a CRQ message.  The server DMAs the SRP IU and processes it,
53  * including doing any additional data transfers.  When it is done, it
54  * DMAs the SRP response back to the same address as the request came from,
55  * and sends a CRQ message back to inform the client that the request has
56  * completed.
57  *
58  * Note that some of the underlying infrastructure is different between
59  * machines conforming to the "RS/6000 Platform Architecture" (RPA) and
60  * the older iSeries hypervisor models.  To support both, some low level
61  * routines have been broken out into rpa_vscsi.c and iseries_vscsi.c.
62  * The Makefile should pick one, not two, not zero, of these.
63  *
64  * TODO: This is currently pretty tied to the IBM i/pSeries hypervisor
65  * interfaces.  It would be really nice to abstract this above an RDMA
66  * layer.
67  */
68
69 #include <linux/module.h>
70 #include <linux/moduleparam.h>
71 #include <linux/dma-mapping.h>
72 #include <asm/vio.h>
73 #include <scsi/scsi.h>
74 #include <scsi/scsi_cmnd.h>
75 #include <scsi/scsi_host.h>
76 #include <scsi/scsi_device.h>
77 #include "ibmvscsi.h"
78
79 /* The values below are somewhat arbitrary default values, but 
80  * OS/400 will use 3 busses (disks, CDs, tapes, I think.)
81  * Note that there are 3 bits of channel value, 6 bits of id, and
82  * 5 bits of LUN.
83  */
84 static int max_id = 64;
85 static int max_channel = 3;
86 static int init_timeout = 5;
87 static int max_requests = 50;
88
89 #define IBMVSCSI_VERSION "1.5.1"
90
91 MODULE_DESCRIPTION("IBM Virtual SCSI");
92 MODULE_AUTHOR("Dave Boutcher");
93 MODULE_LICENSE("GPL");
94 MODULE_VERSION(IBMVSCSI_VERSION);
95
96 module_param_named(max_id, max_id, int, S_IRUGO | S_IWUSR);
97 MODULE_PARM_DESC(max_id, "Largest ID value for each channel");
98 module_param_named(max_channel, max_channel, int, S_IRUGO | S_IWUSR);
99 MODULE_PARM_DESC(max_channel, "Largest channel value");
100 module_param_named(init_timeout, init_timeout, int, S_IRUGO | S_IWUSR);
101 MODULE_PARM_DESC(init_timeout, "Initialization timeout in seconds");
102 module_param_named(max_requests, max_requests, int, S_IRUGO | S_IWUSR);
103 MODULE_PARM_DESC(max_requests, "Maximum requests for this adapter");
104
105 /* ------------------------------------------------------------
106  * Routines for the event pool and event structs
107  */
108 /**
109  * initialize_event_pool: - Allocates and initializes the event pool for a host
110  * @pool:       event_pool to be initialized
111  * @size:       Number of events in pool
112  * @hostdata:   ibmvscsi_host_data who owns the event pool
113  *
114  * Returns zero on success.
115 */
116 static int initialize_event_pool(struct event_pool *pool,
117                                  int size, struct ibmvscsi_host_data *hostdata)
118 {
119         int i;
120
121         pool->size = size;
122         pool->next = 0;
123         pool->events = kmalloc(pool->size * sizeof(*pool->events), GFP_KERNEL);
124         if (!pool->events)
125                 return -ENOMEM;
126         memset(pool->events, 0x00, pool->size * sizeof(*pool->events));
127
128         pool->iu_storage =
129             dma_alloc_coherent(hostdata->dev,
130                                pool->size * sizeof(*pool->iu_storage),
131                                &pool->iu_token, 0);
132         if (!pool->iu_storage) {
133                 kfree(pool->events);
134                 return -ENOMEM;
135         }
136
137         for (i = 0; i < pool->size; ++i) {
138                 struct srp_event_struct *evt = &pool->events[i];
139                 memset(&evt->crq, 0x00, sizeof(evt->crq));
140                 atomic_set(&evt->free, 1);
141                 evt->crq.valid = 0x80;
142                 evt->crq.IU_length = sizeof(*evt->xfer_iu);
143                 evt->crq.IU_data_ptr = pool->iu_token + 
144                         sizeof(*evt->xfer_iu) * i;
145                 evt->xfer_iu = pool->iu_storage + i;
146                 evt->hostdata = hostdata;
147         }
148
149         return 0;
150 }
151
152 /**
153  * release_event_pool: - Frees memory of an event pool of a host
154  * @pool:       event_pool to be released
155  * @hostdata:   ibmvscsi_host_data who owns the even pool
156  *
157  * Returns zero on success.
158 */
159 static void release_event_pool(struct event_pool *pool,
160                                struct ibmvscsi_host_data *hostdata)
161 {
162         int i, in_use = 0;
163         for (i = 0; i < pool->size; ++i)
164                 if (atomic_read(&pool->events[i].free) != 1)
165                         ++in_use;
166         if (in_use)
167                 printk(KERN_WARNING
168                        "ibmvscsi: releasing event pool with %d "
169                        "events still in use?\n", in_use);
170         kfree(pool->events);
171         dma_free_coherent(hostdata->dev,
172                           pool->size * sizeof(*pool->iu_storage),
173                           pool->iu_storage, pool->iu_token);
174 }
175
176 /**
177  * valid_event_struct: - Determines if event is valid.
178  * @pool:       event_pool that contains the event
179  * @evt:        srp_event_struct to be checked for validity
180  *
181  * Returns zero if event is invalid, one otherwise.
182 */
183 static int valid_event_struct(struct event_pool *pool,
184                                 struct srp_event_struct *evt)
185 {
186         int index = evt - pool->events;
187         if (index < 0 || index >= pool->size)   /* outside of bounds */
188                 return 0;
189         if (evt != pool->events + index)        /* unaligned */
190                 return 0;
191         return 1;
192 }
193
194 /**
195  * ibmvscsi_free-event_struct: - Changes status of event to "free"
196  * @pool:       event_pool that contains the event
197  * @evt:        srp_event_struct to be modified
198  *
199 */
200 static void free_event_struct(struct event_pool *pool,
201                                        struct srp_event_struct *evt)
202 {
203         if (!valid_event_struct(pool, evt)) {
204                 printk(KERN_ERR
205                        "ibmvscsi: Freeing invalid event_struct %p "
206                        "(not in pool %p)\n", evt, pool->events);
207                 return;
208         }
209         if (atomic_inc_return(&evt->free) != 1) {
210                 printk(KERN_ERR
211                        "ibmvscsi: Freeing event_struct %p "
212                        "which is not in use!\n", evt);
213                 return;
214         }
215 }
216
217 /**
218  * get_evt_struct: - Gets the next free event in pool
219  * @pool:       event_pool that contains the events to be searched
220  *
221  * Returns the next event in "free" state, and NULL if none are free.
222  * Note that no synchronization is done here, we assume the host_lock
223  * will syncrhonze things.
224 */
225 static struct srp_event_struct *get_event_struct(struct event_pool *pool)
226 {
227         int i;
228         int poolsize = pool->size;
229         int offset = pool->next;
230
231         for (i = 0; i < poolsize; i++) {
232                 offset = (offset + 1) % poolsize;
233                 if (!atomic_dec_if_positive(&pool->events[offset].free)) {
234                         pool->next = offset;
235                         return &pool->events[offset];
236                 }
237         }
238
239         printk(KERN_ERR "ibmvscsi: found no event struct in pool!\n");
240         return NULL;
241 }
242
243 /**
244  * init_event_struct: Initialize fields in an event struct that are always 
245  *                    required.
246  * @evt:        The event
247  * @done:       Routine to call when the event is responded to
248  * @format:     SRP or MAD format
249  * @timeout:    timeout value set in the CRQ
250  */
251 static void init_event_struct(struct srp_event_struct *evt_struct,
252                               void (*done) (struct srp_event_struct *),
253                               u8 format,
254                               int timeout)
255 {
256         evt_struct->cmnd = NULL;
257         evt_struct->cmnd_done = NULL;
258         evt_struct->crq.format = format;
259         evt_struct->crq.timeout = timeout;
260         evt_struct->done = done;
261 }
262
263 /* ------------------------------------------------------------
264  * Routines for receiving SCSI responses from the hosting partition
265  */
266
267 /**
268  * set_srp_direction: Set the fields in the srp related to data
269  *     direction and number of buffers based on the direction in
270  *     the scsi_cmnd and the number of buffers
271  */
272 static void set_srp_direction(struct scsi_cmnd *cmd,
273                               struct srp_cmd *srp_cmd, 
274                               int numbuf)
275 {
276         if (numbuf == 0)
277                 return;
278         
279         if (numbuf == 1) {
280                 if (cmd->sc_data_direction == DMA_TO_DEVICE)
281                         srp_cmd->data_out_format = SRP_DIRECT_BUFFER;
282                 else 
283                         srp_cmd->data_in_format = SRP_DIRECT_BUFFER;
284         } else {
285                 if (cmd->sc_data_direction == DMA_TO_DEVICE) {
286                         srp_cmd->data_out_format = SRP_INDIRECT_BUFFER;
287                         srp_cmd->data_out_count = numbuf;
288                 } else {
289                         srp_cmd->data_in_format = SRP_INDIRECT_BUFFER;
290                         srp_cmd->data_in_count = numbuf;
291                 }
292         }
293 }
294
295 /**
296  * unmap_cmd_data: - Unmap data pointed in srp_cmd based on the format
297  * @cmd:        srp_cmd whose additional_data member will be unmapped
298  * @dev:        device for which the memory is mapped
299  *
300 */
301 static void unmap_cmd_data(struct srp_cmd *cmd, struct device *dev)
302 {
303         int i;
304
305         if ((cmd->data_out_format == SRP_NO_BUFFER) &&
306             (cmd->data_in_format == SRP_NO_BUFFER))
307                 return;
308         else if ((cmd->data_out_format == SRP_DIRECT_BUFFER) ||
309                  (cmd->data_in_format == SRP_DIRECT_BUFFER)) {
310                 struct memory_descriptor *data =
311                         (struct memory_descriptor *)cmd->additional_data;
312                 dma_unmap_single(dev, data->virtual_address, data->length,
313                                  DMA_BIDIRECTIONAL);
314         } else {
315                 struct indirect_descriptor *indirect =
316                         (struct indirect_descriptor *)cmd->additional_data;
317                 int num_mapped = indirect->head.length / 
318                         sizeof(indirect->list[0]);
319                 for (i = 0; i < num_mapped; ++i) {
320                         struct memory_descriptor *data = &indirect->list[i];
321                         dma_unmap_single(dev,
322                                          data->virtual_address,
323                                          data->length, DMA_BIDIRECTIONAL);
324                 }
325         }
326 }
327
328 /**
329  * map_sg_data: - Maps dma for a scatterlist and initializes decriptor fields
330  * @cmd:        Scsi_Cmnd with the scatterlist
331  * @srp_cmd:    srp_cmd that contains the memory descriptor
332  * @dev:        device for which to map dma memory
333  *
334  * Called by map_data_for_srp_cmd() when building srp cmd from scsi cmd.
335  * Returns 1 on success.
336 */
337 static int map_sg_data(struct scsi_cmnd *cmd,
338                        struct srp_cmd *srp_cmd, struct device *dev)
339 {
340
341         int i, sg_mapped;
342         u64 total_length = 0;
343         struct scatterlist *sg = cmd->request_buffer;
344         struct memory_descriptor *data =
345             (struct memory_descriptor *)srp_cmd->additional_data;
346         struct indirect_descriptor *indirect =
347             (struct indirect_descriptor *)data;
348
349         sg_mapped = dma_map_sg(dev, sg, cmd->use_sg, DMA_BIDIRECTIONAL);
350
351         if (sg_mapped == 0)
352                 return 0;
353
354         set_srp_direction(cmd, srp_cmd, sg_mapped);
355
356         /* special case; we can use a single direct descriptor */
357         if (sg_mapped == 1) {
358                 data->virtual_address = sg_dma_address(&sg[0]);
359                 data->length = sg_dma_len(&sg[0]);
360                 data->memory_handle = 0;
361                 return 1;
362         }
363
364         if (sg_mapped > MAX_INDIRECT_BUFS) {
365                 printk(KERN_ERR
366                        "ibmvscsi: More than %d mapped sg entries, got %d\n",
367                        MAX_INDIRECT_BUFS, sg_mapped);
368                 return 0;
369         }
370
371         indirect->head.virtual_address = 0;
372         indirect->head.length = sg_mapped * sizeof(indirect->list[0]);
373         indirect->head.memory_handle = 0;
374         for (i = 0; i < sg_mapped; ++i) {
375                 struct memory_descriptor *descr = &indirect->list[i];
376                 struct scatterlist *sg_entry = &sg[i];
377                 descr->virtual_address = sg_dma_address(sg_entry);
378                 descr->length = sg_dma_len(sg_entry);
379                 descr->memory_handle = 0;
380                 total_length += sg_dma_len(sg_entry);
381         }
382         indirect->total_length = total_length;
383
384         return 1;
385 }
386
387 /**
388  * map_single_data: - Maps memory and initializes memory decriptor fields
389  * @cmd:        struct scsi_cmnd with the memory to be mapped
390  * @srp_cmd:    srp_cmd that contains the memory descriptor
391  * @dev:        device for which to map dma memory
392  *
393  * Called by map_data_for_srp_cmd() when building srp cmd from scsi cmd.
394  * Returns 1 on success.
395 */
396 static int map_single_data(struct scsi_cmnd *cmd,
397                            struct srp_cmd *srp_cmd, struct device *dev)
398 {
399         struct memory_descriptor *data =
400             (struct memory_descriptor *)srp_cmd->additional_data;
401
402         data->virtual_address =
403                 dma_map_single(dev, cmd->request_buffer,
404                                cmd->request_bufflen,
405                                DMA_BIDIRECTIONAL);
406         if (dma_mapping_error(data->virtual_address)) {
407                 printk(KERN_ERR
408                        "ibmvscsi: Unable to map request_buffer for command!\n");
409                 return 0;
410         }
411         data->length = cmd->request_bufflen;
412         data->memory_handle = 0;
413
414         set_srp_direction(cmd, srp_cmd, 1);
415
416         return 1;
417 }
418
419 /**
420  * map_data_for_srp_cmd: - Calls functions to map data for srp cmds
421  * @cmd:        struct scsi_cmnd with the memory to be mapped
422  * @srp_cmd:    srp_cmd that contains the memory descriptor
423  * @dev:        dma device for which to map dma memory
424  *
425  * Called by scsi_cmd_to_srp_cmd() when converting scsi cmds to srp cmds 
426  * Returns 1 on success.
427 */
428 static int map_data_for_srp_cmd(struct scsi_cmnd *cmd,
429                                 struct srp_cmd *srp_cmd, struct device *dev)
430 {
431         switch (cmd->sc_data_direction) {
432         case DMA_FROM_DEVICE:
433         case DMA_TO_DEVICE:
434                 break;
435         case DMA_NONE:
436                 return 1;
437         case DMA_BIDIRECTIONAL:
438                 printk(KERN_ERR
439                        "ibmvscsi: Can't map DMA_BIDIRECTIONAL to read/write\n");
440                 return 0;
441         default:
442                 printk(KERN_ERR
443                        "ibmvscsi: Unknown data direction 0x%02x; can't map!\n",
444                        cmd->sc_data_direction);
445                 return 0;
446         }
447
448         if (!cmd->request_buffer)
449                 return 1;
450         if (cmd->use_sg)
451                 return map_sg_data(cmd, srp_cmd, dev);
452         return map_single_data(cmd, srp_cmd, dev);
453 }
454
455 /* ------------------------------------------------------------
456  * Routines for sending and receiving SRPs
457  */
458 /**
459  * ibmvscsi_send_srp_event: - Transforms event to u64 array and calls send_crq()
460  * @evt_struct: evt_struct to be sent
461  * @hostdata:   ibmvscsi_host_data of host
462  *
463  * Returns the value returned from ibmvscsi_send_crq(). (Zero for success)
464  * Note that this routine assumes that host_lock is held for synchronization
465 */
466 static int ibmvscsi_send_srp_event(struct srp_event_struct *evt_struct,
467                                    struct ibmvscsi_host_data *hostdata)
468 {
469         struct scsi_cmnd *cmnd = evt_struct->cmnd;
470         u64 *crq_as_u64 = (u64 *) &evt_struct->crq;
471         int rc;
472
473         /* If we have exhausted our request limit, just fail this request.
474          * Note that there are rare cases involving driver generated requests 
475          * (such as task management requests) that the mid layer may think we
476          * can handle more requests (can_queue) when we actually can't
477          */
478         if ((evt_struct->crq.format == VIOSRP_SRP_FORMAT) &&
479             (atomic_dec_if_positive(&hostdata->request_limit) < 0)) {
480                 /* See if the adapter is disabled */
481                 if (atomic_read(&hostdata->request_limit) < 0) {
482                         if (cmnd)
483                                 cmnd->result = DID_ERROR << 16;
484                         if (evt_struct->cmnd_done)
485                                 evt_struct->cmnd_done(cmnd);
486                         unmap_cmd_data(&evt_struct->iu.srp.cmd,
487                                        hostdata->dev);
488                         free_event_struct(&hostdata->pool, evt_struct);
489                         return 0;
490                 } else {
491                         printk("ibmvscsi: Warning, request_limit exceeded\n");
492                         unmap_cmd_data(&evt_struct->iu.srp.cmd,
493                                        hostdata->dev);
494                         free_event_struct(&hostdata->pool, evt_struct);
495                         return SCSI_MLQUEUE_HOST_BUSY;
496                 }
497         }
498
499         /* Copy the IU into the transfer area */
500         *evt_struct->xfer_iu = evt_struct->iu;
501         evt_struct->xfer_iu->srp.generic.tag = (u64)evt_struct;
502
503         /* Add this to the sent list.  We need to do this 
504          * before we actually send 
505          * in case it comes back REALLY fast
506          */
507         list_add_tail(&evt_struct->list, &hostdata->sent);
508
509         if ((rc =
510              ibmvscsi_send_crq(hostdata, crq_as_u64[0], crq_as_u64[1])) != 0) {
511                 list_del(&evt_struct->list);
512
513                 cmnd = evt_struct->cmnd;
514                 printk(KERN_ERR "ibmvscsi: failed to send event struct rc %d\n",
515                        rc);
516                 unmap_cmd_data(&evt_struct->iu.srp.cmd, hostdata->dev);
517                 free_event_struct(&hostdata->pool, evt_struct);
518                 if (cmnd)
519                         cmnd->result = DID_ERROR << 16;
520                 if (evt_struct->cmnd_done)
521                         evt_struct->cmnd_done(cmnd);
522         }
523
524         return 0;
525 }
526
527 /**
528  * handle_cmd_rsp: -  Handle responses from commands
529  * @evt_struct: srp_event_struct to be handled
530  *
531  * Used as a callback by when sending scsi cmds.
532  * Gets called by ibmvscsi_handle_crq()
533 */
534 static void handle_cmd_rsp(struct srp_event_struct *evt_struct)
535 {
536         struct srp_rsp *rsp = &evt_struct->xfer_iu->srp.rsp;
537         struct scsi_cmnd *cmnd = evt_struct->cmnd;
538
539         if (cmnd) {
540                 cmnd->result = rsp->status;
541                 if (((cmnd->result >> 1) & 0x1f) == CHECK_CONDITION)
542                         memcpy(cmnd->sense_buffer,
543                                rsp->sense_and_response_data,
544                                rsp->sense_data_list_length);
545                 unmap_cmd_data(&evt_struct->iu.srp.cmd, 
546                                evt_struct->hostdata->dev);
547
548                 if (rsp->doover)
549                         cmnd->resid = rsp->data_out_residual_count;
550                 else if (rsp->diover)
551                         cmnd->resid = rsp->data_in_residual_count;
552         }
553
554         if (evt_struct->cmnd_done)
555                 evt_struct->cmnd_done(cmnd);
556 }
557
558 /**
559  * lun_from_dev: - Returns the lun of the scsi device
560  * @dev:        struct scsi_device
561  *
562 */
563 static inline u16 lun_from_dev(struct scsi_device *dev)
564 {
565         return (0x2 << 14) | (dev->id << 8) | (dev->channel << 5) | dev->lun;
566 }
567
568 /**
569  * ibmvscsi_queue: - The queuecommand function of the scsi template 
570  * @cmd:        struct scsi_cmnd to be executed
571  * @done:       Callback function to be called when cmd is completed
572 */
573 static int ibmvscsi_queuecommand(struct scsi_cmnd *cmnd,
574                                  void (*done) (struct scsi_cmnd *))
575 {
576         struct srp_cmd *srp_cmd;
577         struct srp_event_struct *evt_struct;
578         struct ibmvscsi_host_data *hostdata =
579                 (struct ibmvscsi_host_data *)&cmnd->device->host->hostdata;
580         u16 lun = lun_from_dev(cmnd->device);
581
582         evt_struct = get_event_struct(&hostdata->pool);
583         if (!evt_struct)
584                 return SCSI_MLQUEUE_HOST_BUSY;
585
586         init_event_struct(evt_struct,
587                           handle_cmd_rsp,
588                           VIOSRP_SRP_FORMAT,
589                           cmnd->timeout);
590
591         evt_struct->cmnd = cmnd;
592         evt_struct->cmnd_done = done;
593
594         /* Set up the actual SRP IU */
595         srp_cmd = &evt_struct->iu.srp.cmd;
596         memset(srp_cmd, 0x00, sizeof(*srp_cmd));
597         srp_cmd->type = SRP_CMD_TYPE;
598         memcpy(srp_cmd->cdb, cmnd->cmnd, sizeof(cmnd->cmnd));
599         srp_cmd->lun = ((u64) lun) << 48;
600
601         if (!map_data_for_srp_cmd(cmnd, srp_cmd, hostdata->dev)) {
602                 printk(KERN_ERR "ibmvscsi: couldn't convert cmd to srp_cmd\n");
603                 free_event_struct(&hostdata->pool, evt_struct);
604                 return SCSI_MLQUEUE_HOST_BUSY;
605         }
606
607         /* Fix up dma address of the buffer itself */
608         if ((srp_cmd->data_out_format == SRP_INDIRECT_BUFFER) ||
609             (srp_cmd->data_in_format == SRP_INDIRECT_BUFFER)) {
610                 struct indirect_descriptor *indirect =
611                     (struct indirect_descriptor *)srp_cmd->additional_data;
612                 indirect->head.virtual_address = evt_struct->crq.IU_data_ptr +
613                     offsetof(struct srp_cmd, additional_data) +
614                     offsetof(struct indirect_descriptor, list);
615         }
616
617         return ibmvscsi_send_srp_event(evt_struct, hostdata);
618 }
619
620 /* ------------------------------------------------------------
621  * Routines for driver initialization
622  */
623 /**
624  * adapter_info_rsp: - Handle response to MAD adapter info request
625  * @evt_struct: srp_event_struct with the response
626  *
627  * Used as a "done" callback by when sending adapter_info. Gets called
628  * by ibmvscsi_handle_crq()
629 */
630 static void adapter_info_rsp(struct srp_event_struct *evt_struct)
631 {
632         struct ibmvscsi_host_data *hostdata = evt_struct->hostdata;
633         dma_unmap_single(hostdata->dev,
634                          evt_struct->iu.mad.adapter_info.buffer,
635                          evt_struct->iu.mad.adapter_info.common.length,
636                          DMA_BIDIRECTIONAL);
637
638         if (evt_struct->xfer_iu->mad.adapter_info.common.status) {
639                 printk("ibmvscsi: error %d getting adapter info\n",
640                        evt_struct->xfer_iu->mad.adapter_info.common.status);
641         } else {
642                 printk("ibmvscsi: host srp version: %s, "
643                        "host partition %s (%d), OS %d\n",
644                        hostdata->madapter_info.srp_version,
645                        hostdata->madapter_info.partition_name,
646                        hostdata->madapter_info.partition_number,
647                        hostdata->madapter_info.os_type);
648         }
649 }
650
651 /**
652  * send_mad_adapter_info: - Sends the mad adapter info request
653  *      and stores the result so it can be retrieved with
654  *      sysfs.  We COULD consider causing a failure if the
655  *      returned SRP version doesn't match ours.
656  * @hostdata:   ibmvscsi_host_data of host
657  * 
658  * Returns zero if successful.
659 */
660 static void send_mad_adapter_info(struct ibmvscsi_host_data *hostdata)
661 {
662         struct viosrp_adapter_info *req;
663         struct srp_event_struct *evt_struct;
664         
665         memset(&hostdata->madapter_info, 0x00, sizeof(hostdata->madapter_info));
666         
667         evt_struct = get_event_struct(&hostdata->pool);
668         if (!evt_struct) {
669                 printk(KERN_ERR "ibmvscsi: couldn't allocate an event "
670                        "for ADAPTER_INFO_REQ!\n");
671                 return;
672         }
673
674         init_event_struct(evt_struct,
675                           adapter_info_rsp,
676                           VIOSRP_MAD_FORMAT,
677                           init_timeout * HZ);
678         
679         req = &evt_struct->iu.mad.adapter_info;
680         memset(req, 0x00, sizeof(*req));
681         
682         req->common.type = VIOSRP_ADAPTER_INFO_TYPE;
683         req->common.length = sizeof(hostdata->madapter_info);
684         req->buffer = dma_map_single(hostdata->dev,
685                                      &hostdata->madapter_info,
686                                      sizeof(hostdata->madapter_info),
687                                      DMA_BIDIRECTIONAL);
688
689         if (dma_mapping_error(req->buffer)) {
690                 printk(KERN_ERR
691                        "ibmvscsi: Unable to map request_buffer "
692                        "for adapter_info!\n");
693                 free_event_struct(&hostdata->pool, evt_struct);
694                 return;
695         }
696         
697         if (ibmvscsi_send_srp_event(evt_struct, hostdata))
698                 printk(KERN_ERR "ibmvscsi: couldn't send ADAPTER_INFO_REQ!\n");
699 };
700
701 /**
702  * login_rsp: - Handle response to SRP login request
703  * @evt_struct: srp_event_struct with the response
704  *
705  * Used as a "done" callback by when sending srp_login. Gets called
706  * by ibmvscsi_handle_crq()
707 */
708 static void login_rsp(struct srp_event_struct *evt_struct)
709 {
710         struct ibmvscsi_host_data *hostdata = evt_struct->hostdata;
711         switch (evt_struct->xfer_iu->srp.generic.type) {
712         case SRP_LOGIN_RSP_TYPE:        /* it worked! */
713                 break;
714         case SRP_LOGIN_REJ_TYPE:        /* refused! */
715                 printk(KERN_INFO "ibmvscsi: SRP_LOGIN_REQ rejected\n");
716                 /* Login failed.  */
717                 atomic_set(&hostdata->request_limit, -1);
718                 return;
719         default:
720                 printk(KERN_ERR
721                        "ibmvscsi: Invalid login response typecode 0x%02x!\n",
722                        evt_struct->xfer_iu->srp.generic.type);
723                 /* Login failed.  */
724                 atomic_set(&hostdata->request_limit, -1);
725                 return;
726         }
727
728         printk(KERN_INFO "ibmvscsi: SRP_LOGIN succeeded\n");
729
730         if (evt_struct->xfer_iu->srp.login_rsp.request_limit_delta >
731             (max_requests - 2))
732                 evt_struct->xfer_iu->srp.login_rsp.request_limit_delta =
733                     max_requests - 2;
734
735         /* Now we know what the real request-limit is */
736         atomic_set(&hostdata->request_limit,
737                    evt_struct->xfer_iu->srp.login_rsp.request_limit_delta);
738
739         hostdata->host->can_queue =
740             evt_struct->xfer_iu->srp.login_rsp.request_limit_delta - 2;
741
742         if (hostdata->host->can_queue < 1) {
743                 printk(KERN_ERR "ibmvscsi: Invalid request_limit_delta\n");
744                 return;
745         }
746
747         send_mad_adapter_info(hostdata);
748         return;
749 }
750
751 /**
752  * send_srp_login: - Sends the srp login
753  * @hostdata:   ibmvscsi_host_data of host
754  * 
755  * Returns zero if successful.
756 */
757 static int send_srp_login(struct ibmvscsi_host_data *hostdata)
758 {
759         int rc;
760         unsigned long flags;
761         struct srp_login_req *login;
762         struct srp_event_struct *evt_struct = get_event_struct(&hostdata->pool);
763         if (!evt_struct) {
764                 printk(KERN_ERR
765                        "ibmvscsi: couldn't allocate an event for login req!\n");
766                 return FAILED;
767         }
768
769         init_event_struct(evt_struct,
770                           login_rsp,
771                           VIOSRP_SRP_FORMAT,
772                           init_timeout * HZ);
773
774         login = &evt_struct->iu.srp.login_req;
775         login->type = SRP_LOGIN_REQ_TYPE;
776         login->max_requested_initiator_to_target_iulen = sizeof(union srp_iu);
777         login->required_buffer_formats = 0x0006;
778         
779         /* Start out with a request limit of 1, since this is negotiated in
780          * the login request we are just sending
781          */
782         atomic_set(&hostdata->request_limit, 1);
783
784         spin_lock_irqsave(hostdata->host->host_lock, flags);
785         rc = ibmvscsi_send_srp_event(evt_struct, hostdata);
786         spin_unlock_irqrestore(hostdata->host->host_lock, flags);
787         return rc;
788 };
789
790 /**
791  * sync_completion: Signal that a synchronous command has completed
792  * Note that after returning from this call, the evt_struct is freed.
793  * the caller waiting on this completion shouldn't touch the evt_struct
794  * again.
795  */
796 static void sync_completion(struct srp_event_struct *evt_struct)
797 {
798         complete(&evt_struct->comp);
799 }
800
801 /**
802  * ibmvscsi_abort: Abort a command...from scsi host template
803  * send this over to the server and wait synchronously for the response
804  */
805 static int ibmvscsi_eh_abort_handler(struct scsi_cmnd *cmd)
806 {
807         struct ibmvscsi_host_data *hostdata =
808             (struct ibmvscsi_host_data *)cmd->device->host->hostdata;
809         struct srp_tsk_mgmt *tsk_mgmt;
810         struct srp_event_struct *evt;
811         struct srp_event_struct *tmp_evt, *found_evt;
812         u16 lun = lun_from_dev(cmd->device);
813
814         /* First, find this command in our sent list so we can figure
815          * out the correct tag
816          */
817         found_evt = NULL;
818         list_for_each_entry(tmp_evt, &hostdata->sent, list) {
819                 if (tmp_evt->cmnd == cmd) {
820                         found_evt = tmp_evt;
821                         break;
822                 }
823         }
824
825         if (!found_evt) 
826                 return FAILED;
827
828         evt = get_event_struct(&hostdata->pool);
829         if (evt == NULL) {
830                 printk(KERN_ERR "ibmvscsi: failed to allocate abort event\n");
831                 return FAILED;
832         }
833         
834         init_event_struct(evt,
835                           sync_completion,
836                           VIOSRP_SRP_FORMAT,
837                           init_timeout * HZ);
838
839         tsk_mgmt = &evt->iu.srp.tsk_mgmt;
840         
841         /* Set up an abort SRP command */
842         memset(tsk_mgmt, 0x00, sizeof(*tsk_mgmt));
843         tsk_mgmt->type = SRP_TSK_MGMT_TYPE;
844         tsk_mgmt->lun = ((u64) lun) << 48;
845         tsk_mgmt->task_mgmt_flags = 0x01;       /* ABORT TASK */
846         tsk_mgmt->managed_task_tag = (u64) found_evt;
847
848         printk(KERN_INFO "ibmvscsi: aborting command. lun 0x%lx, tag 0x%lx\n",
849                tsk_mgmt->lun, tsk_mgmt->managed_task_tag);
850
851         init_completion(&evt->comp);
852         if (ibmvscsi_send_srp_event(evt, hostdata) != 0) {
853                 printk(KERN_ERR "ibmvscsi: failed to send abort() event\n");
854                 return FAILED;
855         }
856
857         spin_unlock_irq(hostdata->host->host_lock);
858         wait_for_completion(&evt->comp);
859         spin_lock_irq(hostdata->host->host_lock);
860
861         /* Because we dropped the spinlock above, it's possible
862          * The event is no longer in our list.  Make sure it didn't
863          * complete while we were aborting
864          */
865         found_evt = NULL;
866         list_for_each_entry(tmp_evt, &hostdata->sent, list) {
867                 if (tmp_evt->cmnd == cmd) {
868                         found_evt = tmp_evt;
869                         break;
870                 }
871         }
872
873         printk(KERN_INFO
874                "ibmvscsi: successfully aborted task tag 0x%lx\n",
875                tsk_mgmt->managed_task_tag);
876
877         if (found_evt == NULL)
878                 return SUCCESS;
879
880         cmd->result = (DID_ABORT << 16);
881         list_del(&found_evt->list);
882         unmap_cmd_data(&found_evt->iu.srp.cmd, found_evt->hostdata->dev);
883         free_event_struct(&found_evt->hostdata->pool, found_evt);
884         atomic_inc(&hostdata->request_limit);
885         return SUCCESS;
886 }
887
888 /**
889  * ibmvscsi_eh_device_reset_handler: Reset a single LUN...from scsi host 
890  * template send this over to the server and wait synchronously for the 
891  * response
892  */
893 static int ibmvscsi_eh_device_reset_handler(struct scsi_cmnd *cmd)
894 {
895         struct ibmvscsi_host_data *hostdata =
896             (struct ibmvscsi_host_data *)cmd->device->host->hostdata;
897
898         struct srp_tsk_mgmt *tsk_mgmt;
899         struct srp_event_struct *evt;
900         struct srp_event_struct *tmp_evt, *pos;
901         u16 lun = lun_from_dev(cmd->device);
902
903         evt = get_event_struct(&hostdata->pool);
904         if (evt == NULL) {
905                 printk(KERN_ERR "ibmvscsi: failed to allocate reset event\n");
906                 return FAILED;
907         }
908         
909         init_event_struct(evt,
910                           sync_completion,
911                           VIOSRP_SRP_FORMAT,
912                           init_timeout * HZ);
913
914         tsk_mgmt = &evt->iu.srp.tsk_mgmt;
915
916         /* Set up a lun reset SRP command */
917         memset(tsk_mgmt, 0x00, sizeof(*tsk_mgmt));
918         tsk_mgmt->type = SRP_TSK_MGMT_TYPE;
919         tsk_mgmt->lun = ((u64) lun) << 48;
920         tsk_mgmt->task_mgmt_flags = 0x08;       /* LUN RESET */
921
922         printk(KERN_INFO "ibmvscsi: resetting device. lun 0x%lx\n",
923                tsk_mgmt->lun);
924
925         init_completion(&evt->comp);
926         if (ibmvscsi_send_srp_event(evt, hostdata) != 0) {
927                 printk(KERN_ERR "ibmvscsi: failed to send reset event\n");
928                 return FAILED;
929         }
930
931         spin_unlock_irq(hostdata->host->host_lock);
932         wait_for_completion(&evt->comp);
933         spin_lock_irq(hostdata->host->host_lock);
934
935         /* We need to find all commands for this LUN that have not yet been
936          * responded to, and fail them with DID_RESET
937          */
938         list_for_each_entry_safe(tmp_evt, pos, &hostdata->sent, list) {
939                 if ((tmp_evt->cmnd) && (tmp_evt->cmnd->device == cmd->device)) {
940                         if (tmp_evt->cmnd)
941                                 tmp_evt->cmnd->result = (DID_RESET << 16);
942                         list_del(&tmp_evt->list);
943                         unmap_cmd_data(&tmp_evt->iu.srp.cmd, tmp_evt->hostdata->dev);
944                         free_event_struct(&tmp_evt->hostdata->pool,
945                                                    tmp_evt);
946                         atomic_inc(&hostdata->request_limit);
947                         if (tmp_evt->cmnd_done)
948                                 tmp_evt->cmnd_done(tmp_evt->cmnd);
949                         else if (tmp_evt->done)
950                                 tmp_evt->done(tmp_evt);
951                 }
952         }
953         return SUCCESS;
954 }
955
956 /**
957  * purge_requests: Our virtual adapter just shut down.  purge any sent requests
958  * @hostdata:    the adapter
959  */
960 static void purge_requests(struct ibmvscsi_host_data *hostdata)
961 {
962         struct srp_event_struct *tmp_evt, *pos;
963         unsigned long flags;
964
965         spin_lock_irqsave(hostdata->host->host_lock, flags);
966         list_for_each_entry_safe(tmp_evt, pos, &hostdata->sent, list) {
967                 list_del(&tmp_evt->list);
968                 if (tmp_evt->cmnd) {
969                         tmp_evt->cmnd->result = (DID_ERROR << 16);
970                         unmap_cmd_data(&tmp_evt->iu.srp.cmd, 
971                                        tmp_evt->hostdata->dev);
972                         if (tmp_evt->cmnd_done)
973                                 tmp_evt->cmnd_done(tmp_evt->cmnd);
974                 } else {
975                         if (tmp_evt->done) {
976                                 tmp_evt->done(tmp_evt);
977                         }
978                 }
979                 free_event_struct(&tmp_evt->hostdata->pool, tmp_evt);
980         }
981         spin_unlock_irqrestore(hostdata->host->host_lock, flags);
982 }
983
984 /**
985  * ibmvscsi_handle_crq: - Handles and frees received events in the CRQ
986  * @crq:        Command/Response queue
987  * @hostdata:   ibmvscsi_host_data of host
988  *
989 */
990 void ibmvscsi_handle_crq(struct viosrp_crq *crq,
991                          struct ibmvscsi_host_data *hostdata)
992 {
993         unsigned long flags;
994         struct srp_event_struct *evt_struct =
995             (struct srp_event_struct *)crq->IU_data_ptr;
996         switch (crq->valid) {
997         case 0xC0:              /* initialization */
998                 switch (crq->format) {
999                 case 0x01:      /* Initialization message */
1000                         printk(KERN_INFO "ibmvscsi: partner initialized\n");
1001                         /* Send back a response */
1002                         if (ibmvscsi_send_crq(hostdata,
1003                                               0xC002000000000000LL, 0) == 0) {
1004                                 /* Now login */
1005                                 send_srp_login(hostdata);
1006                         } else {
1007                                 printk(KERN_ERR
1008                                        "ibmvscsi: Unable to send init rsp\n");
1009                         }
1010
1011                         break;
1012                 case 0x02:      /* Initialization response */
1013                         printk(KERN_INFO
1014                                "ibmvscsi: partner initialization complete\n");
1015
1016                         /* Now login */
1017                         send_srp_login(hostdata);
1018                         break;
1019                 default:
1020                         printk(KERN_ERR "ibmvscsi: unknown crq message type\n");
1021                 }
1022                 return;
1023         case 0xFF:              /* Hypervisor telling us the connection is closed */
1024                 printk(KERN_INFO "ibmvscsi: Virtual adapter failed!\n");
1025
1026                 atomic_set(&hostdata->request_limit, -1);
1027                 purge_requests(hostdata);
1028                 ibmvscsi_reset_crq_queue(&hostdata->queue, hostdata);
1029                 return;
1030         case 0x80:              /* real payload */
1031                 break;
1032         default:
1033                 printk(KERN_ERR
1034                        "ibmvscsi: got an invalid message type 0x%02x\n",
1035                        crq->valid);
1036                 return;
1037         }
1038
1039         /* The only kind of payload CRQs we should get are responses to
1040          * things we send. Make sure this response is to something we
1041          * actually sent
1042          */
1043         if (!valid_event_struct(&hostdata->pool, evt_struct)) {
1044                 printk(KERN_ERR
1045                        "ibmvscsi: returned correlation_token 0x%p is invalid!\n",
1046                        (void *)crq->IU_data_ptr);
1047                 return;
1048         }
1049
1050         if (crq->format == VIOSRP_SRP_FORMAT)
1051                 atomic_add(evt_struct->xfer_iu->srp.rsp.request_limit_delta,
1052                            &hostdata->request_limit);
1053
1054         if (evt_struct->done)
1055                 evt_struct->done(evt_struct);
1056         else
1057                 printk(KERN_ERR
1058                        "ibmvscsi: returned done() is NULL; not running it!\n");
1059
1060         /*
1061          * Lock the host_lock before messing with these structures, since we
1062          * are running in a task context
1063          */
1064         spin_lock_irqsave(evt_struct->hostdata->host->host_lock, flags);
1065         list_del(&evt_struct->list);
1066         free_event_struct(&evt_struct->hostdata->pool, evt_struct);
1067         spin_unlock_irqrestore(evt_struct->hostdata->host->host_lock, flags);
1068 }
1069
1070 /**
1071  * ibmvscsi_get_host_config: Send the command to the server to get host
1072  * configuration data.  The data is opaque to us.
1073  */
1074 static int ibmvscsi_do_host_config(struct ibmvscsi_host_data *hostdata,
1075                                    unsigned char *buffer, int length)
1076 {
1077         struct viosrp_host_config *host_config;
1078         struct srp_event_struct *evt_struct;
1079         int rc;
1080
1081         evt_struct = get_event_struct(&hostdata->pool);
1082         if (!evt_struct) {
1083                 printk(KERN_ERR
1084                        "ibmvscsi: could't allocate event for HOST_CONFIG!\n");
1085                 return -1;
1086         }
1087
1088         init_event_struct(evt_struct,
1089                           sync_completion,
1090                           VIOSRP_MAD_FORMAT,
1091                           init_timeout * HZ);
1092
1093         host_config = &evt_struct->iu.mad.host_config;
1094
1095         /* Set up a lun reset SRP command */
1096         memset(host_config, 0x00, sizeof(*host_config));
1097         host_config->common.type = VIOSRP_HOST_CONFIG_TYPE;
1098         host_config->common.length = length;
1099         host_config->buffer = dma_map_single(hostdata->dev, buffer, length,
1100                                             DMA_BIDIRECTIONAL);
1101
1102         if (dma_mapping_error(host_config->buffer)) {
1103                 printk(KERN_ERR
1104                        "ibmvscsi: dma_mapping error " "getting host config\n");
1105                 free_event_struct(&hostdata->pool, evt_struct);
1106                 return -1;
1107         }
1108
1109         init_completion(&evt_struct->comp);
1110         rc = ibmvscsi_send_srp_event(evt_struct, hostdata);
1111         if (rc == 0) {
1112                 wait_for_completion(&evt_struct->comp);
1113                 dma_unmap_single(hostdata->dev, host_config->buffer,
1114                                  length, DMA_BIDIRECTIONAL);
1115         }
1116
1117         return rc;
1118 }
1119
1120 /* ------------------------------------------------------------
1121  * sysfs attributes
1122  */
1123 static ssize_t show_host_srp_version(struct class_device *class_dev, char *buf)
1124 {
1125         struct Scsi_Host *shost = class_to_shost(class_dev);
1126         struct ibmvscsi_host_data *hostdata =
1127             (struct ibmvscsi_host_data *)shost->hostdata;
1128         int len;
1129
1130         len = snprintf(buf, PAGE_SIZE, "%s\n",
1131                        hostdata->madapter_info.srp_version);
1132         return len;
1133 }
1134
1135 static struct class_device_attribute ibmvscsi_host_srp_version = {
1136         .attr = {
1137                  .name = "srp_version",
1138                  .mode = S_IRUGO,
1139                  },
1140         .show = show_host_srp_version,
1141 };
1142
1143 static ssize_t show_host_partition_name(struct class_device *class_dev,
1144                                         char *buf)
1145 {
1146         struct Scsi_Host *shost = class_to_shost(class_dev);
1147         struct ibmvscsi_host_data *hostdata =
1148             (struct ibmvscsi_host_data *)shost->hostdata;
1149         int len;
1150
1151         len = snprintf(buf, PAGE_SIZE, "%s\n",
1152                        hostdata->madapter_info.partition_name);
1153         return len;
1154 }
1155
1156 static struct class_device_attribute ibmvscsi_host_partition_name = {
1157         .attr = {
1158                  .name = "partition_name",
1159                  .mode = S_IRUGO,
1160                  },
1161         .show = show_host_partition_name,
1162 };
1163
1164 static ssize_t show_host_partition_number(struct class_device *class_dev,
1165                                           char *buf)
1166 {
1167         struct Scsi_Host *shost = class_to_shost(class_dev);
1168         struct ibmvscsi_host_data *hostdata =
1169             (struct ibmvscsi_host_data *)shost->hostdata;
1170         int len;
1171
1172         len = snprintf(buf, PAGE_SIZE, "%d\n",
1173                        hostdata->madapter_info.partition_number);
1174         return len;
1175 }
1176
1177 static struct class_device_attribute ibmvscsi_host_partition_number = {
1178         .attr = {
1179                  .name = "partition_number",
1180                  .mode = S_IRUGO,
1181                  },
1182         .show = show_host_partition_number,
1183 };
1184
1185 static ssize_t show_host_mad_version(struct class_device *class_dev, char *buf)
1186 {
1187         struct Scsi_Host *shost = class_to_shost(class_dev);
1188         struct ibmvscsi_host_data *hostdata =
1189             (struct ibmvscsi_host_data *)shost->hostdata;
1190         int len;
1191
1192         len = snprintf(buf, PAGE_SIZE, "%d\n",
1193                        hostdata->madapter_info.mad_version);
1194         return len;
1195 }
1196
1197 static struct class_device_attribute ibmvscsi_host_mad_version = {
1198         .attr = {
1199                  .name = "mad_version",
1200                  .mode = S_IRUGO,
1201                  },
1202         .show = show_host_mad_version,
1203 };
1204
1205 static ssize_t show_host_os_type(struct class_device *class_dev, char *buf)
1206 {
1207         struct Scsi_Host *shost = class_to_shost(class_dev);
1208         struct ibmvscsi_host_data *hostdata =
1209             (struct ibmvscsi_host_data *)shost->hostdata;
1210         int len;
1211
1212         len = snprintf(buf, PAGE_SIZE, "%d\n", hostdata->madapter_info.os_type);
1213         return len;
1214 }
1215
1216 static struct class_device_attribute ibmvscsi_host_os_type = {
1217         .attr = {
1218                  .name = "os_type",
1219                  .mode = S_IRUGO,
1220                  },
1221         .show = show_host_os_type,
1222 };
1223
1224 static ssize_t show_host_config(struct class_device *class_dev, char *buf)
1225 {
1226         struct Scsi_Host *shost = class_to_shost(class_dev);
1227         struct ibmvscsi_host_data *hostdata =
1228             (struct ibmvscsi_host_data *)shost->hostdata;
1229
1230         /* returns null-terminated host config data */
1231         if (ibmvscsi_do_host_config(hostdata, buf, PAGE_SIZE) == 0)
1232                 return strlen(buf);
1233         else
1234                 return 0;
1235 }
1236
1237 static struct class_device_attribute ibmvscsi_host_config = {
1238         .attr = {
1239                  .name = "config",
1240                  .mode = S_IRUGO,
1241                  },
1242         .show = show_host_config,
1243 };
1244
1245 static struct class_device_attribute *ibmvscsi_attrs[] = {
1246         &ibmvscsi_host_srp_version,
1247         &ibmvscsi_host_partition_name,
1248         &ibmvscsi_host_partition_number,
1249         &ibmvscsi_host_mad_version,
1250         &ibmvscsi_host_os_type,
1251         &ibmvscsi_host_config,
1252         NULL
1253 };
1254
1255 /* ------------------------------------------------------------
1256  * SCSI driver registration
1257  */
1258 static struct scsi_host_template driver_template = {
1259         .module = THIS_MODULE,
1260         .name = "IBM POWER Virtual SCSI Adapter " IBMVSCSI_VERSION,
1261         .proc_name = "ibmvscsi",
1262         .queuecommand = ibmvscsi_queuecommand,
1263         .eh_abort_handler = ibmvscsi_eh_abort_handler,
1264         .eh_device_reset_handler = ibmvscsi_eh_device_reset_handler,
1265         .cmd_per_lun = 16,
1266         .can_queue = 1,         /* Updated after SRP_LOGIN */
1267         .this_id = -1,
1268         .sg_tablesize = MAX_INDIRECT_BUFS,
1269         .use_clustering = ENABLE_CLUSTERING,
1270         .shost_attrs = ibmvscsi_attrs,
1271 };
1272
1273 /**
1274  * Called by bus code for each adapter
1275  */
1276 static int ibmvscsi_probe(struct vio_dev *vdev, const struct vio_device_id *id)
1277 {
1278         struct ibmvscsi_host_data *hostdata;
1279         struct Scsi_Host *host;
1280         struct device *dev = &vdev->dev;
1281         unsigned long wait_switch = 0;
1282
1283         vdev->dev.driver_data = NULL;
1284
1285         host = scsi_host_alloc(&driver_template, sizeof(*hostdata));
1286         if (!host) {
1287                 printk(KERN_ERR "ibmvscsi: couldn't allocate host data\n");
1288                 goto scsi_host_alloc_failed;
1289         }
1290
1291         hostdata = (struct ibmvscsi_host_data *)host->hostdata;
1292         memset(hostdata, 0x00, sizeof(*hostdata));
1293         INIT_LIST_HEAD(&hostdata->sent);
1294         hostdata->host = host;
1295         hostdata->dev = dev;
1296         atomic_set(&hostdata->request_limit, -1);
1297
1298         if (ibmvscsi_init_crq_queue(&hostdata->queue, hostdata,
1299                                     max_requests) != 0) {
1300                 printk(KERN_ERR "ibmvscsi: couldn't initialize crq\n");
1301                 goto init_crq_failed;
1302         }
1303         if (initialize_event_pool(&hostdata->pool, max_requests, hostdata) != 0) {
1304                 printk(KERN_ERR "ibmvscsi: couldn't initialize event pool\n");
1305                 goto init_pool_failed;
1306         }
1307
1308         host->max_lun = 8;
1309         host->max_id = max_id;
1310         host->max_channel = max_channel;
1311
1312         if (scsi_add_host(hostdata->host, hostdata->dev))
1313                 goto add_host_failed;
1314
1315         /* Try to send an initialization message.  Note that this is allowed
1316          * to fail if the other end is not acive.  In that case we don't
1317          * want to scan
1318          */
1319         if (ibmvscsi_send_crq(hostdata, 0xC001000000000000LL, 0) == 0) {
1320                 /*
1321                  * Wait around max init_timeout secs for the adapter to finish
1322                  * initializing. When we are done initializing, we will have a
1323                  * valid request_limit.  We don't want Linux scanning before
1324                  * we are ready.
1325                  */
1326                 for (wait_switch = jiffies + (init_timeout * HZ);
1327                      time_before(jiffies, wait_switch) &&
1328                      atomic_read(&hostdata->request_limit) < 0;) {
1329
1330                         set_current_state(TASK_UNINTERRUPTIBLE);
1331                         schedule_timeout(HZ / 100);
1332                 }
1333
1334                 /* if we now have a valid request_limit, initiate a scan */
1335                 if (atomic_read(&hostdata->request_limit) > 0)
1336                         scsi_scan_host(host);
1337         }
1338
1339         vdev->dev.driver_data = hostdata;
1340         return 0;
1341
1342       add_host_failed:
1343         release_event_pool(&hostdata->pool, hostdata);
1344       init_pool_failed:
1345         ibmvscsi_release_crq_queue(&hostdata->queue, hostdata, max_requests);
1346       init_crq_failed:
1347         scsi_host_put(host);
1348       scsi_host_alloc_failed:
1349         return -1;
1350 }
1351
1352 static int ibmvscsi_remove(struct vio_dev *vdev)
1353 {
1354         struct ibmvscsi_host_data *hostdata = vdev->dev.driver_data;
1355         release_event_pool(&hostdata->pool, hostdata);
1356         ibmvscsi_release_crq_queue(&hostdata->queue, hostdata,
1357                                    max_requests);
1358         
1359         scsi_remove_host(hostdata->host);
1360         scsi_host_put(hostdata->host);
1361
1362         return 0;
1363 }
1364
1365 /**
1366  * ibmvscsi_device_table: Used by vio.c to match devices in the device tree we 
1367  * support.
1368  */
1369 static struct vio_device_id ibmvscsi_device_table[] __devinitdata = {
1370         {"vscsi", "IBM,v-scsi"},
1371         {0,}
1372 };
1373
1374 MODULE_DEVICE_TABLE(vio, ibmvscsi_device_table);
1375 static struct vio_driver ibmvscsi_driver = {
1376         .name = "ibmvscsi",
1377         .id_table = ibmvscsi_device_table,
1378         .probe = ibmvscsi_probe,
1379         .remove = ibmvscsi_remove
1380 };
1381
1382 int __init ibmvscsi_module_init(void)
1383 {
1384         return vio_register_driver(&ibmvscsi_driver);
1385 }
1386
1387 void __exit ibmvscsi_module_exit(void)
1388 {
1389         vio_unregister_driver(&ibmvscsi_driver);
1390 }
1391
1392 module_init(ibmvscsi_module_init);
1393 module_exit(ibmvscsi_module_exit);