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