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