scsi: esas2r: esas2r_main: Demote non-conformant kernel-doc header
[linux-2.6-microblaze.git] / drivers / scsi / esas2r / esas2r_main.c
1 /*
2  *  linux/drivers/scsi/esas2r/esas2r_main.c
3  *      For use with ATTO ExpressSAS R6xx SAS/SATA RAID controllers
4  *
5  *  Copyright (c) 2001-2013 ATTO Technology, Inc.
6  *  (mailto:linuxdrivers@attotech.com)
7  *
8  * This program is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License
10  * as published by the Free Software Foundation; either version 2
11  * of the License, or (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  * NO WARRANTY
19  * THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR
20  * CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT
21  * LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT,
22  * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is
23  * solely responsible for determining the appropriateness of using and
24  * distributing the Program and assumes all risks associated with its
25  * exercise of rights under this Agreement, including but not limited to
26  * the risks and costs of program errors, damage to or loss of data,
27  * programs or equipment, and unavailability or interruption of operations.
28  *
29  * DISCLAIMER OF LIABILITY
30  * NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY
31  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32  * DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND
33  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34  * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
35  * USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED
36  * HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES
37  *
38  * You should have received a copy of the GNU General Public License
39  * along with this program; if not, write to the Free Software
40  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
41  * USA.
42  */
43
44 #include "esas2r.h"
45
46 MODULE_DESCRIPTION(ESAS2R_DRVR_NAME ": " ESAS2R_LONGNAME " driver");
47 MODULE_AUTHOR("ATTO Technology, Inc.");
48 MODULE_LICENSE("GPL");
49 MODULE_VERSION(ESAS2R_VERSION_STR);
50
51 /* global definitions */
52
53 static int found_adapters;
54 struct esas2r_adapter *esas2r_adapters[MAX_ADAPTERS];
55
56 #define ESAS2R_VDA_EVENT_PORT1       54414
57 #define ESAS2R_VDA_EVENT_PORT2       54415
58 #define ESAS2R_VDA_EVENT_SOCK_COUNT  2
59
60 static struct esas2r_adapter *esas2r_adapter_from_kobj(struct kobject *kobj)
61 {
62         struct device *dev = container_of(kobj, struct device, kobj);
63         struct Scsi_Host *host = class_to_shost(dev);
64
65         return (struct esas2r_adapter *)host->hostdata;
66 }
67
68 static ssize_t read_fw(struct file *file, struct kobject *kobj,
69                        struct bin_attribute *attr,
70                        char *buf, loff_t off, size_t count)
71 {
72         struct esas2r_adapter *a = esas2r_adapter_from_kobj(kobj);
73
74         return esas2r_read_fw(a, buf, off, count);
75 }
76
77 static ssize_t write_fw(struct file *file, struct kobject *kobj,
78                         struct bin_attribute *attr,
79                         char *buf, loff_t off, size_t count)
80 {
81         struct esas2r_adapter *a = esas2r_adapter_from_kobj(kobj);
82
83         return esas2r_write_fw(a, buf, off, count);
84 }
85
86 static ssize_t read_fs(struct file *file, struct kobject *kobj,
87                        struct bin_attribute *attr,
88                        char *buf, loff_t off, size_t count)
89 {
90         struct esas2r_adapter *a = esas2r_adapter_from_kobj(kobj);
91
92         return esas2r_read_fs(a, buf, off, count);
93 }
94
95 static ssize_t write_fs(struct file *file, struct kobject *kobj,
96                         struct bin_attribute *attr,
97                         char *buf, loff_t off, size_t count)
98 {
99         struct esas2r_adapter *a = esas2r_adapter_from_kobj(kobj);
100         int length = min(sizeof(struct esas2r_ioctl_fs), count);
101         int result = 0;
102
103         result = esas2r_write_fs(a, buf, off, count);
104
105         if (result < 0)
106                 result = 0;
107
108         return length;
109 }
110
111 static ssize_t read_vda(struct file *file, struct kobject *kobj,
112                         struct bin_attribute *attr,
113                         char *buf, loff_t off, size_t count)
114 {
115         struct esas2r_adapter *a = esas2r_adapter_from_kobj(kobj);
116
117         return esas2r_read_vda(a, buf, off, count);
118 }
119
120 static ssize_t write_vda(struct file *file, struct kobject *kobj,
121                          struct bin_attribute *attr,
122                          char *buf, loff_t off, size_t count)
123 {
124         struct esas2r_adapter *a = esas2r_adapter_from_kobj(kobj);
125
126         return esas2r_write_vda(a, buf, off, count);
127 }
128
129 static ssize_t read_live_nvram(struct file *file, struct kobject *kobj,
130                                struct bin_attribute *attr,
131                                char *buf, loff_t off, size_t count)
132 {
133         struct esas2r_adapter *a = esas2r_adapter_from_kobj(kobj);
134         int length = min_t(size_t, sizeof(struct esas2r_sas_nvram), PAGE_SIZE);
135
136         memcpy(buf, a->nvram, length);
137         return length;
138 }
139
140 static ssize_t write_live_nvram(struct file *file, struct kobject *kobj,
141                                 struct bin_attribute *attr,
142                                 char *buf, loff_t off, size_t count)
143 {
144         struct esas2r_adapter *a = esas2r_adapter_from_kobj(kobj);
145         struct esas2r_request *rq;
146         int result = -EFAULT;
147
148         rq = esas2r_alloc_request(a);
149         if (rq == NULL)
150                 return -ENOMEM;
151
152         if (esas2r_write_params(a, rq, (struct esas2r_sas_nvram *)buf))
153                 result = count;
154
155         esas2r_free_request(a, rq);
156
157         return result;
158 }
159
160 static ssize_t read_default_nvram(struct file *file, struct kobject *kobj,
161                                   struct bin_attribute *attr,
162                                   char *buf, loff_t off, size_t count)
163 {
164         struct esas2r_adapter *a = esas2r_adapter_from_kobj(kobj);
165
166         esas2r_nvram_get_defaults(a, (struct esas2r_sas_nvram *)buf);
167
168         return sizeof(struct esas2r_sas_nvram);
169 }
170
171 static ssize_t read_hw(struct file *file, struct kobject *kobj,
172                        struct bin_attribute *attr,
173                        char *buf, loff_t off, size_t count)
174 {
175         struct esas2r_adapter *a = esas2r_adapter_from_kobj(kobj);
176         int length = min_t(size_t, sizeof(struct atto_ioctl), PAGE_SIZE);
177
178         if (!a->local_atto_ioctl)
179                 return -ENOMEM;
180
181         if (handle_hba_ioctl(a, a->local_atto_ioctl) != IOCTL_SUCCESS)
182                 return -ENOMEM;
183
184         memcpy(buf, a->local_atto_ioctl, length);
185
186         return length;
187 }
188
189 static ssize_t write_hw(struct file *file, struct kobject *kobj,
190                         struct bin_attribute *attr,
191                         char *buf, loff_t off, size_t count)
192 {
193         struct esas2r_adapter *a = esas2r_adapter_from_kobj(kobj);
194         int length = min(sizeof(struct atto_ioctl), count);
195
196         if (!a->local_atto_ioctl) {
197                 a->local_atto_ioctl = kmalloc(sizeof(struct atto_ioctl),
198                                               GFP_KERNEL);
199                 if (a->local_atto_ioctl == NULL) {
200                         esas2r_log(ESAS2R_LOG_WARN,
201                                    "write_hw kzalloc failed for %zu bytes",
202                                    sizeof(struct atto_ioctl));
203                         return -ENOMEM;
204                 }
205         }
206
207         memset(a->local_atto_ioctl, 0, sizeof(struct atto_ioctl));
208         memcpy(a->local_atto_ioctl, buf, length);
209
210         return length;
211 }
212
213 #define ESAS2R_RW_BIN_ATTR(_name) \
214         struct bin_attribute bin_attr_ ## _name = { \
215                 .attr   = \
216                 { .name = __stringify(_name), .mode  = S_IRUSR | S_IWUSR }, \
217                 .size   = 0, \
218                 .read   = read_ ## _name, \
219                 .write  = write_ ## _name }
220
221 ESAS2R_RW_BIN_ATTR(fw);
222 ESAS2R_RW_BIN_ATTR(fs);
223 ESAS2R_RW_BIN_ATTR(vda);
224 ESAS2R_RW_BIN_ATTR(hw);
225 ESAS2R_RW_BIN_ATTR(live_nvram);
226
227 struct bin_attribute bin_attr_default_nvram = {
228         .attr   = { .name = "default_nvram", .mode = S_IRUGO },
229         .size   = 0,
230         .read   = read_default_nvram,
231         .write  = NULL
232 };
233
234 static struct scsi_host_template driver_template = {
235         .module                         = THIS_MODULE,
236         .show_info                      = esas2r_show_info,
237         .name                           = ESAS2R_LONGNAME,
238         .info                           = esas2r_info,
239         .ioctl                          = esas2r_ioctl,
240         .queuecommand                   = esas2r_queuecommand,
241         .eh_abort_handler               = esas2r_eh_abort,
242         .eh_device_reset_handler        = esas2r_device_reset,
243         .eh_bus_reset_handler           = esas2r_bus_reset,
244         .eh_host_reset_handler          = esas2r_host_reset,
245         .eh_target_reset_handler        = esas2r_target_reset,
246         .can_queue                      = 128,
247         .this_id                        = -1,
248         .sg_tablesize                   = SG_CHUNK_SIZE,
249         .cmd_per_lun                    =
250                 ESAS2R_DEFAULT_CMD_PER_LUN,
251         .present                        = 0,
252         .unchecked_isa_dma              = 0,
253         .emulated                       = 0,
254         .proc_name                      = ESAS2R_DRVR_NAME,
255         .change_queue_depth             = scsi_change_queue_depth,
256         .max_sectors                    = 0xFFFF,
257 };
258
259 int sgl_page_size = 512;
260 module_param(sgl_page_size, int, 0);
261 MODULE_PARM_DESC(sgl_page_size,
262                  "Scatter/gather list (SGL) page size in number of S/G "
263                  "entries.  If your application is doing a lot of very large "
264                  "transfers, you may want to increase the SGL page size.  "
265                  "Default 512.");
266
267 int num_sg_lists = 1024;
268 module_param(num_sg_lists, int, 0);
269 MODULE_PARM_DESC(num_sg_lists,
270                  "Number of scatter/gather lists.  Default 1024.");
271
272 int sg_tablesize = SG_CHUNK_SIZE;
273 module_param(sg_tablesize, int, 0);
274 MODULE_PARM_DESC(sg_tablesize,
275                  "Maximum number of entries in a scatter/gather table.");
276
277 int num_requests = 256;
278 module_param(num_requests, int, 0);
279 MODULE_PARM_DESC(num_requests,
280                  "Number of requests.  Default 256.");
281
282 int num_ae_requests = 4;
283 module_param(num_ae_requests, int, 0);
284 MODULE_PARM_DESC(num_ae_requests,
285                  "Number of VDA asynchronous event requests.  Default 4.");
286
287 int cmd_per_lun = ESAS2R_DEFAULT_CMD_PER_LUN;
288 module_param(cmd_per_lun, int, 0);
289 MODULE_PARM_DESC(cmd_per_lun,
290                  "Maximum number of commands per LUN.  Default "
291                  DEFINED_NUM_TO_STR(ESAS2R_DEFAULT_CMD_PER_LUN) ".");
292
293 int can_queue = 128;
294 module_param(can_queue, int, 0);
295 MODULE_PARM_DESC(can_queue,
296                  "Maximum number of commands per adapter.  Default 128.");
297
298 int esas2r_max_sectors = 0xFFFF;
299 module_param(esas2r_max_sectors, int, 0);
300 MODULE_PARM_DESC(esas2r_max_sectors,
301                  "Maximum number of disk sectors in a single data transfer.  "
302                  "Default 65535 (largest possible setting).");
303
304 int interrupt_mode = 1;
305 module_param(interrupt_mode, int, 0);
306 MODULE_PARM_DESC(interrupt_mode,
307                  "Defines the interrupt mode to use.  0 for legacy"
308                  ", 1 for MSI.  Default is MSI (1).");
309
310 static const struct pci_device_id
311         esas2r_pci_table[] = {
312         { ATTO_VENDOR_ID, 0x0049,         ATTO_VENDOR_ID, 0x0049,
313           0,
314           0, 0 },
315         { ATTO_VENDOR_ID, 0x0049,         ATTO_VENDOR_ID, 0x004A,
316           0,
317           0, 0 },
318         { ATTO_VENDOR_ID, 0x0049,         ATTO_VENDOR_ID, 0x004B,
319           0,
320           0, 0 },
321         { ATTO_VENDOR_ID, 0x0049,         ATTO_VENDOR_ID, 0x004C,
322           0,
323           0, 0 },
324         { ATTO_VENDOR_ID, 0x0049,         ATTO_VENDOR_ID, 0x004D,
325           0,
326           0, 0 },
327         { ATTO_VENDOR_ID, 0x0049,         ATTO_VENDOR_ID, 0x004E,
328           0,
329           0, 0 },
330         { 0,              0,              0,              0,
331           0,
332           0, 0 }
333 };
334
335 MODULE_DEVICE_TABLE(pci, esas2r_pci_table);
336
337 static int
338 esas2r_probe(struct pci_dev *pcid, const struct pci_device_id *id);
339
340 static void
341 esas2r_remove(struct pci_dev *pcid);
342
343 static struct pci_driver
344         esas2r_pci_driver = {
345         .name           = ESAS2R_DRVR_NAME,
346         .id_table       = esas2r_pci_table,
347         .probe          = esas2r_probe,
348         .remove         = esas2r_remove,
349         .suspend        = esas2r_suspend,
350         .resume         = esas2r_resume,
351 };
352
353 static int esas2r_probe(struct pci_dev *pcid,
354                         const struct pci_device_id *id)
355 {
356         struct Scsi_Host *host = NULL;
357         struct esas2r_adapter *a;
358         int err;
359
360         size_t host_alloc_size = sizeof(struct esas2r_adapter)
361                                  + ((num_requests) +
362                                     1) * sizeof(struct esas2r_request);
363
364         esas2r_log_dev(ESAS2R_LOG_DEBG, &(pcid->dev),
365                        "esas2r_probe() 0x%02x 0x%02x 0x%02x 0x%02x",
366                        pcid->vendor,
367                        pcid->device,
368                        pcid->subsystem_vendor,
369                        pcid->subsystem_device);
370
371         esas2r_log_dev(ESAS2R_LOG_INFO, &(pcid->dev),
372                        "before pci_enable_device() "
373                        "enable_cnt: %d",
374                        pcid->enable_cnt.counter);
375
376         err = pci_enable_device(pcid);
377         if (err != 0) {
378                 esas2r_log_dev(ESAS2R_LOG_CRIT, &(pcid->dev),
379                                "pci_enable_device() FAIL (%d)",
380                                err);
381                 return -ENODEV;
382         }
383
384         esas2r_log_dev(ESAS2R_LOG_INFO, &(pcid->dev),
385                        "pci_enable_device() OK");
386         esas2r_log_dev(ESAS2R_LOG_INFO, &(pcid->dev),
387                        "after pci_enable_device() enable_cnt: %d",
388                        pcid->enable_cnt.counter);
389
390         host = scsi_host_alloc(&driver_template, host_alloc_size);
391         if (host == NULL) {
392                 esas2r_log(ESAS2R_LOG_CRIT, "scsi_host_alloc() FAIL");
393                 return -ENODEV;
394         }
395
396         memset(host->hostdata, 0, host_alloc_size);
397
398         a = (struct esas2r_adapter *)host->hostdata;
399
400         esas2r_log(ESAS2R_LOG_INFO, "scsi_host_alloc() OK host: %p", host);
401
402         /* override max LUN and max target id */
403
404         host->max_id = ESAS2R_MAX_ID + 1;
405         host->max_lun = 255;
406
407         /* we can handle 16-byte CDbs */
408
409         host->max_cmd_len = 16;
410
411         host->can_queue = can_queue;
412         host->cmd_per_lun = cmd_per_lun;
413         host->this_id = host->max_id + 1;
414         host->max_channel = 0;
415         host->unique_id = found_adapters;
416         host->sg_tablesize = sg_tablesize;
417         host->max_sectors = esas2r_max_sectors;
418
419         /* set to bus master for BIOses that don't do it for us */
420
421         esas2r_log(ESAS2R_LOG_INFO, "pci_set_master() called");
422
423         pci_set_master(pcid);
424
425         if (!esas2r_init_adapter(host, pcid, found_adapters)) {
426                 esas2r_log(ESAS2R_LOG_CRIT,
427                            "unable to initialize device at PCI bus %x:%x",
428                            pcid->bus->number,
429                            pcid->devfn);
430
431                 esas2r_log_dev(ESAS2R_LOG_INFO, &(host->shost_gendev),
432                                "scsi_host_put() called");
433
434                 scsi_host_put(host);
435
436                 return 0;
437
438         }
439
440         esas2r_log(ESAS2R_LOG_INFO, "pci_set_drvdata(%p, %p) called", pcid,
441                    host->hostdata);
442
443         pci_set_drvdata(pcid, host);
444
445         esas2r_log(ESAS2R_LOG_INFO, "scsi_add_host() called");
446
447         err = scsi_add_host(host, &pcid->dev);
448
449         if (err) {
450                 esas2r_log(ESAS2R_LOG_CRIT, "scsi_add_host returned %d", err);
451                 esas2r_log_dev(ESAS2R_LOG_CRIT, &(host->shost_gendev),
452                                "scsi_add_host() FAIL");
453
454                 esas2r_log_dev(ESAS2R_LOG_INFO, &(host->shost_gendev),
455                                "scsi_host_put() called");
456
457                 scsi_host_put(host);
458
459                 esas2r_log_dev(ESAS2R_LOG_INFO, &(host->shost_gendev),
460                                "pci_set_drvdata(%p, NULL) called",
461                                pcid);
462
463                 pci_set_drvdata(pcid, NULL);
464
465                 return -ENODEV;
466         }
467
468
469         esas2r_fw_event_on(a);
470
471         esas2r_log_dev(ESAS2R_LOG_INFO, &(host->shost_gendev),
472                        "scsi_scan_host() called");
473
474         scsi_scan_host(host);
475
476         /* Add sysfs binary files */
477         if (sysfs_create_bin_file(&host->shost_dev.kobj, &bin_attr_fw))
478                 esas2r_log_dev(ESAS2R_LOG_WARN, &(host->shost_gendev),
479                                "Failed to create sysfs binary file: fw");
480         else
481                 a->sysfs_fw_created = 1;
482
483         if (sysfs_create_bin_file(&host->shost_dev.kobj, &bin_attr_fs))
484                 esas2r_log_dev(ESAS2R_LOG_WARN, &(host->shost_gendev),
485                                "Failed to create sysfs binary file: fs");
486         else
487                 a->sysfs_fs_created = 1;
488
489         if (sysfs_create_bin_file(&host->shost_dev.kobj, &bin_attr_vda))
490                 esas2r_log_dev(ESAS2R_LOG_WARN, &(host->shost_gendev),
491                                "Failed to create sysfs binary file: vda");
492         else
493                 a->sysfs_vda_created = 1;
494
495         if (sysfs_create_bin_file(&host->shost_dev.kobj, &bin_attr_hw))
496                 esas2r_log_dev(ESAS2R_LOG_WARN, &(host->shost_gendev),
497                                "Failed to create sysfs binary file: hw");
498         else
499                 a->sysfs_hw_created = 1;
500
501         if (sysfs_create_bin_file(&host->shost_dev.kobj, &bin_attr_live_nvram))
502                 esas2r_log_dev(ESAS2R_LOG_WARN, &(host->shost_gendev),
503                                "Failed to create sysfs binary file: live_nvram");
504         else
505                 a->sysfs_live_nvram_created = 1;
506
507         if (sysfs_create_bin_file(&host->shost_dev.kobj,
508                                   &bin_attr_default_nvram))
509                 esas2r_log_dev(ESAS2R_LOG_WARN, &(host->shost_gendev),
510                                "Failed to create sysfs binary file: default_nvram");
511         else
512                 a->sysfs_default_nvram_created = 1;
513
514         found_adapters++;
515
516         return 0;
517 }
518
519 static void esas2r_remove(struct pci_dev *pdev)
520 {
521         struct Scsi_Host *host = pci_get_drvdata(pdev);
522         struct esas2r_adapter *a = (struct esas2r_adapter *)host->hostdata;
523
524         esas2r_log_dev(ESAS2R_LOG_INFO, &(pdev->dev),
525                        "esas2r_remove(%p) called; "
526                        "host:%p", pdev,
527                        host);
528
529         esas2r_kill_adapter(a->index);
530         found_adapters--;
531 }
532
533 static int __init esas2r_init(void)
534 {
535         int i;
536
537         esas2r_log(ESAS2R_LOG_INFO, "%s called", __func__);
538
539         /* verify valid parameters */
540
541         if (can_queue < 1) {
542                 esas2r_log(ESAS2R_LOG_WARN,
543                            "warning: can_queue must be at least 1, value "
544                            "forced.");
545                 can_queue = 1;
546         } else if (can_queue > 2048) {
547                 esas2r_log(ESAS2R_LOG_WARN,
548                            "warning: can_queue must be no larger than 2048, "
549                            "value forced.");
550                 can_queue = 2048;
551         }
552
553         if (cmd_per_lun < 1) {
554                 esas2r_log(ESAS2R_LOG_WARN,
555                            "warning: cmd_per_lun must be at least 1, value "
556                            "forced.");
557                 cmd_per_lun = 1;
558         } else if (cmd_per_lun > 2048) {
559                 esas2r_log(ESAS2R_LOG_WARN,
560                            "warning: cmd_per_lun must be no larger than "
561                            "2048, value forced.");
562                 cmd_per_lun = 2048;
563         }
564
565         if (sg_tablesize < 32) {
566                 esas2r_log(ESAS2R_LOG_WARN,
567                            "warning: sg_tablesize must be at least 32, "
568                            "value forced.");
569                 sg_tablesize = 32;
570         }
571
572         if (esas2r_max_sectors < 1) {
573                 esas2r_log(ESAS2R_LOG_WARN,
574                            "warning: esas2r_max_sectors must be at least "
575                            "1, value forced.");
576                 esas2r_max_sectors = 1;
577         } else if (esas2r_max_sectors > 0xffff) {
578                 esas2r_log(ESAS2R_LOG_WARN,
579                            "warning: esas2r_max_sectors must be no larger "
580                            "than 0xffff, value forced.");
581                 esas2r_max_sectors = 0xffff;
582         }
583
584         sgl_page_size &= ~(ESAS2R_SGL_ALIGN - 1);
585
586         if (sgl_page_size < SGL_PG_SZ_MIN)
587                 sgl_page_size = SGL_PG_SZ_MIN;
588         else if (sgl_page_size > SGL_PG_SZ_MAX)
589                 sgl_page_size = SGL_PG_SZ_MAX;
590
591         if (num_sg_lists < NUM_SGL_MIN)
592                 num_sg_lists = NUM_SGL_MIN;
593         else if (num_sg_lists > NUM_SGL_MAX)
594                 num_sg_lists = NUM_SGL_MAX;
595
596         if (num_requests < NUM_REQ_MIN)
597                 num_requests = NUM_REQ_MIN;
598         else if (num_requests > NUM_REQ_MAX)
599                 num_requests = NUM_REQ_MAX;
600
601         if (num_ae_requests < NUM_AE_MIN)
602                 num_ae_requests = NUM_AE_MIN;
603         else if (num_ae_requests > NUM_AE_MAX)
604                 num_ae_requests = NUM_AE_MAX;
605
606         /* set up other globals */
607
608         for (i = 0; i < MAX_ADAPTERS; i++)
609                 esas2r_adapters[i] = NULL;
610
611         return pci_register_driver(&esas2r_pci_driver);
612 }
613
614 /* Handle ioctl calls to "/proc/scsi/esas2r/ATTOnode" */
615 static const struct file_operations esas2r_proc_fops = {
616         .compat_ioctl   = compat_ptr_ioctl,
617         .unlocked_ioctl = esas2r_proc_ioctl,
618 };
619
620 static const struct proc_ops esas2r_proc_ops = {
621         .proc_ioctl             = esas2r_proc_ioctl,
622 #ifdef CONFIG_COMPAT
623         .proc_compat_ioctl      = compat_ptr_ioctl,
624 #endif
625 };
626
627 static struct Scsi_Host *esas2r_proc_host;
628 static int esas2r_proc_major;
629
630 long esas2r_proc_ioctl(struct file *fp, unsigned int cmd, unsigned long arg)
631 {
632         return esas2r_ioctl_handler(esas2r_proc_host->hostdata,
633                                     cmd, (void __user *)arg);
634 }
635
636 static void __exit esas2r_exit(void)
637 {
638         esas2r_log(ESAS2R_LOG_INFO, "%s called", __func__);
639
640         if (esas2r_proc_major > 0) {
641                 esas2r_log(ESAS2R_LOG_INFO, "unregister proc");
642
643                 remove_proc_entry(ATTONODE_NAME,
644                                   esas2r_proc_host->hostt->proc_dir);
645                 unregister_chrdev(esas2r_proc_major, ESAS2R_DRVR_NAME);
646
647                 esas2r_proc_major = 0;
648         }
649
650         esas2r_log(ESAS2R_LOG_INFO, "pci_unregister_driver() called");
651
652         pci_unregister_driver(&esas2r_pci_driver);
653 }
654
655 int esas2r_show_info(struct seq_file *m, struct Scsi_Host *sh)
656 {
657         struct esas2r_adapter *a = (struct esas2r_adapter *)sh->hostdata;
658
659         struct esas2r_target *t;
660         int dev_count = 0;
661
662         esas2r_log(ESAS2R_LOG_DEBG, "esas2r_show_info (%p,%d)", m, sh->host_no);
663
664         seq_printf(m, ESAS2R_LONGNAME "\n"
665                    "Driver version: "ESAS2R_VERSION_STR "\n"
666                    "Flash version: %s\n"
667                    "Firmware version: %s\n"
668                    "Copyright "ESAS2R_COPYRIGHT_YEARS "\n"
669                    "http://www.attotech.com\n"
670                    "\n",
671                    a->flash_rev,
672                    a->fw_rev[0] ? a->fw_rev : "(none)");
673
674
675         seq_printf(m, "Adapter information:\n"
676                    "--------------------\n"
677                    "Model: %s\n"
678                    "SAS address: %02X%02X%02X%02X:%02X%02X%02X%02X\n",
679                    esas2r_get_model_name(a),
680                    a->nvram->sas_addr[0],
681                    a->nvram->sas_addr[1],
682                    a->nvram->sas_addr[2],
683                    a->nvram->sas_addr[3],
684                    a->nvram->sas_addr[4],
685                    a->nvram->sas_addr[5],
686                    a->nvram->sas_addr[6],
687                    a->nvram->sas_addr[7]);
688
689         seq_puts(m, "\n"
690                    "Discovered devices:\n"
691                    "\n"
692                    "   #  Target ID\n"
693                    "---------------\n");
694
695         for (t = a->targetdb; t < a->targetdb_end; t++)
696                 if (t->buffered_target_state == TS_PRESENT) {
697                         seq_printf(m, " %3d   %3d\n",
698                                    ++dev_count,
699                                    (u16)(uintptr_t)(t - a->targetdb));
700                 }
701
702         if (dev_count == 0)
703                 seq_puts(m, "none\n");
704
705         seq_putc(m, '\n');
706         return 0;
707
708 }
709
710 const char *esas2r_info(struct Scsi_Host *sh)
711 {
712         struct esas2r_adapter *a = (struct esas2r_adapter *)sh->hostdata;
713         static char esas2r_info_str[512];
714
715         esas2r_log_dev(ESAS2R_LOG_INFO, &(sh->shost_gendev),
716                        "esas2r_info() called");
717
718         /*
719          * if we haven't done so already, register as a char driver
720          * and stick a node under "/proc/scsi/esas2r/ATTOnode"
721          */
722
723         if (esas2r_proc_major <= 0) {
724                 esas2r_proc_host = sh;
725
726                 esas2r_proc_major = register_chrdev(0, ESAS2R_DRVR_NAME,
727                                                     &esas2r_proc_fops);
728
729                 esas2r_log_dev(ESAS2R_LOG_DEBG, &(sh->shost_gendev),
730                                "register_chrdev (major %d)",
731                                esas2r_proc_major);
732
733                 if (esas2r_proc_major > 0) {
734                         struct proc_dir_entry *pde;
735
736                         pde = proc_create(ATTONODE_NAME, 0,
737                                           sh->hostt->proc_dir,
738                                           &esas2r_proc_ops);
739
740                         if (!pde) {
741                                 esas2r_log_dev(ESAS2R_LOG_WARN,
742                                                &(sh->shost_gendev),
743                                                "failed to create_proc_entry");
744                                 esas2r_proc_major = -1;
745                         }
746                 }
747         }
748
749         sprintf(esas2r_info_str,
750                 ESAS2R_LONGNAME " (bus 0x%02X, device 0x%02X, IRQ 0x%02X)"
751                 " driver version: "ESAS2R_VERSION_STR "  firmware version: "
752                 "%s\n",
753                 a->pcid->bus->number, a->pcid->devfn, a->pcid->irq,
754                 a->fw_rev[0] ? a->fw_rev : "(none)");
755
756         return esas2r_info_str;
757 }
758
759 /* Callback for building a request scatter/gather list */
760 static u32 get_physaddr_from_sgc(struct esas2r_sg_context *sgc, u64 *addr)
761 {
762         u32 len;
763
764         if (likely(sgc->cur_offset == sgc->exp_offset)) {
765                 /*
766                  * the normal case: caller used all bytes from previous call, so
767                  * expected offset is the same as the current offset.
768                  */
769
770                 if (sgc->sgel_count < sgc->num_sgel) {
771                         /* retrieve next segment, except for first time */
772                         if (sgc->exp_offset > (u8 *)0) {
773                                 /* advance current segment */
774                                 sgc->cur_sgel = sg_next(sgc->cur_sgel);
775                                 ++(sgc->sgel_count);
776                         }
777
778
779                         len = sg_dma_len(sgc->cur_sgel);
780                         (*addr) = sg_dma_address(sgc->cur_sgel);
781
782                         /* save the total # bytes returned to caller so far */
783                         sgc->exp_offset += len;
784
785                 } else {
786                         len = 0;
787                 }
788         } else if (sgc->cur_offset < sgc->exp_offset) {
789                 /*
790                  * caller did not use all bytes from previous call. need to
791                  * compute the address based on current segment.
792                  */
793
794                 len = sg_dma_len(sgc->cur_sgel);
795                 (*addr) = sg_dma_address(sgc->cur_sgel);
796
797                 sgc->exp_offset -= len;
798
799                 /* calculate PA based on prev segment address and offsets */
800                 *addr = *addr +
801                         (sgc->cur_offset - sgc->exp_offset);
802
803                 sgc->exp_offset += len;
804
805                 /* re-calculate length based on offset */
806                 len = lower_32_bits(
807                         sgc->exp_offset - sgc->cur_offset);
808         } else {   /* if ( sgc->cur_offset > sgc->exp_offset ) */
809                    /*
810                     * we don't expect the caller to skip ahead.
811                     * cur_offset will never exceed the len we return
812                     */
813                 len = 0;
814         }
815
816         return len;
817 }
818
819 int esas2r_queuecommand(struct Scsi_Host *host, struct scsi_cmnd *cmd)
820 {
821         struct esas2r_adapter *a =
822                 (struct esas2r_adapter *)cmd->device->host->hostdata;
823         struct esas2r_request *rq;
824         struct esas2r_sg_context sgc;
825         unsigned bufflen;
826
827         /* Assume success, if it fails we will fix the result later. */
828         cmd->result = DID_OK << 16;
829
830         if (unlikely(test_bit(AF_DEGRADED_MODE, &a->flags))) {
831                 cmd->result = DID_NO_CONNECT << 16;
832                 cmd->scsi_done(cmd);
833                 return 0;
834         }
835
836         rq = esas2r_alloc_request(a);
837         if (unlikely(rq == NULL)) {
838                 esas2r_debug("esas2r_alloc_request failed");
839                 return SCSI_MLQUEUE_HOST_BUSY;
840         }
841
842         rq->cmd = cmd;
843         bufflen = scsi_bufflen(cmd);
844
845         if (likely(bufflen != 0)) {
846                 if (cmd->sc_data_direction == DMA_TO_DEVICE)
847                         rq->vrq->scsi.flags |= cpu_to_le32(FCP_CMND_WRD);
848                 else if (cmd->sc_data_direction == DMA_FROM_DEVICE)
849                         rq->vrq->scsi.flags |= cpu_to_le32(FCP_CMND_RDD);
850         }
851
852         memcpy(rq->vrq->scsi.cdb, cmd->cmnd, cmd->cmd_len);
853         rq->vrq->scsi.length = cpu_to_le32(bufflen);
854         rq->target_id = cmd->device->id;
855         rq->vrq->scsi.flags |= cpu_to_le32(cmd->device->lun);
856         rq->sense_buf = cmd->sense_buffer;
857         rq->sense_len = SCSI_SENSE_BUFFERSIZE;
858
859         esas2r_sgc_init(&sgc, a, rq, NULL);
860
861         sgc.length = bufflen;
862         sgc.cur_offset = NULL;
863
864         sgc.cur_sgel = scsi_sglist(cmd);
865         sgc.exp_offset = NULL;
866         sgc.num_sgel = scsi_dma_map(cmd);
867         sgc.sgel_count = 0;
868
869         if (unlikely(sgc.num_sgel < 0)) {
870                 esas2r_free_request(a, rq);
871                 return SCSI_MLQUEUE_HOST_BUSY;
872         }
873
874         sgc.get_phys_addr = (PGETPHYSADDR)get_physaddr_from_sgc;
875
876         if (unlikely(!esas2r_build_sg_list(a, rq, &sgc))) {
877                 scsi_dma_unmap(cmd);
878                 esas2r_free_request(a, rq);
879                 return SCSI_MLQUEUE_HOST_BUSY;
880         }
881
882         esas2r_debug("start request %p to %d:%d\n", rq, (int)cmd->device->id,
883                      (int)cmd->device->lun);
884
885         esas2r_start_request(a, rq);
886
887         return 0;
888 }
889
890 static void complete_task_management_request(struct esas2r_adapter *a,
891                                              struct esas2r_request *rq)
892 {
893         (*rq->task_management_status_ptr) = rq->req_stat;
894         esas2r_free_request(a, rq);
895 }
896
897 /*
898  * Searches the specified queue for the specified queue for the command
899  * to abort.
900  *
901  * Return 0 on failure, 1 if command was not found, 2 if command was found
902  */
903 static int esas2r_check_active_queue(struct esas2r_adapter *a,
904                                      struct esas2r_request **abort_request,
905                                      struct scsi_cmnd *cmd,
906                                      struct list_head *queue)
907 {
908         bool found = false;
909         struct esas2r_request *ar = *abort_request;
910         struct esas2r_request *rq;
911         struct list_head *element, *next;
912
913         list_for_each_safe(element, next, queue) {
914
915                 rq = list_entry(element, struct esas2r_request, req_list);
916
917                 if (rq->cmd == cmd) {
918
919                         /* Found the request.  See what to do with it. */
920                         if (queue == &a->active_list) {
921                                 /*
922                                  * We are searching the active queue, which
923                                  * means that we need to send an abort request
924                                  * to the firmware.
925                                  */
926                                 ar = esas2r_alloc_request(a);
927                                 if (ar == NULL) {
928                                         esas2r_log_dev(ESAS2R_LOG_WARN,
929                                                        &(a->host->shost_gendev),
930                                                        "unable to allocate an abort request for cmd %p",
931                                                        cmd);
932                                         return 0; /* Failure */
933                                 }
934
935                                 /*
936                                  * Task management request must be formatted
937                                  * with a lock held.
938                                  */
939                                 ar->sense_len = 0;
940                                 ar->vrq->scsi.length = 0;
941                                 ar->target_id = rq->target_id;
942                                 ar->vrq->scsi.flags |= cpu_to_le32(
943                                         (u8)le32_to_cpu(rq->vrq->scsi.flags));
944
945                                 memset(ar->vrq->scsi.cdb, 0,
946                                        sizeof(ar->vrq->scsi.cdb));
947
948                                 ar->vrq->scsi.flags |= cpu_to_le32(
949                                         FCP_CMND_TRM);
950                                 ar->vrq->scsi.u.abort_handle =
951                                         rq->vrq->scsi.handle;
952                         } else {
953                                 /*
954                                  * The request is pending but not active on
955                                  * the firmware.  Just free it now and we'll
956                                  * report the successful abort below.
957                                  */
958                                 list_del_init(&rq->req_list);
959                                 esas2r_free_request(a, rq);
960                         }
961
962                         found = true;
963                         break;
964                 }
965
966         }
967
968         if (!found)
969                 return 1;       /* Not found */
970
971         return 2;               /* found */
972
973
974 }
975
976 int esas2r_eh_abort(struct scsi_cmnd *cmd)
977 {
978         struct esas2r_adapter *a =
979                 (struct esas2r_adapter *)cmd->device->host->hostdata;
980         struct esas2r_request *abort_request = NULL;
981         unsigned long flags;
982         struct list_head *queue;
983         int result;
984
985         esas2r_log(ESAS2R_LOG_INFO, "eh_abort (%p)", cmd);
986
987         if (test_bit(AF_DEGRADED_MODE, &a->flags)) {
988                 cmd->result = DID_ABORT << 16;
989
990                 scsi_set_resid(cmd, 0);
991
992                 cmd->scsi_done(cmd);
993
994                 return SUCCESS;
995         }
996
997         spin_lock_irqsave(&a->queue_lock, flags);
998
999         /*
1000          * Run through the defer and active queues looking for the request
1001          * to abort.
1002          */
1003
1004         queue = &a->defer_list;
1005
1006 check_active_queue:
1007
1008         result = esas2r_check_active_queue(a, &abort_request, cmd, queue);
1009
1010         if (!result) {
1011                 spin_unlock_irqrestore(&a->queue_lock, flags);
1012                 return FAILED;
1013         } else if (result == 2 && (queue == &a->defer_list)) {
1014                 queue = &a->active_list;
1015                 goto check_active_queue;
1016         }
1017
1018         spin_unlock_irqrestore(&a->queue_lock, flags);
1019
1020         if (abort_request) {
1021                 u8 task_management_status = RS_PENDING;
1022
1023                 /*
1024                  * the request is already active, so we need to tell
1025                  * the firmware to abort it and wait for the response.
1026                  */
1027
1028                 abort_request->comp_cb = complete_task_management_request;
1029                 abort_request->task_management_status_ptr =
1030                         &task_management_status;
1031
1032                 esas2r_start_request(a, abort_request);
1033
1034                 if (atomic_read(&a->disable_cnt) == 0)
1035                         esas2r_do_deferred_processes(a);
1036
1037                 while (task_management_status == RS_PENDING)
1038                         msleep(10);
1039
1040                 /*
1041                  * Once we get here, the original request will have been
1042                  * completed by the firmware and the abort request will have
1043                  * been cleaned up.  we're done!
1044                  */
1045
1046                 return SUCCESS;
1047         }
1048
1049         /*
1050          * If we get here, either we found the inactive request and
1051          * freed it, or we didn't find it at all.  Either way, success!
1052          */
1053
1054         cmd->result = DID_ABORT << 16;
1055
1056         scsi_set_resid(cmd, 0);
1057
1058         cmd->scsi_done(cmd);
1059
1060         return SUCCESS;
1061 }
1062
1063 static int esas2r_host_bus_reset(struct scsi_cmnd *cmd, bool host_reset)
1064 {
1065         struct esas2r_adapter *a =
1066                 (struct esas2r_adapter *)cmd->device->host->hostdata;
1067
1068         if (test_bit(AF_DEGRADED_MODE, &a->flags))
1069                 return FAILED;
1070
1071         if (host_reset)
1072                 esas2r_reset_adapter(a);
1073         else
1074                 esas2r_reset_bus(a);
1075
1076         /* above call sets the AF_OS_RESET flag.  wait for it to clear. */
1077
1078         while (test_bit(AF_OS_RESET, &a->flags)) {
1079                 msleep(10);
1080
1081                 if (test_bit(AF_DEGRADED_MODE, &a->flags))
1082                         return FAILED;
1083         }
1084
1085         if (test_bit(AF_DEGRADED_MODE, &a->flags))
1086                 return FAILED;
1087
1088         return SUCCESS;
1089 }
1090
1091 int esas2r_host_reset(struct scsi_cmnd *cmd)
1092 {
1093         esas2r_log(ESAS2R_LOG_INFO, "host_reset (%p)", cmd);
1094
1095         return esas2r_host_bus_reset(cmd, true);
1096 }
1097
1098 int esas2r_bus_reset(struct scsi_cmnd *cmd)
1099 {
1100         esas2r_log(ESAS2R_LOG_INFO, "bus_reset (%p)", cmd);
1101
1102         return esas2r_host_bus_reset(cmd, false);
1103 }
1104
1105 static int esas2r_dev_targ_reset(struct scsi_cmnd *cmd, bool target_reset)
1106 {
1107         struct esas2r_adapter *a =
1108                 (struct esas2r_adapter *)cmd->device->host->hostdata;
1109         struct esas2r_request *rq;
1110         u8 task_management_status = RS_PENDING;
1111         bool completed;
1112
1113         if (test_bit(AF_DEGRADED_MODE, &a->flags))
1114                 return FAILED;
1115
1116 retry:
1117         rq = esas2r_alloc_request(a);
1118         if (rq == NULL) {
1119                 if (target_reset) {
1120                         esas2r_log(ESAS2R_LOG_CRIT,
1121                                    "unable to allocate a request for a "
1122                                    "target reset (%d)!",
1123                                    cmd->device->id);
1124                 } else {
1125                         esas2r_log(ESAS2R_LOG_CRIT,
1126                                    "unable to allocate a request for a "
1127                                    "device reset (%d:%llu)!",
1128                                    cmd->device->id,
1129                                    cmd->device->lun);
1130                 }
1131
1132
1133                 return FAILED;
1134         }
1135
1136         rq->target_id = cmd->device->id;
1137         rq->vrq->scsi.flags |= cpu_to_le32(cmd->device->lun);
1138         rq->req_stat = RS_PENDING;
1139
1140         rq->comp_cb = complete_task_management_request;
1141         rq->task_management_status_ptr = &task_management_status;
1142
1143         if (target_reset) {
1144                 esas2r_debug("issuing target reset (%p) to id %d", rq,
1145                              cmd->device->id);
1146                 completed = esas2r_send_task_mgmt(a, rq, 0x20);
1147         } else {
1148                 esas2r_debug("issuing device reset (%p) to id %d lun %d", rq,
1149                              cmd->device->id, cmd->device->lun);
1150                 completed = esas2r_send_task_mgmt(a, rq, 0x10);
1151         }
1152
1153         if (completed) {
1154                 /* Task management cmd completed right away, need to free it. */
1155
1156                 esas2r_free_request(a, rq);
1157         } else {
1158                 /*
1159                  * Wait for firmware to complete the request.  Completion
1160                  * callback will free it.
1161                  */
1162                 while (task_management_status == RS_PENDING)
1163                         msleep(10);
1164         }
1165
1166         if (test_bit(AF_DEGRADED_MODE, &a->flags))
1167                 return FAILED;
1168
1169         if (task_management_status == RS_BUSY) {
1170                 /*
1171                  * Busy, probably because we are flashing.  Wait a bit and
1172                  * try again.
1173                  */
1174                 msleep(100);
1175                 goto retry;
1176         }
1177
1178         return SUCCESS;
1179 }
1180
1181 int esas2r_device_reset(struct scsi_cmnd *cmd)
1182 {
1183         esas2r_log(ESAS2R_LOG_INFO, "device_reset (%p)", cmd);
1184
1185         return esas2r_dev_targ_reset(cmd, false);
1186
1187 }
1188
1189 int esas2r_target_reset(struct scsi_cmnd *cmd)
1190 {
1191         esas2r_log(ESAS2R_LOG_INFO, "target_reset (%p)", cmd);
1192
1193         return esas2r_dev_targ_reset(cmd, true);
1194 }
1195
1196 void esas2r_log_request_failure(struct esas2r_adapter *a,
1197                                 struct esas2r_request *rq)
1198 {
1199         u8 reqstatus = rq->req_stat;
1200
1201         if (reqstatus == RS_SUCCESS)
1202                 return;
1203
1204         if (rq->vrq->scsi.function == VDA_FUNC_SCSI) {
1205                 if (reqstatus == RS_SCSI_ERROR) {
1206                         if (rq->func_rsp.scsi_rsp.sense_len >= 13) {
1207                                 esas2r_log(ESAS2R_LOG_WARN,
1208                                            "request failure - SCSI error %x ASC:%x ASCQ:%x CDB:%x",
1209                                            rq->sense_buf[2], rq->sense_buf[12],
1210                                            rq->sense_buf[13],
1211                                            rq->vrq->scsi.cdb[0]);
1212                         } else {
1213                                 esas2r_log(ESAS2R_LOG_WARN,
1214                                            "request failure - SCSI error CDB:%x\n",
1215                                            rq->vrq->scsi.cdb[0]);
1216                         }
1217                 } else if ((rq->vrq->scsi.cdb[0] != INQUIRY
1218                             && rq->vrq->scsi.cdb[0] != REPORT_LUNS)
1219                            || (reqstatus != RS_SEL
1220                                && reqstatus != RS_SEL2)) {
1221                         if ((reqstatus == RS_UNDERRUN) &&
1222                             (rq->vrq->scsi.cdb[0] == INQUIRY)) {
1223                                 /* Don't log inquiry underruns */
1224                         } else {
1225                                 esas2r_log(ESAS2R_LOG_WARN,
1226                                            "request failure - cdb:%x reqstatus:%d target:%d",
1227                                            rq->vrq->scsi.cdb[0], reqstatus,
1228                                            rq->target_id);
1229                         }
1230                 }
1231         }
1232 }
1233
1234 void esas2r_wait_request(struct esas2r_adapter *a, struct esas2r_request *rq)
1235 {
1236         u32 starttime;
1237         u32 timeout;
1238
1239         starttime = jiffies_to_msecs(jiffies);
1240         timeout = rq->timeout ? rq->timeout : 5000;
1241
1242         while (true) {
1243                 esas2r_polled_interrupt(a);
1244
1245                 if (rq->req_stat != RS_STARTED)
1246                         break;
1247
1248                 schedule_timeout_interruptible(msecs_to_jiffies(100));
1249
1250                 if ((jiffies_to_msecs(jiffies) - starttime) > timeout) {
1251                         esas2r_hdebug("request TMO");
1252                         esas2r_bugon();
1253
1254                         rq->req_stat = RS_TIMEOUT;
1255
1256                         esas2r_local_reset_adapter(a);
1257                         return;
1258                 }
1259         }
1260 }
1261
1262 u32 esas2r_map_data_window(struct esas2r_adapter *a, u32 addr_lo)
1263 {
1264         u32 offset = addr_lo & (MW_DATA_WINDOW_SIZE - 1);
1265         u32 base = addr_lo & -(signed int)MW_DATA_WINDOW_SIZE;
1266
1267         if (a->window_base != base) {
1268                 esas2r_write_register_dword(a, MVR_PCI_WIN1_REMAP,
1269                                             base | MVRPW1R_ENABLE);
1270                 esas2r_flush_register_dword(a, MVR_PCI_WIN1_REMAP);
1271                 a->window_base = base;
1272         }
1273
1274         return offset;
1275 }
1276
1277 /* Read a block of data from chip memory */
1278 bool esas2r_read_mem_block(struct esas2r_adapter *a,
1279                            void *to,
1280                            u32 from,
1281                            u32 size)
1282 {
1283         u8 *end = (u8 *)to;
1284
1285         while (size) {
1286                 u32 len;
1287                 u32 offset;
1288                 u32 iatvr;
1289
1290                 iatvr = (from & -(signed int)MW_DATA_WINDOW_SIZE);
1291
1292                 esas2r_map_data_window(a, iatvr);
1293
1294                 offset = from & (MW_DATA_WINDOW_SIZE - 1);
1295                 len = size;
1296
1297                 if (len > MW_DATA_WINDOW_SIZE - offset)
1298                         len = MW_DATA_WINDOW_SIZE - offset;
1299
1300                 from += len;
1301                 size -= len;
1302
1303                 while (len--) {
1304                         *end++ = esas2r_read_data_byte(a, offset);
1305                         offset++;
1306                 }
1307         }
1308
1309         return true;
1310 }
1311
1312 void esas2r_nuxi_mgt_data(u8 function, void *data)
1313 {
1314         struct atto_vda_grp_info *g;
1315         struct atto_vda_devinfo *d;
1316         struct atto_vdapart_info *p;
1317         struct atto_vda_dh_info *h;
1318         struct atto_vda_metrics_info *m;
1319         struct atto_vda_schedule_info *s;
1320         struct atto_vda_buzzer_info *b;
1321         u8 i;
1322
1323         switch (function) {
1324         case VDAMGT_BUZZER_INFO:
1325         case VDAMGT_BUZZER_SET:
1326
1327                 b = (struct atto_vda_buzzer_info *)data;
1328
1329                 b->duration = le32_to_cpu(b->duration);
1330                 break;
1331
1332         case VDAMGT_SCHEDULE_INFO:
1333         case VDAMGT_SCHEDULE_EVENT:
1334
1335                 s = (struct atto_vda_schedule_info *)data;
1336
1337                 s->id = le32_to_cpu(s->id);
1338
1339                 break;
1340
1341         case VDAMGT_DEV_INFO:
1342         case VDAMGT_DEV_CLEAN:
1343         case VDAMGT_DEV_PT_INFO:
1344         case VDAMGT_DEV_FEATURES:
1345         case VDAMGT_DEV_PT_FEATURES:
1346         case VDAMGT_DEV_OPERATION:
1347
1348                 d = (struct atto_vda_devinfo *)data;
1349
1350                 d->capacity = le64_to_cpu(d->capacity);
1351                 d->block_size = le32_to_cpu(d->block_size);
1352                 d->ses_dev_index = le16_to_cpu(d->ses_dev_index);
1353                 d->target_id = le16_to_cpu(d->target_id);
1354                 d->lun = le16_to_cpu(d->lun);
1355                 d->features = le16_to_cpu(d->features);
1356                 break;
1357
1358         case VDAMGT_GRP_INFO:
1359         case VDAMGT_GRP_CREATE:
1360         case VDAMGT_GRP_DELETE:
1361         case VDAMGT_ADD_STORAGE:
1362         case VDAMGT_MEMBER_ADD:
1363         case VDAMGT_GRP_COMMIT:
1364         case VDAMGT_GRP_REBUILD:
1365         case VDAMGT_GRP_COMMIT_INIT:
1366         case VDAMGT_QUICK_RAID:
1367         case VDAMGT_GRP_FEATURES:
1368         case VDAMGT_GRP_COMMIT_INIT_AUTOMAP:
1369         case VDAMGT_QUICK_RAID_INIT_AUTOMAP:
1370         case VDAMGT_SPARE_LIST:
1371         case VDAMGT_SPARE_ADD:
1372         case VDAMGT_SPARE_REMOVE:
1373         case VDAMGT_LOCAL_SPARE_ADD:
1374         case VDAMGT_GRP_OPERATION:
1375
1376                 g = (struct atto_vda_grp_info *)data;
1377
1378                 g->capacity = le64_to_cpu(g->capacity);
1379                 g->block_size = le32_to_cpu(g->block_size);
1380                 g->interleave = le32_to_cpu(g->interleave);
1381                 g->features = le16_to_cpu(g->features);
1382
1383                 for (i = 0; i < 32; i++)
1384                         g->members[i] = le16_to_cpu(g->members[i]);
1385
1386                 break;
1387
1388         case VDAMGT_PART_INFO:
1389         case VDAMGT_PART_MAP:
1390         case VDAMGT_PART_UNMAP:
1391         case VDAMGT_PART_AUTOMAP:
1392         case VDAMGT_PART_SPLIT:
1393         case VDAMGT_PART_MERGE:
1394
1395                 p = (struct atto_vdapart_info *)data;
1396
1397                 p->part_size = le64_to_cpu(p->part_size);
1398                 p->start_lba = le32_to_cpu(p->start_lba);
1399                 p->block_size = le32_to_cpu(p->block_size);
1400                 p->target_id = le16_to_cpu(p->target_id);
1401                 break;
1402
1403         case VDAMGT_DEV_HEALTH_REQ:
1404
1405                 h = (struct atto_vda_dh_info *)data;
1406
1407                 h->med_defect_cnt = le32_to_cpu(h->med_defect_cnt);
1408                 h->info_exc_cnt = le32_to_cpu(h->info_exc_cnt);
1409                 break;
1410
1411         case VDAMGT_DEV_METRICS:
1412
1413                 m = (struct atto_vda_metrics_info *)data;
1414
1415                 for (i = 0; i < 32; i++)
1416                         m->dev_indexes[i] = le16_to_cpu(m->dev_indexes[i]);
1417
1418                 break;
1419
1420         default:
1421                 break;
1422         }
1423 }
1424
1425 void esas2r_nuxi_cfg_data(u8 function, void *data)
1426 {
1427         struct atto_vda_cfg_init *ci;
1428
1429         switch (function) {
1430         case VDA_CFG_INIT:
1431         case VDA_CFG_GET_INIT:
1432         case VDA_CFG_GET_INIT2:
1433
1434                 ci = (struct atto_vda_cfg_init *)data;
1435
1436                 ci->date_time.year = le16_to_cpu(ci->date_time.year);
1437                 ci->sgl_page_size = le32_to_cpu(ci->sgl_page_size);
1438                 ci->vda_version = le32_to_cpu(ci->vda_version);
1439                 ci->epoch_time = le32_to_cpu(ci->epoch_time);
1440                 ci->ioctl_tunnel = le32_to_cpu(ci->ioctl_tunnel);
1441                 ci->num_targets_backend = le32_to_cpu(ci->num_targets_backend);
1442                 break;
1443
1444         default:
1445                 break;
1446         }
1447 }
1448
1449 void esas2r_nuxi_ae_data(union atto_vda_ae *ae)
1450 {
1451         struct atto_vda_ae_raid *r = &ae->raid;
1452         struct atto_vda_ae_lu *l = &ae->lu;
1453
1454         switch (ae->hdr.bytype) {
1455         case VDAAE_HDR_TYPE_RAID:
1456
1457                 r->dwflags = le32_to_cpu(r->dwflags);
1458                 break;
1459
1460         case VDAAE_HDR_TYPE_LU:
1461
1462                 l->dwevent = le32_to_cpu(l->dwevent);
1463                 l->wphys_target_id = le16_to_cpu(l->wphys_target_id);
1464                 l->id.tgtlun.wtarget_id = le16_to_cpu(l->id.tgtlun.wtarget_id);
1465
1466                 if (l->hdr.bylength >= offsetof(struct atto_vda_ae_lu, id)
1467                     + sizeof(struct atto_vda_ae_lu_tgt_lun_raid)) {
1468                         l->id.tgtlun_raid.dwinterleave
1469                                 = le32_to_cpu(l->id.tgtlun_raid.dwinterleave);
1470                         l->id.tgtlun_raid.dwblock_size
1471                                 = le32_to_cpu(l->id.tgtlun_raid.dwblock_size);
1472                 }
1473
1474                 break;
1475
1476         case VDAAE_HDR_TYPE_DISK:
1477         default:
1478                 break;
1479         }
1480 }
1481
1482 void esas2r_free_request(struct esas2r_adapter *a, struct esas2r_request *rq)
1483 {
1484         unsigned long flags;
1485
1486         esas2r_rq_destroy_request(rq, a);
1487         spin_lock_irqsave(&a->request_lock, flags);
1488         list_add(&rq->comp_list, &a->avail_request);
1489         spin_unlock_irqrestore(&a->request_lock, flags);
1490 }
1491
1492 struct esas2r_request *esas2r_alloc_request(struct esas2r_adapter *a)
1493 {
1494         struct esas2r_request *rq;
1495         unsigned long flags;
1496
1497         spin_lock_irqsave(&a->request_lock, flags);
1498
1499         if (unlikely(list_empty(&a->avail_request))) {
1500                 spin_unlock_irqrestore(&a->request_lock, flags);
1501                 return NULL;
1502         }
1503
1504         rq = list_first_entry(&a->avail_request, struct esas2r_request,
1505                               comp_list);
1506         list_del(&rq->comp_list);
1507         spin_unlock_irqrestore(&a->request_lock, flags);
1508         esas2r_rq_init_request(rq, a);
1509
1510         return rq;
1511
1512 }
1513
1514 void esas2r_complete_request_cb(struct esas2r_adapter *a,
1515                                 struct esas2r_request *rq)
1516 {
1517         esas2r_debug("completing request %p\n", rq);
1518
1519         scsi_dma_unmap(rq->cmd);
1520
1521         if (unlikely(rq->req_stat != RS_SUCCESS)) {
1522                 esas2r_debug("[%x STATUS %x:%x (%x)]", rq->target_id,
1523                              rq->req_stat,
1524                              rq->func_rsp.scsi_rsp.scsi_stat,
1525                              rq->cmd);
1526
1527                 rq->cmd->result =
1528                         ((esas2r_req_status_to_error(rq->req_stat) << 16)
1529                          | (rq->func_rsp.scsi_rsp.scsi_stat & STATUS_MASK));
1530
1531                 if (rq->req_stat == RS_UNDERRUN)
1532                         scsi_set_resid(rq->cmd,
1533                                        le32_to_cpu(rq->func_rsp.scsi_rsp.
1534                                                    residual_length));
1535                 else
1536                         scsi_set_resid(rq->cmd, 0);
1537         }
1538
1539         rq->cmd->scsi_done(rq->cmd);
1540
1541         esas2r_free_request(a, rq);
1542 }
1543
1544 /* Run tasklet to handle stuff outside of interrupt context. */
1545 void esas2r_adapter_tasklet(unsigned long context)
1546 {
1547         struct esas2r_adapter *a = (struct esas2r_adapter *)context;
1548
1549         if (unlikely(test_bit(AF2_TIMER_TICK, &a->flags2))) {
1550                 clear_bit(AF2_TIMER_TICK, &a->flags2);
1551                 esas2r_timer_tick(a);
1552         }
1553
1554         if (likely(test_bit(AF2_INT_PENDING, &a->flags2))) {
1555                 clear_bit(AF2_INT_PENDING, &a->flags2);
1556                 esas2r_adapter_interrupt(a);
1557         }
1558
1559         if (esas2r_is_tasklet_pending(a))
1560                 esas2r_do_tasklet_tasks(a);
1561
1562         if (esas2r_is_tasklet_pending(a)
1563             || (test_bit(AF2_INT_PENDING, &a->flags2))
1564             || (test_bit(AF2_TIMER_TICK, &a->flags2))) {
1565                 clear_bit(AF_TASKLET_SCHEDULED, &a->flags);
1566                 esas2r_schedule_tasklet(a);
1567         } else {
1568                 clear_bit(AF_TASKLET_SCHEDULED, &a->flags);
1569         }
1570 }
1571
1572 static void esas2r_timer_callback(struct timer_list *t);
1573
1574 void esas2r_kickoff_timer(struct esas2r_adapter *a)
1575 {
1576         timer_setup(&a->timer, esas2r_timer_callback, 0);
1577
1578         a->timer.expires = jiffies +
1579                            msecs_to_jiffies(100);
1580
1581         add_timer(&a->timer);
1582 }
1583
1584 static void esas2r_timer_callback(struct timer_list *t)
1585 {
1586         struct esas2r_adapter *a = from_timer(a, t, timer);
1587
1588         set_bit(AF2_TIMER_TICK, &a->flags2);
1589
1590         esas2r_schedule_tasklet(a);
1591
1592         esas2r_kickoff_timer(a);
1593 }
1594
1595 /*
1596  * Firmware events need to be handled outside of interrupt context
1597  * so we schedule a delayed_work to handle them.
1598  */
1599
1600 static void
1601 esas2r_free_fw_event(struct esas2r_fw_event_work *fw_event)
1602 {
1603         unsigned long flags;
1604         struct esas2r_adapter *a = fw_event->a;
1605
1606         spin_lock_irqsave(&a->fw_event_lock, flags);
1607         list_del(&fw_event->list);
1608         kfree(fw_event);
1609         spin_unlock_irqrestore(&a->fw_event_lock, flags);
1610 }
1611
1612 void
1613 esas2r_fw_event_off(struct esas2r_adapter *a)
1614 {
1615         unsigned long flags;
1616
1617         spin_lock_irqsave(&a->fw_event_lock, flags);
1618         a->fw_events_off = 1;
1619         spin_unlock_irqrestore(&a->fw_event_lock, flags);
1620 }
1621
1622 void
1623 esas2r_fw_event_on(struct esas2r_adapter *a)
1624 {
1625         unsigned long flags;
1626
1627         spin_lock_irqsave(&a->fw_event_lock, flags);
1628         a->fw_events_off = 0;
1629         spin_unlock_irqrestore(&a->fw_event_lock, flags);
1630 }
1631
1632 static void esas2r_add_device(struct esas2r_adapter *a, u16 target_id)
1633 {
1634         int ret;
1635         struct scsi_device *scsi_dev;
1636
1637         scsi_dev = scsi_device_lookup(a->host, 0, target_id, 0);
1638
1639         if (scsi_dev) {
1640                 esas2r_log_dev(
1641                         ESAS2R_LOG_WARN,
1642                         &(scsi_dev->
1643                           sdev_gendev),
1644                         "scsi device already exists at id %d", target_id);
1645
1646                 scsi_device_put(scsi_dev);
1647         } else {
1648                 esas2r_log_dev(
1649                         ESAS2R_LOG_INFO,
1650                         &(a->host->
1651                           shost_gendev),
1652                         "scsi_add_device() called for 0:%d:0",
1653                         target_id);
1654
1655                 ret = scsi_add_device(a->host, 0, target_id, 0);
1656                 if (ret) {
1657                         esas2r_log_dev(
1658                                 ESAS2R_LOG_CRIT,
1659                                 &(a->host->
1660                                   shost_gendev),
1661                                 "scsi_add_device failed with %d for id %d",
1662                                 ret, target_id);
1663                 }
1664         }
1665 }
1666
1667 static void esas2r_remove_device(struct esas2r_adapter *a, u16 target_id)
1668 {
1669         struct scsi_device *scsi_dev;
1670
1671         scsi_dev = scsi_device_lookup(a->host, 0, target_id, 0);
1672
1673         if (scsi_dev) {
1674                 scsi_device_set_state(scsi_dev, SDEV_OFFLINE);
1675
1676                 esas2r_log_dev(
1677                         ESAS2R_LOG_INFO,
1678                         &(scsi_dev->
1679                           sdev_gendev),
1680                         "scsi_remove_device() called for 0:%d:0",
1681                         target_id);
1682
1683                 scsi_remove_device(scsi_dev);
1684
1685                 esas2r_log_dev(
1686                         ESAS2R_LOG_INFO,
1687                         &(scsi_dev->
1688                           sdev_gendev),
1689                         "scsi_device_put() called");
1690
1691                 scsi_device_put(scsi_dev);
1692         } else {
1693                 esas2r_log_dev(
1694                         ESAS2R_LOG_WARN,
1695                         &(a->host->shost_gendev),
1696                         "no target found at id %d",
1697                         target_id);
1698         }
1699 }
1700
1701 /*
1702  * Sends a firmware asynchronous event to anyone who happens to be
1703  * listening on the defined ATTO VDA event ports.
1704  */
1705 static void esas2r_send_ae_event(struct esas2r_fw_event_work *fw_event)
1706 {
1707         struct esas2r_vda_ae *ae = (struct esas2r_vda_ae *)fw_event->data;
1708         char *type;
1709
1710         switch (ae->vda_ae.hdr.bytype) {
1711         case VDAAE_HDR_TYPE_RAID:
1712                 type = "RAID group state change";
1713                 break;
1714
1715         case VDAAE_HDR_TYPE_LU:
1716                 type = "Mapped destination LU change";
1717                 break;
1718
1719         case VDAAE_HDR_TYPE_DISK:
1720                 type = "Physical disk inventory change";
1721                 break;
1722
1723         case VDAAE_HDR_TYPE_RESET:
1724                 type = "Firmware reset";
1725                 break;
1726
1727         case VDAAE_HDR_TYPE_LOG_INFO:
1728                 type = "Event Log message (INFO level)";
1729                 break;
1730
1731         case VDAAE_HDR_TYPE_LOG_WARN:
1732                 type = "Event Log message (WARN level)";
1733                 break;
1734
1735         case VDAAE_HDR_TYPE_LOG_CRIT:
1736                 type = "Event Log message (CRIT level)";
1737                 break;
1738
1739         case VDAAE_HDR_TYPE_LOG_FAIL:
1740                 type = "Event Log message (FAIL level)";
1741                 break;
1742
1743         case VDAAE_HDR_TYPE_NVC:
1744                 type = "NVCache change";
1745                 break;
1746
1747         case VDAAE_HDR_TYPE_TLG_INFO:
1748                 type = "Time stamped log message (INFO level)";
1749                 break;
1750
1751         case VDAAE_HDR_TYPE_TLG_WARN:
1752                 type = "Time stamped log message (WARN level)";
1753                 break;
1754
1755         case VDAAE_HDR_TYPE_TLG_CRIT:
1756                 type = "Time stamped log message (CRIT level)";
1757                 break;
1758
1759         case VDAAE_HDR_TYPE_PWRMGT:
1760                 type = "Power management";
1761                 break;
1762
1763         case VDAAE_HDR_TYPE_MUTE:
1764                 type = "Mute button pressed";
1765                 break;
1766
1767         case VDAAE_HDR_TYPE_DEV:
1768                 type = "Device attribute change";
1769                 break;
1770
1771         default:
1772                 type = "Unknown";
1773                 break;
1774         }
1775
1776         esas2r_log(ESAS2R_LOG_WARN,
1777                    "An async event of type \"%s\" was received from the firmware.  The event contents are:",
1778                    type);
1779         esas2r_log_hexdump(ESAS2R_LOG_WARN, &ae->vda_ae,
1780                            ae->vda_ae.hdr.bylength);
1781
1782 }
1783
1784 static void
1785 esas2r_firmware_event_work(struct work_struct *work)
1786 {
1787         struct esas2r_fw_event_work *fw_event =
1788                 container_of(work, struct esas2r_fw_event_work, work.work);
1789
1790         struct esas2r_adapter *a = fw_event->a;
1791
1792         u16 target_id = *(u16 *)&fw_event->data[0];
1793
1794         if (a->fw_events_off)
1795                 goto done;
1796
1797         switch (fw_event->type) {
1798         case fw_event_null:
1799                 break; /* do nothing */
1800
1801         case fw_event_lun_change:
1802                 esas2r_remove_device(a, target_id);
1803                 esas2r_add_device(a, target_id);
1804                 break;
1805
1806         case fw_event_present:
1807                 esas2r_add_device(a, target_id);
1808                 break;
1809
1810         case fw_event_not_present:
1811                 esas2r_remove_device(a, target_id);
1812                 break;
1813
1814         case fw_event_vda_ae:
1815                 esas2r_send_ae_event(fw_event);
1816                 break;
1817         }
1818
1819 done:
1820         esas2r_free_fw_event(fw_event);
1821 }
1822
1823 void esas2r_queue_fw_event(struct esas2r_adapter *a,
1824                            enum fw_event_type type,
1825                            void *data,
1826                            int data_sz)
1827 {
1828         struct esas2r_fw_event_work *fw_event;
1829         unsigned long flags;
1830
1831         fw_event = kzalloc(sizeof(struct esas2r_fw_event_work), GFP_ATOMIC);
1832         if (!fw_event) {
1833                 esas2r_log(ESAS2R_LOG_WARN,
1834                            "esas2r_queue_fw_event failed to alloc");
1835                 return;
1836         }
1837
1838         if (type == fw_event_vda_ae) {
1839                 struct esas2r_vda_ae *ae =
1840                         (struct esas2r_vda_ae *)fw_event->data;
1841
1842                 ae->signature = ESAS2R_VDA_EVENT_SIG;
1843                 ae->bus_number = a->pcid->bus->number;
1844                 ae->devfn = a->pcid->devfn;
1845                 memcpy(&ae->vda_ae, data, sizeof(ae->vda_ae));
1846         } else {
1847                 memcpy(fw_event->data, data, data_sz);
1848         }
1849
1850         fw_event->type = type;
1851         fw_event->a = a;
1852
1853         spin_lock_irqsave(&a->fw_event_lock, flags);
1854         list_add_tail(&fw_event->list, &a->fw_event_list);
1855         INIT_DELAYED_WORK(&fw_event->work, esas2r_firmware_event_work);
1856         queue_delayed_work_on(
1857                 smp_processor_id(), a->fw_event_q, &fw_event->work,
1858                 msecs_to_jiffies(1));
1859         spin_unlock_irqrestore(&a->fw_event_lock, flags);
1860 }
1861
1862 void esas2r_target_state_changed(struct esas2r_adapter *a, u16 targ_id,
1863                                  u8 state)
1864 {
1865         if (state == TS_LUN_CHANGE)
1866                 esas2r_queue_fw_event(a, fw_event_lun_change, &targ_id,
1867                                       sizeof(targ_id));
1868         else if (state == TS_PRESENT)
1869                 esas2r_queue_fw_event(a, fw_event_present, &targ_id,
1870                                       sizeof(targ_id));
1871         else if (state == TS_NOT_PRESENT)
1872                 esas2r_queue_fw_event(a, fw_event_not_present, &targ_id,
1873                                       sizeof(targ_id));
1874 }
1875
1876 /* Translate status to a Linux SCSI mid-layer error code */
1877 int esas2r_req_status_to_error(u8 req_stat)
1878 {
1879         switch (req_stat) {
1880         case RS_OVERRUN:
1881         case RS_UNDERRUN:
1882         case RS_SUCCESS:
1883         /*
1884          * NOTE: SCSI mid-layer wants a good status for a SCSI error, because
1885          *       it will check the scsi_stat value in the completion anyway.
1886          */
1887         case RS_SCSI_ERROR:
1888                 return DID_OK;
1889
1890         case RS_SEL:
1891         case RS_SEL2:
1892                 return DID_NO_CONNECT;
1893
1894         case RS_RESET:
1895                 return DID_RESET;
1896
1897         case RS_ABORTED:
1898                 return DID_ABORT;
1899
1900         case RS_BUSY:
1901                 return DID_BUS_BUSY;
1902         }
1903
1904         /* everything else is just an error. */
1905
1906         return DID_ERROR;
1907 }
1908
1909 module_init(esas2r_init);
1910 module_exit(esas2r_exit);