mtip32xx: Make SGL container per-command to eliminate high order dma allocation
[firefly-linux-kernel-4.4.55.git] / drivers / block / mtip32xx / mtip32xx.c
1 /*
2  * Driver for the Micron P320 SSD
3  *   Copyright (C) 2011 Micron Technology, Inc.
4  *
5  * Portions of this code were derived from works subjected to the
6  * following copyright:
7  *    Copyright (C) 2009 Integrated Device Technology, Inc.
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  */
20
21 #include <linux/pci.h>
22 #include <linux/interrupt.h>
23 #include <linux/ata.h>
24 #include <linux/delay.h>
25 #include <linux/hdreg.h>
26 #include <linux/uaccess.h>
27 #include <linux/random.h>
28 #include <linux/smp.h>
29 #include <linux/compat.h>
30 #include <linux/fs.h>
31 #include <linux/module.h>
32 #include <linux/genhd.h>
33 #include <linux/blkdev.h>
34 #include <linux/bio.h>
35 #include <linux/dma-mapping.h>
36 #include <linux/idr.h>
37 #include <linux/kthread.h>
38 #include <../drivers/ata/ahci.h>
39 #include <linux/export.h>
40 #include <linux/debugfs.h>
41 #include "mtip32xx.h"
42
43 #define HW_CMD_SLOT_SZ          (MTIP_MAX_COMMAND_SLOTS * 32)
44
45 /* DMA region containing RX Fis, Identify, RLE10, and SMART buffers */
46 #define AHCI_RX_FIS_SZ          0x100
47 #define AHCI_RX_FIS_OFFSET      0x0
48 #define AHCI_IDFY_SZ            ATA_SECT_SIZE
49 #define AHCI_IDFY_OFFSET        0x400
50 #define AHCI_SECTBUF_SZ         ATA_SECT_SIZE
51 #define AHCI_SECTBUF_OFFSET     0x800
52 #define AHCI_SMARTBUF_SZ        ATA_SECT_SIZE
53 #define AHCI_SMARTBUF_OFFSET    0xC00
54 /* 0x100 + 0x200 + 0x200 + 0x200 is smaller than 4k but we pad it out */
55 #define BLOCK_DMA_ALLOC_SZ      4096
56
57 /* DMA region containing command table (should be 8192 bytes) */
58 #define AHCI_CMD_SLOT_SZ        sizeof(struct mtip_cmd_hdr)
59 #define AHCI_CMD_TBL_SZ         (MTIP_MAX_COMMAND_SLOTS * AHCI_CMD_SLOT_SZ)
60 #define AHCI_CMD_TBL_OFFSET     0x0
61
62 /* DMA region per command (contains header and SGL) */
63 #define AHCI_CMD_TBL_HDR_SZ     0x80
64 #define AHCI_CMD_TBL_HDR_OFFSET 0x0
65 #define AHCI_CMD_TBL_SGL_SZ     (MTIP_MAX_SG * sizeof(struct mtip_cmd_sg))
66 #define AHCI_CMD_TBL_SGL_OFFSET AHCI_CMD_TBL_HDR_SZ
67 #define CMD_DMA_ALLOC_SZ        (AHCI_CMD_TBL_SGL_SZ + AHCI_CMD_TBL_HDR_SZ)
68
69
70 #define HOST_CAP_NZDMA          (1 << 19)
71 #define HOST_HSORG              0xFC
72 #define HSORG_DISABLE_SLOTGRP_INTR (1<<24)
73 #define HSORG_DISABLE_SLOTGRP_PXIS (1<<16)
74 #define HSORG_HWREV             0xFF00
75 #define HSORG_STYLE             0x8
76 #define HSORG_SLOTGROUPS        0x7
77
78 #define PORT_COMMAND_ISSUE      0x38
79 #define PORT_SDBV               0x7C
80
81 #define PORT_OFFSET             0x100
82 #define PORT_MEM_SIZE           0x80
83
84 #define PORT_IRQ_ERR \
85         (PORT_IRQ_HBUS_ERR | PORT_IRQ_IF_ERR | PORT_IRQ_CONNECT | \
86          PORT_IRQ_PHYRDY | PORT_IRQ_UNK_FIS | PORT_IRQ_BAD_PMP | \
87          PORT_IRQ_TF_ERR | PORT_IRQ_HBUS_DATA_ERR | PORT_IRQ_IF_NONFATAL | \
88          PORT_IRQ_OVERFLOW)
89 #define PORT_IRQ_LEGACY \
90         (PORT_IRQ_PIOS_FIS | PORT_IRQ_D2H_REG_FIS)
91 #define PORT_IRQ_HANDLED \
92         (PORT_IRQ_SDB_FIS | PORT_IRQ_LEGACY | \
93          PORT_IRQ_TF_ERR | PORT_IRQ_IF_ERR | \
94          PORT_IRQ_CONNECT | PORT_IRQ_PHYRDY)
95 #define DEF_PORT_IRQ \
96         (PORT_IRQ_ERR | PORT_IRQ_LEGACY | PORT_IRQ_SDB_FIS)
97
98 /* product numbers */
99 #define MTIP_PRODUCT_UNKNOWN    0x00
100 #define MTIP_PRODUCT_ASICFPGA   0x11
101
102 /* Device instance number, incremented each time a device is probed. */
103 static int instance;
104
105 struct list_head online_list;
106 struct list_head removing_list;
107 spinlock_t dev_lock;
108
109 /*
110  * Global variable used to hold the major block device number
111  * allocated in mtip_init().
112  */
113 static int mtip_major;
114 static struct dentry *dfs_parent;
115 static struct dentry *dfs_device_status;
116
117 static u32 cpu_use[NR_CPUS];
118
119 static DEFINE_SPINLOCK(rssd_index_lock);
120 static DEFINE_IDA(rssd_index_ida);
121
122 static int mtip_block_initialize(struct driver_data *dd);
123
124 #ifdef CONFIG_COMPAT
125 struct mtip_compat_ide_task_request_s {
126         __u8            io_ports[8];
127         __u8            hob_ports[8];
128         ide_reg_valid_t out_flags;
129         ide_reg_valid_t in_flags;
130         int             data_phase;
131         int             req_cmd;
132         compat_ulong_t  out_size;
133         compat_ulong_t  in_size;
134 };
135 #endif
136
137 /*
138  * This function check_for_surprise_removal is called
139  * while card is removed from the system and it will
140  * read the vendor id from the configration space
141  *
142  * @pdev Pointer to the pci_dev structure.
143  *
144  * return value
145  *       true if device removed, else false
146  */
147 static bool mtip_check_surprise_removal(struct pci_dev *pdev)
148 {
149         u16 vendor_id = 0;
150         struct driver_data *dd = pci_get_drvdata(pdev);
151
152         if (dd->sr)
153                 return true;
154
155        /* Read the vendorID from the configuration space */
156         pci_read_config_word(pdev, 0x00, &vendor_id);
157         if (vendor_id == 0xFFFF) {
158                 dd->sr = true;
159                 if (dd->queue)
160                         set_bit(QUEUE_FLAG_DEAD, &dd->queue->queue_flags);
161                 else
162                         dev_warn(&dd->pdev->dev,
163                                 "%s: dd->queue is NULL\n", __func__);
164                 if (dd->port) {
165                         set_bit(MTIP_PF_SR_CLEANUP_BIT, &dd->port->flags);
166                         wake_up_interruptible(&dd->port->svc_wait);
167                 } else
168                         dev_warn(&dd->pdev->dev,
169                                 "%s: dd->port is NULL\n", __func__);
170                 return true; /* device removed */
171         }
172
173         return false; /* device present */
174 }
175
176 /*
177  * Obtain an empty command slot.
178  *
179  * This function needs to be reentrant since it could be called
180  * at the same time on multiple CPUs. The allocation of the
181  * command slot must be atomic.
182  *
183  * @port Pointer to the port data structure.
184  *
185  * return value
186  *      >= 0    Index of command slot obtained.
187  *      -1      No command slots available.
188  */
189 static int get_slot(struct mtip_port *port)
190 {
191         int slot, i;
192         unsigned int num_command_slots = port->dd->slot_groups * 32;
193
194         /*
195          * Try 10 times, because there is a small race here.
196          *  that's ok, because it's still cheaper than a lock.
197          *
198          * Race: Since this section is not protected by lock, same bit
199          * could be chosen by different process contexts running in
200          * different processor. So instead of costly lock, we are going
201          * with loop.
202          */
203         for (i = 0; i < 10; i++) {
204                 slot = find_next_zero_bit(port->allocated,
205                                          num_command_slots, 1);
206                 if ((slot < num_command_slots) &&
207                     (!test_and_set_bit(slot, port->allocated)))
208                         return slot;
209         }
210         dev_warn(&port->dd->pdev->dev, "Failed to get a tag.\n");
211
212         mtip_check_surprise_removal(port->dd->pdev);
213         return -1;
214 }
215
216 /*
217  * Release a command slot.
218  *
219  * @port Pointer to the port data structure.
220  * @tag  Tag of command to release
221  *
222  * return value
223  *      None
224  */
225 static inline void release_slot(struct mtip_port *port, int tag)
226 {
227         smp_mb__before_clear_bit();
228         clear_bit(tag, port->allocated);
229         smp_mb__after_clear_bit();
230 }
231
232 /*
233  * IO completion function.
234  *
235  * This completion function is called by the driver ISR when a
236  * command that was issued by the kernel completes. It first calls the
237  * asynchronous completion function which normally calls back into the block
238  * layer passing the asynchronous callback data, then unmaps the
239  * scatter list associated with the completed command, and finally
240  * clears the allocated bit associated with the completed command.
241  *
242  * @port   Pointer to the port data structure.
243  * @tag    Tag of the command.
244  * @data   Pointer to driver_data.
245  * @status Completion status.
246  *
247  * return value
248  *      None
249  */
250 static void mtip_async_complete(struct mtip_port *port,
251                                 int tag,
252                                 void *data,
253                                 int status)
254 {
255         struct mtip_cmd *command;
256         struct driver_data *dd = data;
257         int cb_status = status ? -EIO : 0;
258
259         if (unlikely(!dd) || unlikely(!port))
260                 return;
261
262         command = &port->commands[tag];
263
264         if (unlikely(status == PORT_IRQ_TF_ERR)) {
265                 dev_warn(&port->dd->pdev->dev,
266                         "Command tag %d failed due to TFE\n", tag);
267         }
268
269         /* Upper layer callback */
270         if (likely(command->async_callback))
271                 command->async_callback(command->async_data, cb_status);
272
273         command->async_callback = NULL;
274         command->comp_func = NULL;
275
276         /* Unmap the DMA scatter list entries */
277         dma_unmap_sg(&dd->pdev->dev,
278                 command->sg,
279                 command->scatter_ents,
280                 command->direction);
281
282         /* Clear the allocated and active bits for the command */
283         atomic_set(&port->commands[tag].active, 0);
284         release_slot(port, tag);
285
286         up(&port->cmd_slot);
287 }
288
289 /*
290  * This function is called for clean the pending command in the
291  * command slot during the surprise removal of device and return
292  * error to the upper layer.
293  *
294  * @dd Pointer to the DRIVER_DATA structure.
295  *
296  * return value
297  *      None
298  */
299 static void mtip_command_cleanup(struct driver_data *dd)
300 {
301         int tag = 0;
302         struct mtip_cmd *cmd;
303         struct mtip_port *port = dd->port;
304         unsigned int num_cmd_slots = dd->slot_groups * 32;
305
306         if (!test_bit(MTIP_DDF_INIT_DONE_BIT, &dd->dd_flag))
307                 return;
308
309         if (!port)
310                 return;
311
312         cmd = &port->commands[MTIP_TAG_INTERNAL];
313         if (atomic_read(&cmd->active))
314                 if (readl(port->cmd_issue[MTIP_TAG_INTERNAL]) &
315                                         (1 << MTIP_TAG_INTERNAL))
316                         if (cmd->comp_func)
317                                 cmd->comp_func(port, MTIP_TAG_INTERNAL,
318                                          cmd->comp_data, -ENODEV);
319
320         while (1) {
321                 tag = find_next_bit(port->allocated, num_cmd_slots, tag);
322                 if (tag >= num_cmd_slots)
323                         break;
324
325                 cmd = &port->commands[tag];
326                 if (atomic_read(&cmd->active))
327                         mtip_async_complete(port, tag, dd, -ENODEV);
328         }
329
330         set_bit(MTIP_DDF_CLEANUP_BIT, &dd->dd_flag);
331 }
332
333 /*
334  * Reset the HBA (without sleeping)
335  *
336  * @dd Pointer to the driver data structure.
337  *
338  * return value
339  *      0       The reset was successful.
340  *      -1      The HBA Reset bit did not clear.
341  */
342 static int mtip_hba_reset(struct driver_data *dd)
343 {
344         unsigned long timeout;
345
346         /* Set the reset bit */
347         writel(HOST_RESET, dd->mmio + HOST_CTL);
348
349         /* Flush */
350         readl(dd->mmio + HOST_CTL);
351
352         /* Spin for up to 2 seconds, waiting for reset acknowledgement */
353         timeout = jiffies + msecs_to_jiffies(2000);
354         do {
355                 mdelay(10);
356                 if (test_bit(MTIP_DDF_REMOVE_PENDING_BIT, &dd->dd_flag))
357                         return -1;
358
359         } while ((readl(dd->mmio + HOST_CTL) & HOST_RESET)
360                  && time_before(jiffies, timeout));
361
362         if (readl(dd->mmio + HOST_CTL) & HOST_RESET)
363                 return -1;
364
365         return 0;
366 }
367
368 /*
369  * Issue a command to the hardware.
370  *
371  * Set the appropriate bit in the s_active and Command Issue hardware
372  * registers, causing hardware command processing to begin.
373  *
374  * @port Pointer to the port structure.
375  * @tag  The tag of the command to be issued.
376  *
377  * return value
378  *      None
379  */
380 static inline void mtip_issue_ncq_command(struct mtip_port *port, int tag)
381 {
382         int group = tag >> 5;
383
384         atomic_set(&port->commands[tag].active, 1);
385
386         /* guard SACT and CI registers */
387         spin_lock(&port->cmd_issue_lock[group]);
388         writel((1 << MTIP_TAG_BIT(tag)),
389                         port->s_active[MTIP_TAG_INDEX(tag)]);
390         writel((1 << MTIP_TAG_BIT(tag)),
391                         port->cmd_issue[MTIP_TAG_INDEX(tag)]);
392         spin_unlock(&port->cmd_issue_lock[group]);
393
394         /* Set the command's timeout value.*/
395         port->commands[tag].comp_time = jiffies + msecs_to_jiffies(
396                                         MTIP_NCQ_COMMAND_TIMEOUT_MS);
397 }
398
399 /*
400  * Enable/disable the reception of FIS
401  *
402  * @port   Pointer to the port data structure
403  * @enable 1 to enable, 0 to disable
404  *
405  * return value
406  *      Previous state: 1 enabled, 0 disabled
407  */
408 static int mtip_enable_fis(struct mtip_port *port, int enable)
409 {
410         u32 tmp;
411
412         /* enable FIS reception */
413         tmp = readl(port->mmio + PORT_CMD);
414         if (enable)
415                 writel(tmp | PORT_CMD_FIS_RX, port->mmio + PORT_CMD);
416         else
417                 writel(tmp & ~PORT_CMD_FIS_RX, port->mmio + PORT_CMD);
418
419         /* Flush */
420         readl(port->mmio + PORT_CMD);
421
422         return (((tmp & PORT_CMD_FIS_RX) == PORT_CMD_FIS_RX));
423 }
424
425 /*
426  * Enable/disable the DMA engine
427  *
428  * @port   Pointer to the port data structure
429  * @enable 1 to enable, 0 to disable
430  *
431  * return value
432  *      Previous state: 1 enabled, 0 disabled.
433  */
434 static int mtip_enable_engine(struct mtip_port *port, int enable)
435 {
436         u32 tmp;
437
438         /* enable FIS reception */
439         tmp = readl(port->mmio + PORT_CMD);
440         if (enable)
441                 writel(tmp | PORT_CMD_START, port->mmio + PORT_CMD);
442         else
443                 writel(tmp & ~PORT_CMD_START, port->mmio + PORT_CMD);
444
445         readl(port->mmio + PORT_CMD);
446         return (((tmp & PORT_CMD_START) == PORT_CMD_START));
447 }
448
449 /*
450  * Enables the port DMA engine and FIS reception.
451  *
452  * return value
453  *      None
454  */
455 static inline void mtip_start_port(struct mtip_port *port)
456 {
457         /* Enable FIS reception */
458         mtip_enable_fis(port, 1);
459
460         /* Enable the DMA engine */
461         mtip_enable_engine(port, 1);
462 }
463
464 /*
465  * Deinitialize a port by disabling port interrupts, the DMA engine,
466  * and FIS reception.
467  *
468  * @port Pointer to the port structure
469  *
470  * return value
471  *      None
472  */
473 static inline void mtip_deinit_port(struct mtip_port *port)
474 {
475         /* Disable interrupts on this port */
476         writel(0, port->mmio + PORT_IRQ_MASK);
477
478         /* Disable the DMA engine */
479         mtip_enable_engine(port, 0);
480
481         /* Disable FIS reception */
482         mtip_enable_fis(port, 0);
483 }
484
485 /*
486  * Initialize a port.
487  *
488  * This function deinitializes the port by calling mtip_deinit_port() and
489  * then initializes it by setting the command header and RX FIS addresses,
490  * clearing the SError register and any pending port interrupts before
491  * re-enabling the default set of port interrupts.
492  *
493  * @port Pointer to the port structure.
494  *
495  * return value
496  *      None
497  */
498 static void mtip_init_port(struct mtip_port *port)
499 {
500         int i;
501         mtip_deinit_port(port);
502
503         /* Program the command list base and FIS base addresses */
504         if (readl(port->dd->mmio + HOST_CAP) & HOST_CAP_64) {
505                 writel((port->command_list_dma >> 16) >> 16,
506                          port->mmio + PORT_LST_ADDR_HI);
507                 writel((port->rxfis_dma >> 16) >> 16,
508                          port->mmio + PORT_FIS_ADDR_HI);
509         }
510
511         writel(port->command_list_dma & 0xFFFFFFFF,
512                         port->mmio + PORT_LST_ADDR);
513         writel(port->rxfis_dma & 0xFFFFFFFF, port->mmio + PORT_FIS_ADDR);
514
515         /* Clear SError */
516         writel(readl(port->mmio + PORT_SCR_ERR), port->mmio + PORT_SCR_ERR);
517
518         /* reset the completed registers.*/
519         for (i = 0; i < port->dd->slot_groups; i++)
520                 writel(0xFFFFFFFF, port->completed[i]);
521
522         /* Clear any pending interrupts for this port */
523         writel(readl(port->mmio + PORT_IRQ_STAT), port->mmio + PORT_IRQ_STAT);
524
525         /* Clear any pending interrupts on the HBA. */
526         writel(readl(port->dd->mmio + HOST_IRQ_STAT),
527                                         port->dd->mmio + HOST_IRQ_STAT);
528
529         /* Enable port interrupts */
530         writel(DEF_PORT_IRQ, port->mmio + PORT_IRQ_MASK);
531 }
532
533 /*
534  * Restart a port
535  *
536  * @port Pointer to the port data structure.
537  *
538  * return value
539  *      None
540  */
541 static void mtip_restart_port(struct mtip_port *port)
542 {
543         unsigned long timeout;
544
545         /* Disable the DMA engine */
546         mtip_enable_engine(port, 0);
547
548         /* Chip quirk: wait up to 500ms for PxCMD.CR == 0 */
549         timeout = jiffies + msecs_to_jiffies(500);
550         while ((readl(port->mmio + PORT_CMD) & PORT_CMD_LIST_ON)
551                  && time_before(jiffies, timeout))
552                 ;
553
554         if (test_bit(MTIP_DDF_REMOVE_PENDING_BIT, &port->dd->dd_flag))
555                 return;
556
557         /*
558          * Chip quirk: escalate to hba reset if
559          * PxCMD.CR not clear after 500 ms
560          */
561         if (readl(port->mmio + PORT_CMD) & PORT_CMD_LIST_ON) {
562                 dev_warn(&port->dd->pdev->dev,
563                         "PxCMD.CR not clear, escalating reset\n");
564
565                 if (mtip_hba_reset(port->dd))
566                         dev_err(&port->dd->pdev->dev,
567                                 "HBA reset escalation failed.\n");
568
569                 /* 30 ms delay before com reset to quiesce chip */
570                 mdelay(30);
571         }
572
573         dev_warn(&port->dd->pdev->dev, "Issuing COM reset\n");
574
575         /* Set PxSCTL.DET */
576         writel(readl(port->mmio + PORT_SCR_CTL) |
577                          1, port->mmio + PORT_SCR_CTL);
578         readl(port->mmio + PORT_SCR_CTL);
579
580         /* Wait 1 ms to quiesce chip function */
581         timeout = jiffies + msecs_to_jiffies(1);
582         while (time_before(jiffies, timeout))
583                 ;
584
585         if (test_bit(MTIP_DDF_REMOVE_PENDING_BIT, &port->dd->dd_flag))
586                 return;
587
588         /* Clear PxSCTL.DET */
589         writel(readl(port->mmio + PORT_SCR_CTL) & ~1,
590                          port->mmio + PORT_SCR_CTL);
591         readl(port->mmio + PORT_SCR_CTL);
592
593         /* Wait 500 ms for bit 0 of PORT_SCR_STS to be set */
594         timeout = jiffies + msecs_to_jiffies(500);
595         while (((readl(port->mmio + PORT_SCR_STAT) & 0x01) == 0)
596                          && time_before(jiffies, timeout))
597                 ;
598
599         if (test_bit(MTIP_DDF_REMOVE_PENDING_BIT, &port->dd->dd_flag))
600                 return;
601
602         if ((readl(port->mmio + PORT_SCR_STAT) & 0x01) == 0)
603                 dev_warn(&port->dd->pdev->dev,
604                         "COM reset failed\n");
605
606         mtip_init_port(port);
607         mtip_start_port(port);
608
609 }
610
611 static int mtip_device_reset(struct driver_data *dd)
612 {
613         int rv = 0;
614
615         if (mtip_check_surprise_removal(dd->pdev))
616                 return 0;
617
618         if (mtip_hba_reset(dd) < 0)
619                 rv = -EFAULT;
620
621         mdelay(1);
622         mtip_init_port(dd->port);
623         mtip_start_port(dd->port);
624
625         /* Enable interrupts on the HBA. */
626         writel(readl(dd->mmio + HOST_CTL) | HOST_IRQ_EN,
627                                         dd->mmio + HOST_CTL);
628         return rv;
629 }
630
631 /*
632  * Helper function for tag logging
633  */
634 static void print_tags(struct driver_data *dd,
635                         char *msg,
636                         unsigned long *tagbits,
637                         int cnt)
638 {
639         unsigned char tagmap[128];
640         int group, tagmap_len = 0;
641
642         memset(tagmap, 0, sizeof(tagmap));
643         for (group = SLOTBITS_IN_LONGS; group > 0; group--)
644                 tagmap_len = sprintf(tagmap + tagmap_len, "%016lX ",
645                                                 tagbits[group-1]);
646         dev_warn(&dd->pdev->dev,
647                         "%d command(s) %s: tagmap [%s]", cnt, msg, tagmap);
648 }
649
650 /*
651  * Called periodically to see if any read/write commands are
652  * taking too long to complete.
653  *
654  * @data Pointer to the PORT data structure.
655  *
656  * return value
657  *      None
658  */
659 static void mtip_timeout_function(unsigned long int data)
660 {
661         struct mtip_port *port = (struct mtip_port *) data;
662         struct host_to_dev_fis *fis;
663         struct mtip_cmd *command;
664         int tag, cmdto_cnt = 0;
665         unsigned int bit, group;
666         unsigned int num_command_slots;
667         unsigned long to, tagaccum[SLOTBITS_IN_LONGS];
668
669         if (unlikely(!port))
670                 return;
671
672         if (unlikely(port->dd->sr))
673                 return;
674
675         if (test_bit(MTIP_DDF_RESUME_BIT, &port->dd->dd_flag)) {
676                 mod_timer(&port->cmd_timer,
677                         jiffies + msecs_to_jiffies(30000));
678                 return;
679         }
680         /* clear the tag accumulator */
681         memset(tagaccum, 0, SLOTBITS_IN_LONGS * sizeof(long));
682         num_command_slots = port->dd->slot_groups * 32;
683
684         for (tag = 0; tag < num_command_slots; tag++) {
685                 /*
686                  * Skip internal command slot as it has
687                  * its own timeout mechanism
688                  */
689                 if (tag == MTIP_TAG_INTERNAL)
690                         continue;
691
692                 if (atomic_read(&port->commands[tag].active) &&
693                    (time_after(jiffies, port->commands[tag].comp_time))) {
694                         group = tag >> 5;
695                         bit = tag & 0x1F;
696
697                         command = &port->commands[tag];
698                         fis = (struct host_to_dev_fis *) command->command;
699
700                         set_bit(tag, tagaccum);
701                         cmdto_cnt++;
702                         if (cmdto_cnt == 1)
703                                 set_bit(MTIP_PF_EH_ACTIVE_BIT, &port->flags);
704
705                         /*
706                          * Clear the completed bit. This should prevent
707                          *  any interrupt handlers from trying to retire
708                          *  the command.
709                          */
710                         writel(1 << bit, port->completed[group]);
711
712                         /* Call the async completion callback. */
713                         if (likely(command->async_callback))
714                                 command->async_callback(command->async_data,
715                                                          -EIO);
716                         command->async_callback = NULL;
717                         command->comp_func = NULL;
718
719                         /* Unmap the DMA scatter list entries */
720                         dma_unmap_sg(&port->dd->pdev->dev,
721                                         command->sg,
722                                         command->scatter_ents,
723                                         command->direction);
724
725                         /*
726                          * Clear the allocated bit and active tag for the
727                          * command.
728                          */
729                         atomic_set(&port->commands[tag].active, 0);
730                         release_slot(port, tag);
731
732                         up(&port->cmd_slot);
733                 }
734         }
735
736         if (cmdto_cnt) {
737                 print_tags(port->dd, "timed out", tagaccum, cmdto_cnt);
738                 if (!test_bit(MTIP_PF_IC_ACTIVE_BIT, &port->flags)) {
739                         mtip_device_reset(port->dd);
740                         wake_up_interruptible(&port->svc_wait);
741                 }
742                 clear_bit(MTIP_PF_EH_ACTIVE_BIT, &port->flags);
743         }
744
745         if (port->ic_pause_timer) {
746                 to  = port->ic_pause_timer + msecs_to_jiffies(1000);
747                 if (time_after(jiffies, to)) {
748                         if (!test_bit(MTIP_PF_IC_ACTIVE_BIT, &port->flags)) {
749                                 port->ic_pause_timer = 0;
750                                 clear_bit(MTIP_PF_SE_ACTIVE_BIT, &port->flags);
751                                 clear_bit(MTIP_PF_DM_ACTIVE_BIT, &port->flags);
752                                 clear_bit(MTIP_PF_IC_ACTIVE_BIT, &port->flags);
753                                 wake_up_interruptible(&port->svc_wait);
754                         }
755
756
757                 }
758         }
759
760         /* Restart the timer */
761         mod_timer(&port->cmd_timer,
762                 jiffies + msecs_to_jiffies(MTIP_TIMEOUT_CHECK_PERIOD));
763 }
764
765 /*
766  * Internal command completion callback function.
767  *
768  * This function is normally called by the driver ISR when an internal
769  * command completed. This function signals the command completion by
770  * calling complete().
771  *
772  * @port   Pointer to the port data structure.
773  * @tag    Tag of the command that has completed.
774  * @data   Pointer to a completion structure.
775  * @status Completion status.
776  *
777  * return value
778  *      None
779  */
780 static void mtip_completion(struct mtip_port *port,
781                             int tag,
782                             void *data,
783                             int status)
784 {
785         struct mtip_cmd *command = &port->commands[tag];
786         struct completion *waiting = data;
787         if (unlikely(status == PORT_IRQ_TF_ERR))
788                 dev_warn(&port->dd->pdev->dev,
789                         "Internal command %d completed with TFE\n", tag);
790
791         command->async_callback = NULL;
792         command->comp_func = NULL;
793
794         complete(waiting);
795 }
796
797 static void mtip_null_completion(struct mtip_port *port,
798                             int tag,
799                             void *data,
800                             int status)
801 {
802         return;
803 }
804
805 static int mtip_read_log_page(struct mtip_port *port, u8 page, u16 *buffer,
806                                 dma_addr_t buffer_dma, unsigned int sectors);
807 static int mtip_get_smart_attr(struct mtip_port *port, unsigned int id,
808                                                 struct smart_attr *attrib);
809 /*
810  * Handle an error.
811  *
812  * @dd Pointer to the DRIVER_DATA structure.
813  *
814  * return value
815  *      None
816  */
817 static void mtip_handle_tfe(struct driver_data *dd)
818 {
819         int group, tag, bit, reissue, rv;
820         struct mtip_port *port;
821         struct mtip_cmd  *cmd;
822         u32 completed;
823         struct host_to_dev_fis *fis;
824         unsigned long tagaccum[SLOTBITS_IN_LONGS];
825         unsigned int cmd_cnt = 0;
826         unsigned char *buf;
827         char *fail_reason = NULL;
828         int fail_all_ncq_write = 0, fail_all_ncq_cmds = 0;
829
830         dev_warn(&dd->pdev->dev, "Taskfile error\n");
831
832         port = dd->port;
833
834         /* Stop the timer to prevent command timeouts. */
835         del_timer(&port->cmd_timer);
836         set_bit(MTIP_PF_EH_ACTIVE_BIT, &port->flags);
837
838         if (test_bit(MTIP_PF_IC_ACTIVE_BIT, &port->flags) &&
839                         test_bit(MTIP_TAG_INTERNAL, port->allocated)) {
840                 cmd = &port->commands[MTIP_TAG_INTERNAL];
841                 dbg_printk(MTIP_DRV_NAME " TFE for the internal command\n");
842
843                 atomic_inc(&cmd->active); /* active > 1 indicates error */
844                 if (cmd->comp_data && cmd->comp_func) {
845                         cmd->comp_func(port, MTIP_TAG_INTERNAL,
846                                         cmd->comp_data, PORT_IRQ_TF_ERR);
847                 }
848                 goto handle_tfe_exit;
849         }
850
851         /* clear the tag accumulator */
852         memset(tagaccum, 0, SLOTBITS_IN_LONGS * sizeof(long));
853
854         /* Loop through all the groups */
855         for (group = 0; group < dd->slot_groups; group++) {
856                 completed = readl(port->completed[group]);
857
858                 /* clear completed status register in the hardware.*/
859                 writel(completed, port->completed[group]);
860
861                 /* Process successfully completed commands */
862                 for (bit = 0; bit < 32 && completed; bit++) {
863                         if (!(completed & (1<<bit)))
864                                 continue;
865                         tag = (group << 5) + bit;
866
867                         /* Skip the internal command slot */
868                         if (tag == MTIP_TAG_INTERNAL)
869                                 continue;
870
871                         cmd = &port->commands[tag];
872                         if (likely(cmd->comp_func)) {
873                                 set_bit(tag, tagaccum);
874                                 cmd_cnt++;
875                                 atomic_set(&cmd->active, 0);
876                                 cmd->comp_func(port,
877                                          tag,
878                                          cmd->comp_data,
879                                          0);
880                         } else {
881                                 dev_err(&port->dd->pdev->dev,
882                                         "Missing completion func for tag %d",
883                                         tag);
884                                 if (mtip_check_surprise_removal(dd->pdev)) {
885                                         /* don't proceed further */
886                                         return;
887                                 }
888                         }
889                 }
890         }
891
892         print_tags(dd, "completed (TFE)", tagaccum, cmd_cnt);
893
894         /* Restart the port */
895         mdelay(20);
896         mtip_restart_port(port);
897
898         /* Trying to determine the cause of the error */
899         rv = mtip_read_log_page(dd->port, ATA_LOG_SATA_NCQ,
900                                 dd->port->log_buf,
901                                 dd->port->log_buf_dma, 1);
902         if (rv) {
903                 dev_warn(&dd->pdev->dev,
904                         "Error in READ LOG EXT (10h) command\n");
905                 /* non-critical error, don't fail the load */
906         } else {
907                 buf = (unsigned char *)dd->port->log_buf;
908                 if (buf[259] & 0x1) {
909                         dev_info(&dd->pdev->dev,
910                                 "Write protect bit is set.\n");
911                         set_bit(MTIP_DDF_WRITE_PROTECT_BIT, &dd->dd_flag);
912                         fail_all_ncq_write = 1;
913                         fail_reason = "write protect";
914                 }
915                 if (buf[288] == 0xF7) {
916                         dev_info(&dd->pdev->dev,
917                                 "Exceeded Tmax, drive in thermal shutdown.\n");
918                         set_bit(MTIP_DDF_OVER_TEMP_BIT, &dd->dd_flag);
919                         fail_all_ncq_cmds = 1;
920                         fail_reason = "thermal shutdown";
921                 }
922                 if (buf[288] == 0xBF) {
923                         dev_info(&dd->pdev->dev,
924                                 "Drive indicates rebuild has failed.\n");
925                         fail_all_ncq_cmds = 1;
926                         fail_reason = "rebuild failed";
927                 }
928         }
929
930         /* clear the tag accumulator */
931         memset(tagaccum, 0, SLOTBITS_IN_LONGS * sizeof(long));
932
933         /* Loop through all the groups */
934         for (group = 0; group < dd->slot_groups; group++) {
935                 for (bit = 0; bit < 32; bit++) {
936                         reissue = 1;
937                         tag = (group << 5) + bit;
938                         cmd = &port->commands[tag];
939
940                         /* If the active bit is set re-issue the command */
941                         if (atomic_read(&cmd->active) == 0)
942                                 continue;
943
944                         fis = (struct host_to_dev_fis *)cmd->command;
945
946                         /* Should re-issue? */
947                         if (tag == MTIP_TAG_INTERNAL ||
948                             fis->command == ATA_CMD_SET_FEATURES)
949                                 reissue = 0;
950                         else {
951                                 if (fail_all_ncq_cmds ||
952                                         (fail_all_ncq_write &&
953                                         fis->command == ATA_CMD_FPDMA_WRITE)) {
954                                         dev_warn(&dd->pdev->dev,
955                                         "  Fail: %s w/tag %d [%s].\n",
956                                         fis->command == ATA_CMD_FPDMA_WRITE ?
957                                                 "write" : "read",
958                                         tag,
959                                         fail_reason != NULL ?
960                                                 fail_reason : "unknown");
961                                         atomic_set(&cmd->active, 0);
962                                         if (cmd->comp_func) {
963                                                 cmd->comp_func(port, tag,
964                                                         cmd->comp_data,
965                                                         -ENODATA);
966                                         }
967                                         continue;
968                                 }
969                         }
970
971                         /*
972                          * First check if this command has
973                          *  exceeded its retries.
974                          */
975                         if (reissue && (cmd->retries-- > 0)) {
976
977                                 set_bit(tag, tagaccum);
978
979                                 /* Re-issue the command. */
980                                 mtip_issue_ncq_command(port, tag);
981
982                                 continue;
983                         }
984
985                         /* Retire a command that will not be reissued */
986                         dev_warn(&port->dd->pdev->dev,
987                                 "retiring tag %d\n", tag);
988                         atomic_set(&cmd->active, 0);
989
990                         if (cmd->comp_func)
991                                 cmd->comp_func(
992                                         port,
993                                         tag,
994                                         cmd->comp_data,
995                                         PORT_IRQ_TF_ERR);
996                         else
997                                 dev_warn(&port->dd->pdev->dev,
998                                         "Bad completion for tag %d\n",
999                                         tag);
1000                 }
1001         }
1002         print_tags(dd, "reissued (TFE)", tagaccum, cmd_cnt);
1003
1004 handle_tfe_exit:
1005         /* clear eh_active */
1006         clear_bit(MTIP_PF_EH_ACTIVE_BIT, &port->flags);
1007         wake_up_interruptible(&port->svc_wait);
1008
1009         mod_timer(&port->cmd_timer,
1010                  jiffies + msecs_to_jiffies(MTIP_TIMEOUT_CHECK_PERIOD));
1011 }
1012
1013 /*
1014  * Handle a set device bits interrupt
1015  */
1016 static inline void mtip_workq_sdbfx(struct mtip_port *port, int group,
1017                                                         u32 completed)
1018 {
1019         struct driver_data *dd = port->dd;
1020         int tag, bit;
1021         struct mtip_cmd *command;
1022
1023         if (!completed) {
1024                 WARN_ON_ONCE(!completed);
1025                 return;
1026         }
1027         /* clear completed status register in the hardware.*/
1028         writel(completed, port->completed[group]);
1029
1030         /* Process completed commands. */
1031         for (bit = 0; (bit < 32) && completed; bit++) {
1032                 if (completed & 0x01) {
1033                         tag = (group << 5) | bit;
1034
1035                         /* skip internal command slot. */
1036                         if (unlikely(tag == MTIP_TAG_INTERNAL))
1037                                 continue;
1038
1039                         command = &port->commands[tag];
1040                         /* make internal callback */
1041                         if (likely(command->comp_func)) {
1042                                 command->comp_func(
1043                                         port,
1044                                         tag,
1045                                         command->comp_data,
1046                                         0);
1047                         } else {
1048                                 dev_dbg(&dd->pdev->dev,
1049                                         "Null completion for tag %d",
1050                                         tag);
1051
1052                                 if (mtip_check_surprise_removal(
1053                                         dd->pdev)) {
1054                                         return;
1055                                 }
1056                         }
1057                 }
1058                 completed >>= 1;
1059         }
1060
1061         /* If last, re-enable interrupts */
1062         if (atomic_dec_return(&dd->irq_workers_active) == 0)
1063                 writel(0xffffffff, dd->mmio + HOST_IRQ_STAT);
1064 }
1065
1066 /*
1067  * Process legacy pio and d2h interrupts
1068  */
1069 static inline void mtip_process_legacy(struct driver_data *dd, u32 port_stat)
1070 {
1071         struct mtip_port *port = dd->port;
1072         struct mtip_cmd *cmd = &port->commands[MTIP_TAG_INTERNAL];
1073
1074         if (test_bit(MTIP_PF_IC_ACTIVE_BIT, &port->flags) &&
1075             (cmd != NULL) && !(readl(port->cmd_issue[MTIP_TAG_INTERNAL])
1076                 & (1 << MTIP_TAG_INTERNAL))) {
1077                 if (cmd->comp_func) {
1078                         cmd->comp_func(port,
1079                                 MTIP_TAG_INTERNAL,
1080                                 cmd->comp_data,
1081                                 0);
1082                         return;
1083                 }
1084         }
1085
1086         return;
1087 }
1088
1089 /*
1090  * Demux and handle errors
1091  */
1092 static inline void mtip_process_errors(struct driver_data *dd, u32 port_stat)
1093 {
1094         if (likely(port_stat & (PORT_IRQ_TF_ERR | PORT_IRQ_IF_ERR)))
1095                 mtip_handle_tfe(dd);
1096
1097         if (unlikely(port_stat & PORT_IRQ_CONNECT)) {
1098                 dev_warn(&dd->pdev->dev,
1099                         "Clearing PxSERR.DIAG.x\n");
1100                 writel((1 << 26), dd->port->mmio + PORT_SCR_ERR);
1101         }
1102
1103         if (unlikely(port_stat & PORT_IRQ_PHYRDY)) {
1104                 dev_warn(&dd->pdev->dev,
1105                         "Clearing PxSERR.DIAG.n\n");
1106                 writel((1 << 16), dd->port->mmio + PORT_SCR_ERR);
1107         }
1108
1109         if (unlikely(port_stat & ~PORT_IRQ_HANDLED)) {
1110                 dev_warn(&dd->pdev->dev,
1111                         "Port stat errors %x unhandled\n",
1112                         (port_stat & ~PORT_IRQ_HANDLED));
1113         }
1114 }
1115
1116 static inline irqreturn_t mtip_handle_irq(struct driver_data *data)
1117 {
1118         struct driver_data *dd = (struct driver_data *) data;
1119         struct mtip_port *port = dd->port;
1120         u32 hba_stat, port_stat;
1121         int rv = IRQ_NONE;
1122         int do_irq_enable = 1, i, workers;
1123         struct mtip_work *twork;
1124
1125         hba_stat = readl(dd->mmio + HOST_IRQ_STAT);
1126         if (hba_stat) {
1127                 rv = IRQ_HANDLED;
1128
1129                 /* Acknowledge the interrupt status on the port.*/
1130                 port_stat = readl(port->mmio + PORT_IRQ_STAT);
1131                 writel(port_stat, port->mmio + PORT_IRQ_STAT);
1132
1133                 /* Demux port status */
1134                 if (likely(port_stat & PORT_IRQ_SDB_FIS)) {
1135                         do_irq_enable = 0;
1136                         WARN_ON_ONCE(atomic_read(&dd->irq_workers_active) != 0);
1137
1138                         /* Start at 1: group zero is always local? */
1139                         for (i = 0, workers = 0; i < MTIP_MAX_SLOT_GROUPS;
1140                                                                         i++) {
1141                                 twork = &dd->work[i];
1142                                 twork->completed = readl(port->completed[i]);
1143                                 if (twork->completed)
1144                                         workers++;
1145                         }
1146
1147                         atomic_set(&dd->irq_workers_active, workers);
1148                         if (workers) {
1149                                 for (i = 1; i < MTIP_MAX_SLOT_GROUPS; i++) {
1150                                         twork = &dd->work[i];
1151                                         if (twork->completed)
1152                                                 queue_work_on(
1153                                                         twork->cpu_binding,
1154                                                         dd->isr_workq,
1155                                                         &twork->work);
1156                                 }
1157
1158                                 if (likely(dd->work[0].completed))
1159                                         mtip_workq_sdbfx(port, 0,
1160                                                         dd->work[0].completed);
1161
1162                         } else {
1163                                 /*
1164                                  * Chip quirk: SDB interrupt but nothing
1165                                  * to complete
1166                                  */
1167                                 do_irq_enable = 1;
1168                         }
1169                 }
1170
1171                 if (unlikely(port_stat & PORT_IRQ_ERR)) {
1172                         if (unlikely(mtip_check_surprise_removal(dd->pdev))) {
1173                                 /* don't proceed further */
1174                                 return IRQ_HANDLED;
1175                         }
1176                         if (test_bit(MTIP_DDF_REMOVE_PENDING_BIT,
1177                                                         &dd->dd_flag))
1178                                 return rv;
1179
1180                         mtip_process_errors(dd, port_stat & PORT_IRQ_ERR);
1181                 }
1182
1183                 if (unlikely(port_stat & PORT_IRQ_LEGACY))
1184                         mtip_process_legacy(dd, port_stat & PORT_IRQ_LEGACY);
1185         }
1186
1187         /* acknowledge interrupt */
1188         if (unlikely(do_irq_enable))
1189                 writel(hba_stat, dd->mmio + HOST_IRQ_STAT);
1190
1191         return rv;
1192 }
1193
1194 /*
1195  * HBA interrupt subroutine.
1196  *
1197  * @irq         IRQ number.
1198  * @instance    Pointer to the driver data structure.
1199  *
1200  * return value
1201  *      IRQ_HANDLED     A HBA interrupt was pending and handled.
1202  *      IRQ_NONE        This interrupt was not for the HBA.
1203  */
1204 static irqreturn_t mtip_irq_handler(int irq, void *instance)
1205 {
1206         struct driver_data *dd = instance;
1207
1208         return mtip_handle_irq(dd);
1209 }
1210
1211 static void mtip_issue_non_ncq_command(struct mtip_port *port, int tag)
1212 {
1213         atomic_set(&port->commands[tag].active, 1);
1214         writel(1 << MTIP_TAG_BIT(tag),
1215                 port->cmd_issue[MTIP_TAG_INDEX(tag)]);
1216 }
1217
1218 static bool mtip_pause_ncq(struct mtip_port *port,
1219                                 struct host_to_dev_fis *fis)
1220 {
1221         struct host_to_dev_fis *reply;
1222         unsigned long task_file_data;
1223
1224         reply = port->rxfis + RX_FIS_D2H_REG;
1225         task_file_data = readl(port->mmio+PORT_TFDATA);
1226
1227         if (fis->command == ATA_CMD_SEC_ERASE_UNIT)
1228                 clear_bit(MTIP_DDF_SEC_LOCK_BIT, &port->dd->dd_flag);
1229
1230         if ((task_file_data & 1))
1231                 return false;
1232
1233         if (fis->command == ATA_CMD_SEC_ERASE_PREP) {
1234                 set_bit(MTIP_PF_SE_ACTIVE_BIT, &port->flags);
1235                 set_bit(MTIP_DDF_SEC_LOCK_BIT, &port->dd->dd_flag);
1236                 port->ic_pause_timer = jiffies;
1237                 return true;
1238         } else if ((fis->command == ATA_CMD_DOWNLOAD_MICRO) &&
1239                                         (fis->features == 0x03)) {
1240                 set_bit(MTIP_PF_DM_ACTIVE_BIT, &port->flags);
1241                 port->ic_pause_timer = jiffies;
1242                 return true;
1243         } else if ((fis->command == ATA_CMD_SEC_ERASE_UNIT) ||
1244                 ((fis->command == 0xFC) &&
1245                         (fis->features == 0x27 || fis->features == 0x72 ||
1246                          fis->features == 0x62 || fis->features == 0x26))) {
1247                 /* Com reset after secure erase or lowlevel format */
1248                 mtip_restart_port(port);
1249                 return false;
1250         }
1251
1252         return false;
1253 }
1254
1255 /*
1256  * Wait for port to quiesce
1257  *
1258  * @port    Pointer to port data structure
1259  * @timeout Max duration to wait (ms)
1260  *
1261  * return value
1262  *      0       Success
1263  *      -EBUSY  Commands still active
1264  */
1265 static int mtip_quiesce_io(struct mtip_port *port, unsigned long timeout)
1266 {
1267         unsigned long to;
1268         unsigned int n;
1269         unsigned int active = 1;
1270
1271         to = jiffies + msecs_to_jiffies(timeout);
1272         do {
1273                 if (test_bit(MTIP_PF_SVC_THD_ACTIVE_BIT, &port->flags) &&
1274                         test_bit(MTIP_PF_ISSUE_CMDS_BIT, &port->flags)) {
1275                         msleep(20);
1276                         continue; /* svc thd is actively issuing commands */
1277                 }
1278                 if (test_bit(MTIP_DDF_REMOVE_PENDING_BIT, &port->dd->dd_flag))
1279                         return -EFAULT;
1280                 /*
1281                  * Ignore s_active bit 0 of array element 0.
1282                  * This bit will always be set
1283                  */
1284                 active = readl(port->s_active[0]) & 0xFFFFFFFE;
1285                 for (n = 1; n < port->dd->slot_groups; n++)
1286                         active |= readl(port->s_active[n]);
1287
1288                 if (!active)
1289                         break;
1290
1291                 msleep(20);
1292         } while (time_before(jiffies, to));
1293
1294         return active ? -EBUSY : 0;
1295 }
1296
1297 /*
1298  * Execute an internal command and wait for the completion.
1299  *
1300  * @port    Pointer to the port data structure.
1301  * @fis     Pointer to the FIS that describes the command.
1302  * @fis_len  Length in WORDS of the FIS.
1303  * @buffer  DMA accessible for command data.
1304  * @buf_len  Length, in bytes, of the data buffer.
1305  * @opts    Command header options, excluding the FIS length
1306  *             and the number of PRD entries.
1307  * @timeout Time in ms to wait for the command to complete.
1308  *
1309  * return value
1310  *      0        Command completed successfully.
1311  *      -EFAULT  The buffer address is not correctly aligned.
1312  *      -EBUSY   Internal command or other IO in progress.
1313  *      -EAGAIN  Time out waiting for command to complete.
1314  */
1315 static int mtip_exec_internal_command(struct mtip_port *port,
1316                                         struct host_to_dev_fis *fis,
1317                                         int fis_len,
1318                                         dma_addr_t buffer,
1319                                         int buf_len,
1320                                         u32 opts,
1321                                         gfp_t atomic,
1322                                         unsigned long timeout)
1323 {
1324         struct mtip_cmd_sg *command_sg;
1325         DECLARE_COMPLETION_ONSTACK(wait);
1326         int rv = 0, ready2go = 1;
1327         struct mtip_cmd *int_cmd = &port->commands[MTIP_TAG_INTERNAL];
1328         unsigned long to;
1329         struct driver_data *dd = port->dd;
1330
1331         /* Make sure the buffer is 8 byte aligned. This is asic specific. */
1332         if (buffer & 0x00000007) {
1333                 dev_err(&dd->pdev->dev, "SG buffer is not 8 byte aligned\n");
1334                 return -EFAULT;
1335         }
1336
1337         to = jiffies + msecs_to_jiffies(timeout);
1338         do {
1339                 ready2go = !test_and_set_bit(MTIP_TAG_INTERNAL,
1340                                                 port->allocated);
1341                 if (ready2go)
1342                         break;
1343                 mdelay(100);
1344         } while (time_before(jiffies, to));
1345         if (!ready2go) {
1346                 dev_warn(&dd->pdev->dev,
1347                         "Internal cmd active. new cmd [%02X]\n", fis->command);
1348                 return -EBUSY;
1349         }
1350         set_bit(MTIP_PF_IC_ACTIVE_BIT, &port->flags);
1351         port->ic_pause_timer = 0;
1352
1353         clear_bit(MTIP_PF_SE_ACTIVE_BIT, &port->flags);
1354         clear_bit(MTIP_PF_DM_ACTIVE_BIT, &port->flags);
1355
1356         if (atomic == GFP_KERNEL) {
1357                 if (fis->command != ATA_CMD_STANDBYNOW1) {
1358                         /* wait for io to complete if non atomic */
1359                         if (mtip_quiesce_io(port, 5000) < 0) {
1360                                 dev_warn(&dd->pdev->dev,
1361                                         "Failed to quiesce IO\n");
1362                                 release_slot(port, MTIP_TAG_INTERNAL);
1363                                 clear_bit(MTIP_PF_IC_ACTIVE_BIT, &port->flags);
1364                                 wake_up_interruptible(&port->svc_wait);
1365                                 return -EBUSY;
1366                         }
1367                 }
1368
1369                 /* Set the completion function and data for the command. */
1370                 int_cmd->comp_data = &wait;
1371                 int_cmd->comp_func = mtip_completion;
1372
1373         } else {
1374                 /* Clear completion - we're going to poll */
1375                 int_cmd->comp_data = NULL;
1376                 int_cmd->comp_func = mtip_null_completion;
1377         }
1378
1379         /* Copy the command to the command table */
1380         memcpy(int_cmd->command, fis, fis_len*4);
1381
1382         /* Populate the SG list */
1383         int_cmd->command_header->opts =
1384                  __force_bit2int cpu_to_le32(opts | fis_len);
1385         if (buf_len) {
1386                 command_sg = int_cmd->command + AHCI_CMD_TBL_HDR_SZ;
1387
1388                 command_sg->info =
1389                         __force_bit2int cpu_to_le32((buf_len-1) & 0x3FFFFF);
1390                 command_sg->dba =
1391                         __force_bit2int cpu_to_le32(buffer & 0xFFFFFFFF);
1392                 command_sg->dba_upper =
1393                         __force_bit2int cpu_to_le32((buffer >> 16) >> 16);
1394
1395                 int_cmd->command_header->opts |=
1396                         __force_bit2int cpu_to_le32((1 << 16));
1397         }
1398
1399         /* Populate the command header */
1400         int_cmd->command_header->byte_count = 0;
1401
1402         /* Issue the command to the hardware */
1403         mtip_issue_non_ncq_command(port, MTIP_TAG_INTERNAL);
1404
1405         if (atomic == GFP_KERNEL) {
1406                 /* Wait for the command to complete or timeout. */
1407                 if (wait_for_completion_interruptible_timeout(
1408                                 &wait,
1409                                 msecs_to_jiffies(timeout)) <= 0) {
1410                         if (rv == -ERESTARTSYS) { /* interrupted */
1411                                 dev_err(&dd->pdev->dev,
1412                                         "Internal command [%02X] was interrupted after %lu ms\n",
1413                                         fis->command, timeout);
1414                                 rv = -EINTR;
1415                                 goto exec_ic_exit;
1416                         } else if (rv == 0) /* timeout */
1417                                 dev_err(&dd->pdev->dev,
1418                                         "Internal command did not complete [%02X] within timeout of  %lu ms\n",
1419                                         fis->command, timeout);
1420                         else
1421                                 dev_err(&dd->pdev->dev,
1422                                         "Internal command [%02X] wait returned code [%d] after %lu ms - unhandled\n",
1423                                         fis->command, rv, timeout);
1424
1425                         if (mtip_check_surprise_removal(dd->pdev) ||
1426                                 test_bit(MTIP_DDF_REMOVE_PENDING_BIT,
1427                                                 &dd->dd_flag)) {
1428                                 dev_err(&dd->pdev->dev,
1429                                         "Internal command [%02X] wait returned due to SR\n",
1430                                         fis->command);
1431                                 rv = -ENXIO;
1432                                 goto exec_ic_exit;
1433                         }
1434                         mtip_device_reset(dd); /* recover from timeout issue */
1435                         rv = -EAGAIN;
1436                         goto exec_ic_exit;
1437                 }
1438         } else {
1439                 u32 hba_stat, port_stat;
1440
1441                 /* Spin for <timeout> checking if command still outstanding */
1442                 timeout = jiffies + msecs_to_jiffies(timeout);
1443                 while ((readl(port->cmd_issue[MTIP_TAG_INTERNAL])
1444                                 & (1 << MTIP_TAG_INTERNAL))
1445                                 && time_before(jiffies, timeout)) {
1446                         if (mtip_check_surprise_removal(dd->pdev)) {
1447                                 rv = -ENXIO;
1448                                 goto exec_ic_exit;
1449                         }
1450                         if ((fis->command != ATA_CMD_STANDBYNOW1) &&
1451                                 test_bit(MTIP_DDF_REMOVE_PENDING_BIT,
1452                                                 &dd->dd_flag)) {
1453                                 rv = -ENXIO;
1454                                 goto exec_ic_exit;
1455                         }
1456                         port_stat = readl(port->mmio + PORT_IRQ_STAT);
1457                         if (!port_stat)
1458                                 continue;
1459
1460                         if (port_stat & PORT_IRQ_ERR) {
1461                                 dev_err(&dd->pdev->dev,
1462                                         "Internal command [%02X] failed\n",
1463                                         fis->command);
1464                                 mtip_device_reset(dd);
1465                                 rv = -EIO;
1466                                 goto exec_ic_exit;
1467                         } else {
1468                                 writel(port_stat, port->mmio + PORT_IRQ_STAT);
1469                                 hba_stat = readl(dd->mmio + HOST_IRQ_STAT);
1470                                 if (hba_stat)
1471                                         writel(hba_stat,
1472                                                 dd->mmio + HOST_IRQ_STAT);
1473                         }
1474                         break;
1475                 }
1476         }
1477
1478         if (readl(port->cmd_issue[MTIP_TAG_INTERNAL])
1479                         & (1 << MTIP_TAG_INTERNAL)) {
1480                 rv = -ENXIO;
1481                 if (!test_bit(MTIP_DDF_REMOVE_PENDING_BIT, &dd->dd_flag)) {
1482                         mtip_device_reset(dd);
1483                         rv = -EAGAIN;
1484                 }
1485         }
1486 exec_ic_exit:
1487         /* Clear the allocated and active bits for the internal command. */
1488         atomic_set(&int_cmd->active, 0);
1489         release_slot(port, MTIP_TAG_INTERNAL);
1490         if (rv >= 0 && mtip_pause_ncq(port, fis)) {
1491                 /* NCQ paused */
1492                 return rv;
1493         }
1494         clear_bit(MTIP_PF_IC_ACTIVE_BIT, &port->flags);
1495         wake_up_interruptible(&port->svc_wait);
1496
1497         return rv;
1498 }
1499
1500 /*
1501  * Byte-swap ATA ID strings.
1502  *
1503  * ATA identify data contains strings in byte-swapped 16-bit words.
1504  * They must be swapped (on all architectures) to be usable as C strings.
1505  * This function swaps bytes in-place.
1506  *
1507  * @buf The buffer location of the string
1508  * @len The number of bytes to swap
1509  *
1510  * return value
1511  *      None
1512  */
1513 static inline void ata_swap_string(u16 *buf, unsigned int len)
1514 {
1515         int i;
1516         for (i = 0; i < (len/2); i++)
1517                 be16_to_cpus(&buf[i]);
1518 }
1519
1520 /*
1521  * Request the device identity information.
1522  *
1523  * If a user space buffer is not specified, i.e. is NULL, the
1524  * identify information is still read from the drive and placed
1525  * into the identify data buffer (@e port->identify) in the
1526  * port data structure.
1527  * When the identify buffer contains valid identify information @e
1528  * port->identify_valid is non-zero.
1529  *
1530  * @port         Pointer to the port structure.
1531  * @user_buffer  A user space buffer where the identify data should be
1532  *                    copied.
1533  *
1534  * return value
1535  *      0       Command completed successfully.
1536  *      -EFAULT An error occurred while coping data to the user buffer.
1537  *      -1      Command failed.
1538  */
1539 static int mtip_get_identify(struct mtip_port *port, void __user *user_buffer)
1540 {
1541         int rv = 0;
1542         struct host_to_dev_fis fis;
1543
1544         if (test_bit(MTIP_DDF_REMOVE_PENDING_BIT, &port->dd->dd_flag))
1545                 return -EFAULT;
1546
1547         /* Build the FIS. */
1548         memset(&fis, 0, sizeof(struct host_to_dev_fis));
1549         fis.type        = 0x27;
1550         fis.opts        = 1 << 7;
1551         fis.command     = ATA_CMD_ID_ATA;
1552
1553         /* Set the identify information as invalid. */
1554         port->identify_valid = 0;
1555
1556         /* Clear the identify information. */
1557         memset(port->identify, 0, sizeof(u16) * ATA_ID_WORDS);
1558
1559         /* Execute the command. */
1560         if (mtip_exec_internal_command(port,
1561                                 &fis,
1562                                 5,
1563                                 port->identify_dma,
1564                                 sizeof(u16) * ATA_ID_WORDS,
1565                                 0,
1566                                 GFP_KERNEL,
1567                                 MTIP_INTERNAL_COMMAND_TIMEOUT_MS)
1568                                 < 0) {
1569                 rv = -1;
1570                 goto out;
1571         }
1572
1573         /*
1574          * Perform any necessary byte-swapping.  Yes, the kernel does in fact
1575          * perform field-sensitive swapping on the string fields.
1576          * See the kernel use of ata_id_string() for proof of this.
1577          */
1578 #ifdef __LITTLE_ENDIAN
1579         ata_swap_string(port->identify + 27, 40);  /* model string*/
1580         ata_swap_string(port->identify + 23, 8);   /* firmware string*/
1581         ata_swap_string(port->identify + 10, 20);  /* serial# string*/
1582 #else
1583         {
1584                 int i;
1585                 for (i = 0; i < ATA_ID_WORDS; i++)
1586                         port->identify[i] = le16_to_cpu(port->identify[i]);
1587         }
1588 #endif
1589
1590 #ifdef MTIP_TRIM /* Disabling TRIM support temporarily */
1591         /* Demux ID.DRAT & ID.RZAT to determine trim support */
1592         if (port->identify[69] & (1 << 14) && port->identify[69] & (1 << 5))
1593                 port->dd->trim_supp = true;
1594         else
1595 #endif
1596                 port->dd->trim_supp = false;
1597
1598         /* Set the identify buffer as valid. */
1599         port->identify_valid = 1;
1600
1601         if (user_buffer) {
1602                 if (copy_to_user(
1603                         user_buffer,
1604                         port->identify,
1605                         ATA_ID_WORDS * sizeof(u16))) {
1606                         rv = -EFAULT;
1607                         goto out;
1608                 }
1609         }
1610
1611 out:
1612         return rv;
1613 }
1614
1615 /*
1616  * Issue a standby immediate command to the device.
1617  *
1618  * @port Pointer to the port structure.
1619  *
1620  * return value
1621  *      0       Command was executed successfully.
1622  *      -1      An error occurred while executing the command.
1623  */
1624 static int mtip_standby_immediate(struct mtip_port *port)
1625 {
1626         int rv;
1627         struct host_to_dev_fis  fis;
1628         unsigned long start;
1629
1630         /* Build the FIS. */
1631         memset(&fis, 0, sizeof(struct host_to_dev_fis));
1632         fis.type        = 0x27;
1633         fis.opts        = 1 << 7;
1634         fis.command     = ATA_CMD_STANDBYNOW1;
1635
1636         start = jiffies;
1637         rv = mtip_exec_internal_command(port,
1638                                         &fis,
1639                                         5,
1640                                         0,
1641                                         0,
1642                                         0,
1643                                         GFP_ATOMIC,
1644                                         15000);
1645         dbg_printk(MTIP_DRV_NAME "Time taken to complete standby cmd: %d ms\n",
1646                         jiffies_to_msecs(jiffies - start));
1647         if (rv)
1648                 dev_warn(&port->dd->pdev->dev,
1649                         "STANDBY IMMEDIATE command failed.\n");
1650
1651         return rv;
1652 }
1653
1654 /*
1655  * Issue a READ LOG EXT command to the device.
1656  *
1657  * @port        pointer to the port structure.
1658  * @page        page number to fetch
1659  * @buffer      pointer to buffer
1660  * @buffer_dma  dma address corresponding to @buffer
1661  * @sectors     page length to fetch, in sectors
1662  *
1663  * return value
1664  *      @rv     return value from mtip_exec_internal_command()
1665  */
1666 static int mtip_read_log_page(struct mtip_port *port, u8 page, u16 *buffer,
1667                                 dma_addr_t buffer_dma, unsigned int sectors)
1668 {
1669         struct host_to_dev_fis fis;
1670
1671         memset(&fis, 0, sizeof(struct host_to_dev_fis));
1672         fis.type        = 0x27;
1673         fis.opts        = 1 << 7;
1674         fis.command     = ATA_CMD_READ_LOG_EXT;
1675         fis.sect_count  = sectors & 0xFF;
1676         fis.sect_cnt_ex = (sectors >> 8) & 0xFF;
1677         fis.lba_low     = page;
1678         fis.lba_mid     = 0;
1679         fis.device      = ATA_DEVICE_OBS;
1680
1681         memset(buffer, 0, sectors * ATA_SECT_SIZE);
1682
1683         return mtip_exec_internal_command(port,
1684                                         &fis,
1685                                         5,
1686                                         buffer_dma,
1687                                         sectors * ATA_SECT_SIZE,
1688                                         0,
1689                                         GFP_ATOMIC,
1690                                         MTIP_INTERNAL_COMMAND_TIMEOUT_MS);
1691 }
1692
1693 /*
1694  * Issue a SMART READ DATA command to the device.
1695  *
1696  * @port        pointer to the port structure.
1697  * @buffer      pointer to buffer
1698  * @buffer_dma  dma address corresponding to @buffer
1699  *
1700  * return value
1701  *      @rv     return value from mtip_exec_internal_command()
1702  */
1703 static int mtip_get_smart_data(struct mtip_port *port, u8 *buffer,
1704                                         dma_addr_t buffer_dma)
1705 {
1706         struct host_to_dev_fis fis;
1707
1708         memset(&fis, 0, sizeof(struct host_to_dev_fis));
1709         fis.type        = 0x27;
1710         fis.opts        = 1 << 7;
1711         fis.command     = ATA_CMD_SMART;
1712         fis.features    = 0xD0;
1713         fis.sect_count  = 1;
1714         fis.lba_mid     = 0x4F;
1715         fis.lba_hi      = 0xC2;
1716         fis.device      = ATA_DEVICE_OBS;
1717
1718         return mtip_exec_internal_command(port,
1719                                         &fis,
1720                                         5,
1721                                         buffer_dma,
1722                                         ATA_SECT_SIZE,
1723                                         0,
1724                                         GFP_ATOMIC,
1725                                         15000);
1726 }
1727
1728 /*
1729  * Get the value of a smart attribute
1730  *
1731  * @port        pointer to the port structure
1732  * @id          attribute number
1733  * @attrib      pointer to return attrib information corresponding to @id
1734  *
1735  * return value
1736  *      -EINVAL NULL buffer passed or unsupported attribute @id.
1737  *      -EPERM  Identify data not valid, SMART not supported or not enabled
1738  */
1739 static int mtip_get_smart_attr(struct mtip_port *port, unsigned int id,
1740                                                 struct smart_attr *attrib)
1741 {
1742         int rv, i;
1743         struct smart_attr *pattr;
1744
1745         if (!attrib)
1746                 return -EINVAL;
1747
1748         if (!port->identify_valid) {
1749                 dev_warn(&port->dd->pdev->dev, "IDENTIFY DATA not valid\n");
1750                 return -EPERM;
1751         }
1752         if (!(port->identify[82] & 0x1)) {
1753                 dev_warn(&port->dd->pdev->dev, "SMART not supported\n");
1754                 return -EPERM;
1755         }
1756         if (!(port->identify[85] & 0x1)) {
1757                 dev_warn(&port->dd->pdev->dev, "SMART not enabled\n");
1758                 return -EPERM;
1759         }
1760
1761         memset(port->smart_buf, 0, ATA_SECT_SIZE);
1762         rv = mtip_get_smart_data(port, port->smart_buf, port->smart_buf_dma);
1763         if (rv) {
1764                 dev_warn(&port->dd->pdev->dev, "Failed to ge SMART data\n");
1765                 return rv;
1766         }
1767
1768         pattr = (struct smart_attr *)(port->smart_buf + 2);
1769         for (i = 0; i < 29; i++, pattr++)
1770                 if (pattr->attr_id == id) {
1771                         memcpy(attrib, pattr, sizeof(struct smart_attr));
1772                         break;
1773                 }
1774
1775         if (i == 29) {
1776                 dev_warn(&port->dd->pdev->dev,
1777                         "Query for invalid SMART attribute ID\n");
1778                 rv = -EINVAL;
1779         }
1780
1781         return rv;
1782 }
1783
1784 /*
1785  * Trim unused sectors
1786  *
1787  * @dd          pointer to driver_data structure
1788  * @lba         starting lba
1789  * @len         # of 512b sectors to trim
1790  *
1791  * return value
1792  *      -ENOMEM         Out of dma memory
1793  *      -EINVAL         Invalid parameters passed in, trim not supported
1794  *      -EIO            Error submitting trim request to hw
1795  */
1796 static int mtip_send_trim(struct driver_data *dd, unsigned int lba,
1797                                 unsigned int len)
1798 {
1799         int i, rv = 0;
1800         u64 tlba, tlen, sect_left;
1801         struct mtip_trim_entry *buf;
1802         dma_addr_t dma_addr;
1803         struct host_to_dev_fis fis;
1804
1805         if (!len || dd->trim_supp == false)
1806                 return -EINVAL;
1807
1808         /* Trim request too big */
1809         WARN_ON(len > (MTIP_MAX_TRIM_ENTRY_LEN * MTIP_MAX_TRIM_ENTRIES));
1810
1811         /* Trim request not aligned on 4k boundary */
1812         WARN_ON(len % 8 != 0);
1813
1814         /* Warn if vu_trim structure is too big */
1815         WARN_ON(sizeof(struct mtip_trim) > ATA_SECT_SIZE);
1816
1817         /* Allocate a DMA buffer for the trim structure */
1818         buf = dmam_alloc_coherent(&dd->pdev->dev, ATA_SECT_SIZE, &dma_addr,
1819                                                                 GFP_KERNEL);
1820         if (!buf)
1821                 return -ENOMEM;
1822         memset(buf, 0, ATA_SECT_SIZE);
1823
1824         for (i = 0, sect_left = len, tlba = lba;
1825                         i < MTIP_MAX_TRIM_ENTRIES && sect_left;
1826                         i++) {
1827                 tlen = (sect_left >= MTIP_MAX_TRIM_ENTRY_LEN ?
1828                                         MTIP_MAX_TRIM_ENTRY_LEN :
1829                                         sect_left);
1830                 buf[i].lba = __force_bit2int cpu_to_le32(tlba);
1831                 buf[i].range = __force_bit2int cpu_to_le16(tlen);
1832                 tlba += tlen;
1833                 sect_left -= tlen;
1834         }
1835         WARN_ON(sect_left != 0);
1836
1837         /* Build the fis */
1838         memset(&fis, 0, sizeof(struct host_to_dev_fis));
1839         fis.type       = 0x27;
1840         fis.opts       = 1 << 7;
1841         fis.command    = 0xfb;
1842         fis.features   = 0x60;
1843         fis.sect_count = 1;
1844         fis.device     = ATA_DEVICE_OBS;
1845
1846         if (mtip_exec_internal_command(dd->port,
1847                                         &fis,
1848                                         5,
1849                                         dma_addr,
1850                                         ATA_SECT_SIZE,
1851                                         0,
1852                                         GFP_KERNEL,
1853                                         MTIP_TRIM_TIMEOUT_MS) < 0)
1854                 rv = -EIO;
1855
1856         dmam_free_coherent(&dd->pdev->dev, ATA_SECT_SIZE, buf, dma_addr);
1857         return rv;
1858 }
1859
1860 /*
1861  * Get the drive capacity.
1862  *
1863  * @dd      Pointer to the device data structure.
1864  * @sectors Pointer to the variable that will receive the sector count.
1865  *
1866  * return value
1867  *      1 Capacity was returned successfully.
1868  *      0 The identify information is invalid.
1869  */
1870 static bool mtip_hw_get_capacity(struct driver_data *dd, sector_t *sectors)
1871 {
1872         struct mtip_port *port = dd->port;
1873         u64 total, raw0, raw1, raw2, raw3;
1874         raw0 = port->identify[100];
1875         raw1 = port->identify[101];
1876         raw2 = port->identify[102];
1877         raw3 = port->identify[103];
1878         total = raw0 | raw1<<16 | raw2<<32 | raw3<<48;
1879         *sectors = total;
1880         return (bool) !!port->identify_valid;
1881 }
1882
1883 /*
1884  * Display the identify command data.
1885  *
1886  * @port Pointer to the port data structure.
1887  *
1888  * return value
1889  *      None
1890  */
1891 static void mtip_dump_identify(struct mtip_port *port)
1892 {
1893         sector_t sectors;
1894         unsigned short revid;
1895         char cbuf[42];
1896
1897         if (!port->identify_valid)
1898                 return;
1899
1900         strlcpy(cbuf, (char *)(port->identify+10), 21);
1901         dev_info(&port->dd->pdev->dev,
1902                 "Serial No.: %s\n", cbuf);
1903
1904         strlcpy(cbuf, (char *)(port->identify+23), 9);
1905         dev_info(&port->dd->pdev->dev,
1906                 "Firmware Ver.: %s\n", cbuf);
1907
1908         strlcpy(cbuf, (char *)(port->identify+27), 41);
1909         dev_info(&port->dd->pdev->dev, "Model: %s\n", cbuf);
1910
1911         if (mtip_hw_get_capacity(port->dd, &sectors))
1912                 dev_info(&port->dd->pdev->dev,
1913                         "Capacity: %llu sectors (%llu MB)\n",
1914                          (u64)sectors,
1915                          ((u64)sectors) * ATA_SECT_SIZE >> 20);
1916
1917         pci_read_config_word(port->dd->pdev, PCI_REVISION_ID, &revid);
1918         switch (revid & 0xFF) {
1919         case 0x1:
1920                 strlcpy(cbuf, "A0", 3);
1921                 break;
1922         case 0x3:
1923                 strlcpy(cbuf, "A2", 3);
1924                 break;
1925         default:
1926                 strlcpy(cbuf, "?", 2);
1927                 break;
1928         }
1929         dev_info(&port->dd->pdev->dev,
1930                 "Card Type: %s\n", cbuf);
1931 }
1932
1933 /*
1934  * Map the commands scatter list into the command table.
1935  *
1936  * @command Pointer to the command.
1937  * @nents Number of scatter list entries.
1938  *
1939  * return value
1940  *      None
1941  */
1942 static inline void fill_command_sg(struct driver_data *dd,
1943                                 struct mtip_cmd *command,
1944                                 int nents)
1945 {
1946         int n;
1947         unsigned int dma_len;
1948         struct mtip_cmd_sg *command_sg;
1949         struct scatterlist *sg = command->sg;
1950
1951         command_sg = command->command + AHCI_CMD_TBL_HDR_SZ;
1952
1953         for (n = 0; n < nents; n++) {
1954                 dma_len = sg_dma_len(sg);
1955                 if (dma_len > 0x400000)
1956                         dev_err(&dd->pdev->dev,
1957                                 "DMA segment length truncated\n");
1958                 command_sg->info = __force_bit2int
1959                         cpu_to_le32((dma_len-1) & 0x3FFFFF);
1960                 command_sg->dba = __force_bit2int
1961                         cpu_to_le32(sg_dma_address(sg));
1962                 command_sg->dba_upper = __force_bit2int
1963                         cpu_to_le32((sg_dma_address(sg) >> 16) >> 16);
1964                 command_sg++;
1965                 sg++;
1966         }
1967 }
1968
1969 /*
1970  * @brief Execute a drive command.
1971  *
1972  * return value 0 The command completed successfully.
1973  * return value -1 An error occurred while executing the command.
1974  */
1975 static int exec_drive_task(struct mtip_port *port, u8 *command)
1976 {
1977         struct host_to_dev_fis  fis;
1978         struct host_to_dev_fis *reply = (port->rxfis + RX_FIS_D2H_REG);
1979
1980         /* Build the FIS. */
1981         memset(&fis, 0, sizeof(struct host_to_dev_fis));
1982         fis.type        = 0x27;
1983         fis.opts        = 1 << 7;
1984         fis.command     = command[0];
1985         fis.features    = command[1];
1986         fis.sect_count  = command[2];
1987         fis.sector      = command[3];
1988         fis.cyl_low     = command[4];
1989         fis.cyl_hi      = command[5];
1990         fis.device      = command[6] & ~0x10; /* Clear the dev bit*/
1991
1992         dbg_printk(MTIP_DRV_NAME " %s: User Command: cmd %x, feat %x, nsect %x, sect %x, lcyl %x, hcyl %x, sel %x\n",
1993                 __func__,
1994                 command[0],
1995                 command[1],
1996                 command[2],
1997                 command[3],
1998                 command[4],
1999                 command[5],
2000                 command[6]);
2001
2002         /* Execute the command. */
2003         if (mtip_exec_internal_command(port,
2004                                  &fis,
2005                                  5,
2006                                  0,
2007                                  0,
2008                                  0,
2009                                  GFP_KERNEL,
2010                                  MTIP_IOCTL_COMMAND_TIMEOUT_MS) < 0) {
2011                 return -1;
2012         }
2013
2014         command[0] = reply->command; /* Status*/
2015         command[1] = reply->features; /* Error*/
2016         command[4] = reply->cyl_low;
2017         command[5] = reply->cyl_hi;
2018
2019         dbg_printk(MTIP_DRV_NAME " %s: Completion Status: stat %x, err %x , cyl_lo %x cyl_hi %x\n",
2020                 __func__,
2021                 command[0],
2022                 command[1],
2023                 command[4],
2024                 command[5]);
2025
2026         return 0;
2027 }
2028
2029 /*
2030  * @brief Execute a drive command.
2031  *
2032  * @param port Pointer to the port data structure.
2033  * @param command Pointer to the user specified command parameters.
2034  * @param user_buffer Pointer to the user space buffer where read sector
2035  *                   data should be copied.
2036  *
2037  * return value 0 The command completed successfully.
2038  * return value -EFAULT An error occurred while copying the completion
2039  *                 data to the user space buffer.
2040  * return value -1 An error occurred while executing the command.
2041  */
2042 static int exec_drive_command(struct mtip_port *port, u8 *command,
2043                                 void __user *user_buffer)
2044 {
2045         struct host_to_dev_fis  fis;
2046         struct host_to_dev_fis *reply;
2047         u8 *buf = NULL;
2048         dma_addr_t dma_addr = 0;
2049         int rv = 0, xfer_sz = command[3];
2050
2051         if (xfer_sz) {
2052                 if (!user_buffer)
2053                         return -EFAULT;
2054
2055                 buf = dmam_alloc_coherent(&port->dd->pdev->dev,
2056                                 ATA_SECT_SIZE * xfer_sz,
2057                                 &dma_addr,
2058                                 GFP_KERNEL);
2059                 if (!buf) {
2060                         dev_err(&port->dd->pdev->dev,
2061                                 "Memory allocation failed (%d bytes)\n",
2062                                 ATA_SECT_SIZE * xfer_sz);
2063                         return -ENOMEM;
2064                 }
2065                 memset(buf, 0, ATA_SECT_SIZE * xfer_sz);
2066         }
2067
2068         /* Build the FIS. */
2069         memset(&fis, 0, sizeof(struct host_to_dev_fis));
2070         fis.type        = 0x27;
2071         fis.opts        = 1 << 7;
2072         fis.command     = command[0];
2073         fis.features    = command[2];
2074         fis.sect_count  = command[3];
2075         if (fis.command == ATA_CMD_SMART) {
2076                 fis.sector      = command[1];
2077                 fis.cyl_low     = 0x4F;
2078                 fis.cyl_hi      = 0xC2;
2079         }
2080
2081         if (xfer_sz)
2082                 reply = (port->rxfis + RX_FIS_PIO_SETUP);
2083         else
2084                 reply = (port->rxfis + RX_FIS_D2H_REG);
2085
2086         dbg_printk(MTIP_DRV_NAME
2087                 " %s: User Command: cmd %x, sect %x, "
2088                 "feat %x, sectcnt %x\n",
2089                 __func__,
2090                 command[0],
2091                 command[1],
2092                 command[2],
2093                 command[3]);
2094
2095         /* Execute the command. */
2096         if (mtip_exec_internal_command(port,
2097                                 &fis,
2098                                  5,
2099                                  (xfer_sz ? dma_addr : 0),
2100                                  (xfer_sz ? ATA_SECT_SIZE * xfer_sz : 0),
2101                                  0,
2102                                  GFP_KERNEL,
2103                                  MTIP_IOCTL_COMMAND_TIMEOUT_MS)
2104                                  < 0) {
2105                 rv = -EFAULT;
2106                 goto exit_drive_command;
2107         }
2108
2109         /* Collect the completion status. */
2110         command[0] = reply->command; /* Status*/
2111         command[1] = reply->features; /* Error*/
2112         command[2] = reply->sect_count;
2113
2114         dbg_printk(MTIP_DRV_NAME
2115                 " %s: Completion Status: stat %x, "
2116                 "err %x, nsect %x\n",
2117                 __func__,
2118                 command[0],
2119                 command[1],
2120                 command[2]);
2121
2122         if (xfer_sz) {
2123                 if (copy_to_user(user_buffer,
2124                                  buf,
2125                                  ATA_SECT_SIZE * command[3])) {
2126                         rv = -EFAULT;
2127                         goto exit_drive_command;
2128                 }
2129         }
2130 exit_drive_command:
2131         if (buf)
2132                 dmam_free_coherent(&port->dd->pdev->dev,
2133                                 ATA_SECT_SIZE * xfer_sz, buf, dma_addr);
2134         return rv;
2135 }
2136
2137 /*
2138  *  Indicates whether a command has a single sector payload.
2139  *
2140  *  @command passed to the device to perform the certain event.
2141  *  @features passed to the device to perform the certain event.
2142  *
2143  *  return value
2144  *      1       command is one that always has a single sector payload,
2145  *              regardless of the value in the Sector Count field.
2146  *      0       otherwise
2147  *
2148  */
2149 static unsigned int implicit_sector(unsigned char command,
2150                                     unsigned char features)
2151 {
2152         unsigned int rv = 0;
2153
2154         /* list of commands that have an implicit sector count of 1 */
2155         switch (command) {
2156         case ATA_CMD_SEC_SET_PASS:
2157         case ATA_CMD_SEC_UNLOCK:
2158         case ATA_CMD_SEC_ERASE_PREP:
2159         case ATA_CMD_SEC_ERASE_UNIT:
2160         case ATA_CMD_SEC_FREEZE_LOCK:
2161         case ATA_CMD_SEC_DISABLE_PASS:
2162         case ATA_CMD_PMP_READ:
2163         case ATA_CMD_PMP_WRITE:
2164                 rv = 1;
2165                 break;
2166         case ATA_CMD_SET_MAX:
2167                 if (features == ATA_SET_MAX_UNLOCK)
2168                         rv = 1;
2169                 break;
2170         case ATA_CMD_SMART:
2171                 if ((features == ATA_SMART_READ_VALUES) ||
2172                                 (features == ATA_SMART_READ_THRESHOLDS))
2173                         rv = 1;
2174                 break;
2175         case ATA_CMD_CONF_OVERLAY:
2176                 if ((features == ATA_DCO_IDENTIFY) ||
2177                                 (features == ATA_DCO_SET))
2178                         rv = 1;
2179                 break;
2180         }
2181         return rv;
2182 }
2183 static void mtip_set_timeout(struct driver_data *dd,
2184                                         struct host_to_dev_fis *fis,
2185                                         unsigned int *timeout, u8 erasemode)
2186 {
2187         switch (fis->command) {
2188         case ATA_CMD_DOWNLOAD_MICRO:
2189                 *timeout = 120000; /* 2 minutes */
2190                 break;
2191         case ATA_CMD_SEC_ERASE_UNIT:
2192         case 0xFC:
2193                 if (erasemode)
2194                         *timeout = ((*(dd->port->identify + 90) * 2) * 60000);
2195                 else
2196                         *timeout = ((*(dd->port->identify + 89) * 2) * 60000);
2197                 break;
2198         case ATA_CMD_STANDBYNOW1:
2199                 *timeout = 120000;  /* 2 minutes */
2200                 break;
2201         case 0xF7:
2202         case 0xFA:
2203                 *timeout = 60000;  /* 60 seconds */
2204                 break;
2205         case ATA_CMD_SMART:
2206                 *timeout = 15000;  /* 15 seconds */
2207                 break;
2208         default:
2209                 *timeout = MTIP_IOCTL_COMMAND_TIMEOUT_MS;
2210                 break;
2211         }
2212 }
2213
2214 /*
2215  * Executes a taskfile
2216  * See ide_taskfile_ioctl() for derivation
2217  */
2218 static int exec_drive_taskfile(struct driver_data *dd,
2219                                void __user *buf,
2220                                ide_task_request_t *req_task,
2221                                int outtotal)
2222 {
2223         struct host_to_dev_fis  fis;
2224         struct host_to_dev_fis *reply;
2225         u8 *outbuf = NULL;
2226         u8 *inbuf = NULL;
2227         dma_addr_t outbuf_dma = 0;
2228         dma_addr_t inbuf_dma = 0;
2229         dma_addr_t dma_buffer = 0;
2230         int err = 0;
2231         unsigned int taskin = 0;
2232         unsigned int taskout = 0;
2233         u8 nsect = 0;
2234         unsigned int timeout;
2235         unsigned int force_single_sector;
2236         unsigned int transfer_size;
2237         unsigned long task_file_data;
2238         int intotal = outtotal + req_task->out_size;
2239         int erasemode = 0;
2240
2241         taskout = req_task->out_size;
2242         taskin = req_task->in_size;
2243         /* 130560 = 512 * 0xFF*/
2244         if (taskin > 130560 || taskout > 130560) {
2245                 err = -EINVAL;
2246                 goto abort;
2247         }
2248
2249         if (taskout) {
2250                 outbuf = kzalloc(taskout, GFP_KERNEL);
2251                 if (outbuf == NULL) {
2252                         err = -ENOMEM;
2253                         goto abort;
2254                 }
2255                 if (copy_from_user(outbuf, buf + outtotal, taskout)) {
2256                         err = -EFAULT;
2257                         goto abort;
2258                 }
2259                 outbuf_dma = pci_map_single(dd->pdev,
2260                                          outbuf,
2261                                          taskout,
2262                                          DMA_TO_DEVICE);
2263                 if (outbuf_dma == 0) {
2264                         err = -ENOMEM;
2265                         goto abort;
2266                 }
2267                 dma_buffer = outbuf_dma;
2268         }
2269
2270         if (taskin) {
2271                 inbuf = kzalloc(taskin, GFP_KERNEL);
2272                 if (inbuf == NULL) {
2273                         err = -ENOMEM;
2274                         goto abort;
2275                 }
2276
2277                 if (copy_from_user(inbuf, buf + intotal, taskin)) {
2278                         err = -EFAULT;
2279                         goto abort;
2280                 }
2281                 inbuf_dma = pci_map_single(dd->pdev,
2282                                          inbuf,
2283                                          taskin, DMA_FROM_DEVICE);
2284                 if (inbuf_dma == 0) {
2285                         err = -ENOMEM;
2286                         goto abort;
2287                 }
2288                 dma_buffer = inbuf_dma;
2289         }
2290
2291         /* only supports PIO and non-data commands from this ioctl. */
2292         switch (req_task->data_phase) {
2293         case TASKFILE_OUT:
2294                 nsect = taskout / ATA_SECT_SIZE;
2295                 reply = (dd->port->rxfis + RX_FIS_PIO_SETUP);
2296                 break;
2297         case TASKFILE_IN:
2298                 reply = (dd->port->rxfis + RX_FIS_PIO_SETUP);
2299                 break;
2300         case TASKFILE_NO_DATA:
2301                 reply = (dd->port->rxfis + RX_FIS_D2H_REG);
2302                 break;
2303         default:
2304                 err = -EINVAL;
2305                 goto abort;
2306         }
2307
2308         /* Build the FIS. */
2309         memset(&fis, 0, sizeof(struct host_to_dev_fis));
2310
2311         fis.type        = 0x27;
2312         fis.opts        = 1 << 7;
2313         fis.command     = req_task->io_ports[7];
2314         fis.features    = req_task->io_ports[1];
2315         fis.sect_count  = req_task->io_ports[2];
2316         fis.lba_low     = req_task->io_ports[3];
2317         fis.lba_mid     = req_task->io_ports[4];
2318         fis.lba_hi      = req_task->io_ports[5];
2319          /* Clear the dev bit*/
2320         fis.device      = req_task->io_ports[6] & ~0x10;
2321
2322         if ((req_task->in_flags.all == 0) && (req_task->out_flags.all & 1)) {
2323                 req_task->in_flags.all  =
2324                         IDE_TASKFILE_STD_IN_FLAGS |
2325                         (IDE_HOB_STD_IN_FLAGS << 8);
2326                 fis.lba_low_ex          = req_task->hob_ports[3];
2327                 fis.lba_mid_ex          = req_task->hob_ports[4];
2328                 fis.lba_hi_ex           = req_task->hob_ports[5];
2329                 fis.features_ex         = req_task->hob_ports[1];
2330                 fis.sect_cnt_ex         = req_task->hob_ports[2];
2331
2332         } else {
2333                 req_task->in_flags.all = IDE_TASKFILE_STD_IN_FLAGS;
2334         }
2335
2336         force_single_sector = implicit_sector(fis.command, fis.features);
2337
2338         if ((taskin || taskout) && (!fis.sect_count)) {
2339                 if (nsect)
2340                         fis.sect_count = nsect;
2341                 else {
2342                         if (!force_single_sector) {
2343                                 dev_warn(&dd->pdev->dev,
2344                                         "data movement but "
2345                                         "sect_count is 0\n");
2346                                         err = -EINVAL;
2347                                         goto abort;
2348                         }
2349                 }
2350         }
2351
2352         dbg_printk(MTIP_DRV_NAME
2353                 " %s: cmd %x, feat %x, nsect %x,"
2354                 " sect/lbal %x, lcyl/lbam %x, hcyl/lbah %x,"
2355                 " head/dev %x\n",
2356                 __func__,
2357                 fis.command,
2358                 fis.features,
2359                 fis.sect_count,
2360                 fis.lba_low,
2361                 fis.lba_mid,
2362                 fis.lba_hi,
2363                 fis.device);
2364
2365         /* check for erase mode support during secure erase.*/
2366         if ((fis.command == ATA_CMD_SEC_ERASE_UNIT) && outbuf &&
2367                                         (outbuf[0] & MTIP_SEC_ERASE_MODE)) {
2368                 erasemode = 1;
2369         }
2370
2371         mtip_set_timeout(dd, &fis, &timeout, erasemode);
2372
2373         /* Determine the correct transfer size.*/
2374         if (force_single_sector)
2375                 transfer_size = ATA_SECT_SIZE;
2376         else
2377                 transfer_size = ATA_SECT_SIZE * fis.sect_count;
2378
2379         /* Execute the command.*/
2380         if (mtip_exec_internal_command(dd->port,
2381                                  &fis,
2382                                  5,
2383                                  dma_buffer,
2384                                  transfer_size,
2385                                  0,
2386                                  GFP_KERNEL,
2387                                  timeout) < 0) {
2388                 err = -EIO;
2389                 goto abort;
2390         }
2391
2392         task_file_data = readl(dd->port->mmio+PORT_TFDATA);
2393
2394         if ((req_task->data_phase == TASKFILE_IN) && !(task_file_data & 1)) {
2395                 reply = dd->port->rxfis + RX_FIS_PIO_SETUP;
2396                 req_task->io_ports[7] = reply->control;
2397         } else {
2398                 reply = dd->port->rxfis + RX_FIS_D2H_REG;
2399                 req_task->io_ports[7] = reply->command;
2400         }
2401
2402         /* reclaim the DMA buffers.*/
2403         if (inbuf_dma)
2404                 pci_unmap_single(dd->pdev, inbuf_dma,
2405                         taskin, DMA_FROM_DEVICE);
2406         if (outbuf_dma)
2407                 pci_unmap_single(dd->pdev, outbuf_dma,
2408                         taskout, DMA_TO_DEVICE);
2409         inbuf_dma  = 0;
2410         outbuf_dma = 0;
2411
2412         /* return the ATA registers to the caller.*/
2413         req_task->io_ports[1] = reply->features;
2414         req_task->io_ports[2] = reply->sect_count;
2415         req_task->io_ports[3] = reply->lba_low;
2416         req_task->io_ports[4] = reply->lba_mid;
2417         req_task->io_ports[5] = reply->lba_hi;
2418         req_task->io_ports[6] = reply->device;
2419
2420         if (req_task->out_flags.all & 1)  {
2421
2422                 req_task->hob_ports[3] = reply->lba_low_ex;
2423                 req_task->hob_ports[4] = reply->lba_mid_ex;
2424                 req_task->hob_ports[5] = reply->lba_hi_ex;
2425                 req_task->hob_ports[1] = reply->features_ex;
2426                 req_task->hob_ports[2] = reply->sect_cnt_ex;
2427         }
2428         dbg_printk(MTIP_DRV_NAME
2429                 " %s: Completion: stat %x,"
2430                 "err %x, sect_cnt %x, lbalo %x,"
2431                 "lbamid %x, lbahi %x, dev %x\n",
2432                 __func__,
2433                 req_task->io_ports[7],
2434                 req_task->io_ports[1],
2435                 req_task->io_ports[2],
2436                 req_task->io_ports[3],
2437                 req_task->io_ports[4],
2438                 req_task->io_ports[5],
2439                 req_task->io_ports[6]);
2440
2441         if (taskout) {
2442                 if (copy_to_user(buf + outtotal, outbuf, taskout)) {
2443                         err = -EFAULT;
2444                         goto abort;
2445                 }
2446         }
2447         if (taskin) {
2448                 if (copy_to_user(buf + intotal, inbuf, taskin)) {
2449                         err = -EFAULT;
2450                         goto abort;
2451                 }
2452         }
2453 abort:
2454         if (inbuf_dma)
2455                 pci_unmap_single(dd->pdev, inbuf_dma,
2456                                         taskin, DMA_FROM_DEVICE);
2457         if (outbuf_dma)
2458                 pci_unmap_single(dd->pdev, outbuf_dma,
2459                                         taskout, DMA_TO_DEVICE);
2460         kfree(outbuf);
2461         kfree(inbuf);
2462
2463         return err;
2464 }
2465
2466 /*
2467  * Handle IOCTL calls from the Block Layer.
2468  *
2469  * This function is called by the Block Layer when it receives an IOCTL
2470  * command that it does not understand. If the IOCTL command is not supported
2471  * this function returns -ENOTTY.
2472  *
2473  * @dd  Pointer to the driver data structure.
2474  * @cmd IOCTL command passed from the Block Layer.
2475  * @arg IOCTL argument passed from the Block Layer.
2476  *
2477  * return value
2478  *      0       The IOCTL completed successfully.
2479  *      -ENOTTY The specified command is not supported.
2480  *      -EFAULT An error occurred copying data to a user space buffer.
2481  *      -EIO    An error occurred while executing the command.
2482  */
2483 static int mtip_hw_ioctl(struct driver_data *dd, unsigned int cmd,
2484                          unsigned long arg)
2485 {
2486         switch (cmd) {
2487         case HDIO_GET_IDENTITY:
2488         {
2489                 if (copy_to_user((void __user *)arg, dd->port->identify,
2490                                                 sizeof(u16) * ATA_ID_WORDS))
2491                         return -EFAULT;
2492                 break;
2493         }
2494         case HDIO_DRIVE_CMD:
2495         {
2496                 u8 drive_command[4];
2497
2498                 /* Copy the user command info to our buffer. */
2499                 if (copy_from_user(drive_command,
2500                                          (void __user *) arg,
2501                                          sizeof(drive_command)))
2502                         return -EFAULT;
2503
2504                 /* Execute the drive command. */
2505                 if (exec_drive_command(dd->port,
2506                                          drive_command,
2507                                          (void __user *) (arg+4)))
2508                         return -EIO;
2509
2510                 /* Copy the status back to the users buffer. */
2511                 if (copy_to_user((void __user *) arg,
2512                                          drive_command,
2513                                          sizeof(drive_command)))
2514                         return -EFAULT;
2515
2516                 break;
2517         }
2518         case HDIO_DRIVE_TASK:
2519         {
2520                 u8 drive_command[7];
2521
2522                 /* Copy the user command info to our buffer. */
2523                 if (copy_from_user(drive_command,
2524                                          (void __user *) arg,
2525                                          sizeof(drive_command)))
2526                         return -EFAULT;
2527
2528                 /* Execute the drive command. */
2529                 if (exec_drive_task(dd->port, drive_command))
2530                         return -EIO;
2531
2532                 /* Copy the status back to the users buffer. */
2533                 if (copy_to_user((void __user *) arg,
2534                                          drive_command,
2535                                          sizeof(drive_command)))
2536                         return -EFAULT;
2537
2538                 break;
2539         }
2540         case HDIO_DRIVE_TASKFILE: {
2541                 ide_task_request_t req_task;
2542                 int ret, outtotal;
2543
2544                 if (copy_from_user(&req_task, (void __user *) arg,
2545                                         sizeof(req_task)))
2546                         return -EFAULT;
2547
2548                 outtotal = sizeof(req_task);
2549
2550                 ret = exec_drive_taskfile(dd, (void __user *) arg,
2551                                                 &req_task, outtotal);
2552
2553                 if (copy_to_user((void __user *) arg, &req_task,
2554                                                         sizeof(req_task)))
2555                         return -EFAULT;
2556
2557                 return ret;
2558         }
2559
2560         default:
2561                 return -EINVAL;
2562         }
2563         return 0;
2564 }
2565
2566 /*
2567  * Submit an IO to the hw
2568  *
2569  * This function is called by the block layer to issue an io
2570  * to the device. Upon completion, the callback function will
2571  * be called with the data parameter passed as the callback data.
2572  *
2573  * @dd       Pointer to the driver data structure.
2574  * @start    First sector to read.
2575  * @nsect    Number of sectors to read.
2576  * @nents    Number of entries in scatter list for the read command.
2577  * @tag      The tag of this read command.
2578  * @callback Pointer to the function that should be called
2579  *           when the read completes.
2580  * @data     Callback data passed to the callback function
2581  *           when the read completes.
2582  * @dir      Direction (read or write)
2583  *
2584  * return value
2585  *      None
2586  */
2587 static void mtip_hw_submit_io(struct driver_data *dd, sector_t sector,
2588                               int nsect, int nents, int tag, void *callback,
2589                               void *data, int dir, int unaligned)
2590 {
2591         struct host_to_dev_fis  *fis;
2592         struct mtip_port *port = dd->port;
2593         struct mtip_cmd *command = &port->commands[tag];
2594         int dma_dir = (dir == READ) ? DMA_FROM_DEVICE : DMA_TO_DEVICE;
2595         u64 start = sector;
2596
2597         /* Map the scatter list for DMA access */
2598         nents = dma_map_sg(&dd->pdev->dev, command->sg, nents, dma_dir);
2599
2600         command->scatter_ents = nents;
2601
2602         command->unaligned = unaligned;
2603         /*
2604          * The number of retries for this command before it is
2605          * reported as a failure to the upper layers.
2606          */
2607         command->retries = MTIP_MAX_RETRIES;
2608
2609         /* Fill out fis */
2610         fis = command->command;
2611         fis->type        = 0x27;
2612         fis->opts        = 1 << 7;
2613         fis->command     =
2614                 (dir == READ ? ATA_CMD_FPDMA_READ : ATA_CMD_FPDMA_WRITE);
2615         fis->lba_low     = start & 0xFF;
2616         fis->lba_mid     = (start >> 8) & 0xFF;
2617         fis->lba_hi      = (start >> 16) & 0xFF;
2618         fis->lba_low_ex  = (start >> 24) & 0xFF;
2619         fis->lba_mid_ex  = (start >> 32) & 0xFF;
2620         fis->lba_hi_ex   = (start >> 40) & 0xFF;
2621         fis->device      = 1 << 6;
2622         fis->features    = nsect & 0xFF;
2623         fis->features_ex = (nsect >> 8) & 0xFF;
2624         fis->sect_count  = ((tag << 3) | (tag >> 5));
2625         fis->sect_cnt_ex = 0;
2626         fis->control     = 0;
2627         fis->res2        = 0;
2628         fis->res3        = 0;
2629         fill_command_sg(dd, command, nents);
2630
2631         if (unaligned)
2632                 fis->device |= 1 << 7;
2633
2634         /* Populate the command header */
2635         command->command_header->opts =
2636                         __force_bit2int cpu_to_le32(
2637                                 (nents << 16) | 5 | AHCI_CMD_PREFETCH);
2638         command->command_header->byte_count = 0;
2639
2640         /*
2641          * Set the completion function and data for the command
2642          * within this layer.
2643          */
2644         command->comp_data = dd;
2645         command->comp_func = mtip_async_complete;
2646         command->direction = dma_dir;
2647
2648         /*
2649          * Set the completion function and data for the command passed
2650          * from the upper layer.
2651          */
2652         command->async_data = data;
2653         command->async_callback = callback;
2654
2655         /*
2656          * To prevent this command from being issued
2657          * if an internal command is in progress or error handling is active.
2658          */
2659         if (port->flags & MTIP_PF_PAUSE_IO) {
2660                 set_bit(tag, port->cmds_to_issue);
2661                 set_bit(MTIP_PF_ISSUE_CMDS_BIT, &port->flags);
2662                 return;
2663         }
2664
2665         /* Issue the command to the hardware */
2666         mtip_issue_ncq_command(port, tag);
2667
2668         return;
2669 }
2670
2671 /*
2672  * Release a command slot.
2673  *
2674  * @dd  Pointer to the driver data structure.
2675  * @tag Slot tag
2676  *
2677  * return value
2678  *      None
2679  */
2680 static void mtip_hw_release_scatterlist(struct driver_data *dd, int tag,
2681                                                                 int unaligned)
2682 {
2683         struct semaphore *sem = unaligned ? &dd->port->cmd_slot_unal :
2684                                                         &dd->port->cmd_slot;
2685         release_slot(dd->port, tag);
2686         up(sem);
2687 }
2688
2689 /*
2690  * Obtain a command slot and return its associated scatter list.
2691  *
2692  * @dd  Pointer to the driver data structure.
2693  * @tag Pointer to an int that will receive the allocated command
2694  *            slot tag.
2695  *
2696  * return value
2697  *      Pointer to the scatter list for the allocated command slot
2698  *      or NULL if no command slots are available.
2699  */
2700 static struct scatterlist *mtip_hw_get_scatterlist(struct driver_data *dd,
2701                                                    int *tag, int unaligned)
2702 {
2703         struct semaphore *sem = unaligned ? &dd->port->cmd_slot_unal :
2704                                                         &dd->port->cmd_slot;
2705
2706         /*
2707          * It is possible that, even with this semaphore, a thread
2708          * may think that no command slots are available. Therefore, we
2709          * need to make an attempt to get_slot().
2710          */
2711         down(sem);
2712         *tag = get_slot(dd->port);
2713
2714         if (unlikely(test_bit(MTIP_DDF_REMOVE_PENDING_BIT, &dd->dd_flag))) {
2715                 up(sem);
2716                 return NULL;
2717         }
2718         if (unlikely(*tag < 0)) {
2719                 up(sem);
2720                 return NULL;
2721         }
2722
2723         return dd->port->commands[*tag].sg;
2724 }
2725
2726 /*
2727  * Sysfs status dump.
2728  *
2729  * @dev  Pointer to the device structure, passed by the kernrel.
2730  * @attr Pointer to the device_attribute structure passed by the kernel.
2731  * @buf  Pointer to the char buffer that will receive the stats info.
2732  *
2733  * return value
2734  *      The size, in bytes, of the data copied into buf.
2735  */
2736 static ssize_t mtip_hw_show_status(struct device *dev,
2737                                 struct device_attribute *attr,
2738                                 char *buf)
2739 {
2740         struct driver_data *dd = dev_to_disk(dev)->private_data;
2741         int size = 0;
2742
2743         if (test_bit(MTIP_DDF_OVER_TEMP_BIT, &dd->dd_flag))
2744                 size += sprintf(buf, "%s", "thermal_shutdown\n");
2745         else if (test_bit(MTIP_DDF_WRITE_PROTECT_BIT, &dd->dd_flag))
2746                 size += sprintf(buf, "%s", "write_protect\n");
2747         else
2748                 size += sprintf(buf, "%s", "online\n");
2749
2750         return size;
2751 }
2752
2753 static DEVICE_ATTR(status, S_IRUGO, mtip_hw_show_status, NULL);
2754
2755 /* debugsfs entries */
2756
2757 static ssize_t show_device_status(struct device_driver *drv, char *buf)
2758 {
2759         int size = 0;
2760         struct driver_data *dd, *tmp;
2761         unsigned long flags;
2762         char id_buf[42];
2763         u16 status = 0;
2764
2765         spin_lock_irqsave(&dev_lock, flags);
2766         size += sprintf(&buf[size], "Devices Present:\n");
2767         list_for_each_entry_safe(dd, tmp, &online_list, online_list) {
2768                 if (dd->pdev) {
2769                         if (dd->port &&
2770                             dd->port->identify &&
2771                             dd->port->identify_valid) {
2772                                 strlcpy(id_buf,
2773                                         (char *) (dd->port->identify + 10), 21);
2774                                 status = *(dd->port->identify + 141);
2775                         } else {
2776                                 memset(id_buf, 0, 42);
2777                                 status = 0;
2778                         }
2779
2780                         if (dd->port &&
2781                             test_bit(MTIP_PF_REBUILD_BIT, &dd->port->flags)) {
2782                                 size += sprintf(&buf[size],
2783                                         " device %s %s (ftl rebuild %d %%)\n",
2784                                         dev_name(&dd->pdev->dev),
2785                                         id_buf,
2786                                         status);
2787                         } else {
2788                                 size += sprintf(&buf[size],
2789                                         " device %s %s\n",
2790                                         dev_name(&dd->pdev->dev),
2791                                         id_buf);
2792                         }
2793                 }
2794         }
2795
2796         size += sprintf(&buf[size], "Devices Being Removed:\n");
2797         list_for_each_entry_safe(dd, tmp, &removing_list, remove_list) {
2798                 if (dd->pdev) {
2799                         if (dd->port &&
2800                             dd->port->identify &&
2801                             dd->port->identify_valid) {
2802                                 strlcpy(id_buf,
2803                                         (char *) (dd->port->identify+10), 21);
2804                                 status = *(dd->port->identify + 141);
2805                         } else {
2806                                 memset(id_buf, 0, 42);
2807                                 status = 0;
2808                         }
2809
2810                         if (dd->port &&
2811                             test_bit(MTIP_PF_REBUILD_BIT, &dd->port->flags)) {
2812                                 size += sprintf(&buf[size],
2813                                         " device %s %s (ftl rebuild %d %%)\n",
2814                                         dev_name(&dd->pdev->dev),
2815                                         id_buf,
2816                                         status);
2817                         } else {
2818                                 size += sprintf(&buf[size],
2819                                         " device %s %s\n",
2820                                         dev_name(&dd->pdev->dev),
2821                                         id_buf);
2822                         }
2823                 }
2824         }
2825         spin_unlock_irqrestore(&dev_lock, flags);
2826
2827         return size;
2828 }
2829
2830 static ssize_t mtip_hw_read_device_status(struct file *f, char __user *ubuf,
2831                                                 size_t len, loff_t *offset)
2832 {
2833         struct driver_data *dd =  (struct driver_data *)f->private_data;
2834         int size = *offset;
2835         char *buf;
2836         int rv = 0;
2837
2838         if (!len || *offset)
2839                 return 0;
2840
2841         buf = kzalloc(MTIP_DFS_MAX_BUF_SIZE, GFP_KERNEL);
2842         if (!buf) {
2843                 dev_err(&dd->pdev->dev,
2844                         "Memory allocation: status buffer\n");
2845                 return -ENOMEM;
2846         }
2847
2848         size += show_device_status(NULL, buf);
2849
2850         *offset = size <= len ? size : len;
2851         size = copy_to_user(ubuf, buf, *offset);
2852         if (size)
2853                 rv = -EFAULT;
2854
2855         kfree(buf);
2856         return rv ? rv : *offset;
2857 }
2858
2859 static ssize_t mtip_hw_read_registers(struct file *f, char __user *ubuf,
2860                                   size_t len, loff_t *offset)
2861 {
2862         struct driver_data *dd =  (struct driver_data *)f->private_data;
2863         char *buf;
2864         u32 group_allocated;
2865         int size = *offset;
2866         int n, rv = 0;
2867
2868         if (!len || size)
2869                 return 0;
2870
2871         buf = kzalloc(MTIP_DFS_MAX_BUF_SIZE, GFP_KERNEL);
2872         if (!buf) {
2873                 dev_err(&dd->pdev->dev,
2874                         "Memory allocation: register buffer\n");
2875                 return -ENOMEM;
2876         }
2877
2878         size += sprintf(&buf[size], "H/ S ACTive      : [ 0x");
2879
2880         for (n = dd->slot_groups-1; n >= 0; n--)
2881                 size += sprintf(&buf[size], "%08X ",
2882                                          readl(dd->port->s_active[n]));
2883
2884         size += sprintf(&buf[size], "]\n");
2885         size += sprintf(&buf[size], "H/ Command Issue : [ 0x");
2886
2887         for (n = dd->slot_groups-1; n >= 0; n--)
2888                 size += sprintf(&buf[size], "%08X ",
2889                                         readl(dd->port->cmd_issue[n]));
2890
2891         size += sprintf(&buf[size], "]\n");
2892         size += sprintf(&buf[size], "H/ Completed     : [ 0x");
2893
2894         for (n = dd->slot_groups-1; n >= 0; n--)
2895                 size += sprintf(&buf[size], "%08X ",
2896                                 readl(dd->port->completed[n]));
2897
2898         size += sprintf(&buf[size], "]\n");
2899         size += sprintf(&buf[size], "H/ PORT IRQ STAT : [ 0x%08X ]\n",
2900                                 readl(dd->port->mmio + PORT_IRQ_STAT));
2901         size += sprintf(&buf[size], "H/ HOST IRQ STAT : [ 0x%08X ]\n",
2902                                 readl(dd->mmio + HOST_IRQ_STAT));
2903         size += sprintf(&buf[size], "\n");
2904
2905         size += sprintf(&buf[size], "L/ Allocated     : [ 0x");
2906
2907         for (n = dd->slot_groups-1; n >= 0; n--) {
2908                 if (sizeof(long) > sizeof(u32))
2909                         group_allocated =
2910                                 dd->port->allocated[n/2] >> (32*(n&1));
2911                 else
2912                         group_allocated = dd->port->allocated[n];
2913                 size += sprintf(&buf[size], "%08X ", group_allocated);
2914         }
2915         size += sprintf(&buf[size], "]\n");
2916
2917         size += sprintf(&buf[size], "L/ Commands in Q : [ 0x");
2918
2919         for (n = dd->slot_groups-1; n >= 0; n--) {
2920                 if (sizeof(long) > sizeof(u32))
2921                         group_allocated =
2922                                 dd->port->cmds_to_issue[n/2] >> (32*(n&1));
2923                 else
2924                         group_allocated = dd->port->cmds_to_issue[n];
2925                 size += sprintf(&buf[size], "%08X ", group_allocated);
2926         }
2927         size += sprintf(&buf[size], "]\n");
2928
2929         *offset = size <= len ? size : len;
2930         size = copy_to_user(ubuf, buf, *offset);
2931         if (size)
2932                 rv = -EFAULT;
2933
2934         kfree(buf);
2935         return rv ? rv : *offset;
2936 }
2937
2938 static ssize_t mtip_hw_read_flags(struct file *f, char __user *ubuf,
2939                                   size_t len, loff_t *offset)
2940 {
2941         struct driver_data *dd =  (struct driver_data *)f->private_data;
2942         char *buf;
2943         int size = *offset;
2944         int rv = 0;
2945
2946         if (!len || size)
2947                 return 0;
2948
2949         buf = kzalloc(MTIP_DFS_MAX_BUF_SIZE, GFP_KERNEL);
2950         if (!buf) {
2951                 dev_err(&dd->pdev->dev,
2952                         "Memory allocation: flag buffer\n");
2953                 return -ENOMEM;
2954         }
2955
2956         size += sprintf(&buf[size], "Flag-port : [ %08lX ]\n",
2957                                                         dd->port->flags);
2958         size += sprintf(&buf[size], "Flag-dd   : [ %08lX ]\n",
2959                                                         dd->dd_flag);
2960
2961         *offset = size <= len ? size : len;
2962         size = copy_to_user(ubuf, buf, *offset);
2963         if (size)
2964                 rv = -EFAULT;
2965
2966         kfree(buf);
2967         return rv ? rv : *offset;
2968 }
2969
2970 static const struct file_operations mtip_device_status_fops = {
2971         .owner  = THIS_MODULE,
2972         .open   = simple_open,
2973         .read   = mtip_hw_read_device_status,
2974         .llseek = no_llseek,
2975 };
2976
2977 static const struct file_operations mtip_regs_fops = {
2978         .owner  = THIS_MODULE,
2979         .open   = simple_open,
2980         .read   = mtip_hw_read_registers,
2981         .llseek = no_llseek,
2982 };
2983
2984 static const struct file_operations mtip_flags_fops = {
2985         .owner  = THIS_MODULE,
2986         .open   = simple_open,
2987         .read   = mtip_hw_read_flags,
2988         .llseek = no_llseek,
2989 };
2990
2991 /*
2992  * Create the sysfs related attributes.
2993  *
2994  * @dd   Pointer to the driver data structure.
2995  * @kobj Pointer to the kobj for the block device.
2996  *
2997  * return value
2998  *      0       Operation completed successfully.
2999  *      -EINVAL Invalid parameter.
3000  */
3001 static int mtip_hw_sysfs_init(struct driver_data *dd, struct kobject *kobj)
3002 {
3003         if (!kobj || !dd)
3004                 return -EINVAL;
3005
3006         if (sysfs_create_file(kobj, &dev_attr_status.attr))
3007                 dev_warn(&dd->pdev->dev,
3008                         "Error creating 'status' sysfs entry\n");
3009         return 0;
3010 }
3011
3012 /*
3013  * Remove the sysfs related attributes.
3014  *
3015  * @dd   Pointer to the driver data structure.
3016  * @kobj Pointer to the kobj for the block device.
3017  *
3018  * return value
3019  *      0       Operation completed successfully.
3020  *      -EINVAL Invalid parameter.
3021  */
3022 static int mtip_hw_sysfs_exit(struct driver_data *dd, struct kobject *kobj)
3023 {
3024         if (!kobj || !dd)
3025                 return -EINVAL;
3026
3027         sysfs_remove_file(kobj, &dev_attr_status.attr);
3028
3029         return 0;
3030 }
3031
3032 static int mtip_hw_debugfs_init(struct driver_data *dd)
3033 {
3034         if (!dfs_parent)
3035                 return -1;
3036
3037         dd->dfs_node = debugfs_create_dir(dd->disk->disk_name, dfs_parent);
3038         if (IS_ERR_OR_NULL(dd->dfs_node)) {
3039                 dev_warn(&dd->pdev->dev,
3040                         "Error creating node %s under debugfs\n",
3041                                                 dd->disk->disk_name);
3042                 dd->dfs_node = NULL;
3043                 return -1;
3044         }
3045
3046         debugfs_create_file("flags", S_IRUGO, dd->dfs_node, dd,
3047                                                         &mtip_flags_fops);
3048         debugfs_create_file("registers", S_IRUGO, dd->dfs_node, dd,
3049                                                         &mtip_regs_fops);
3050
3051         return 0;
3052 }
3053
3054 static void mtip_hw_debugfs_exit(struct driver_data *dd)
3055 {
3056         if (dd->dfs_node)
3057                 debugfs_remove_recursive(dd->dfs_node);
3058 }
3059
3060 static int mtip_free_orphan(struct driver_data *dd)
3061 {
3062         struct kobject *kobj;
3063
3064         if (dd->bdev) {
3065                 if (dd->bdev->bd_holders >= 1)
3066                         return -2;
3067
3068                 bdput(dd->bdev);
3069                 dd->bdev = NULL;
3070         }
3071
3072         mtip_hw_debugfs_exit(dd);
3073
3074         spin_lock(&rssd_index_lock);
3075         ida_remove(&rssd_index_ida, dd->index);
3076         spin_unlock(&rssd_index_lock);
3077
3078         if (!test_bit(MTIP_DDF_INIT_DONE_BIT, &dd->dd_flag) &&
3079                         test_bit(MTIP_DDF_REBUILD_FAILED_BIT, &dd->dd_flag)) {
3080                 put_disk(dd->disk);
3081         } else {
3082                 if (dd->disk) {
3083                         kobj = kobject_get(&disk_to_dev(dd->disk)->kobj);
3084                         if (kobj) {
3085                                 mtip_hw_sysfs_exit(dd, kobj);
3086                                 kobject_put(kobj);
3087                         }
3088                         del_gendisk(dd->disk);
3089                         dd->disk = NULL;
3090                 }
3091                 if (dd->queue) {
3092                         dd->queue->queuedata = NULL;
3093                         blk_cleanup_queue(dd->queue);
3094                         dd->queue = NULL;
3095                 }
3096         }
3097         kfree(dd);
3098         return 0;
3099 }
3100
3101 /*
3102  * Perform any init/resume time hardware setup
3103  *
3104  * @dd Pointer to the driver data structure.
3105  *
3106  * return value
3107  *      None
3108  */
3109 static inline void hba_setup(struct driver_data *dd)
3110 {
3111         u32 hwdata;
3112         hwdata = readl(dd->mmio + HOST_HSORG);
3113
3114         /* interrupt bug workaround: use only 1 IS bit.*/
3115         writel(hwdata |
3116                 HSORG_DISABLE_SLOTGRP_INTR |
3117                 HSORG_DISABLE_SLOTGRP_PXIS,
3118                 dd->mmio + HOST_HSORG);
3119 }
3120
3121 static int mtip_device_unaligned_constrained(struct driver_data *dd)
3122 {
3123         return (dd->pdev->device == P420M_DEVICE_ID ? 1 : 0);
3124 }
3125
3126 /*
3127  * Detect the details of the product, and store anything needed
3128  * into the driver data structure.  This includes product type and
3129  * version and number of slot groups.
3130  *
3131  * @dd Pointer to the driver data structure.
3132  *
3133  * return value
3134  *      None
3135  */
3136 static void mtip_detect_product(struct driver_data *dd)
3137 {
3138         u32 hwdata;
3139         unsigned int rev, slotgroups;
3140
3141         /*
3142          * HBA base + 0xFC [15:0] - vendor-specific hardware interface
3143          * info register:
3144          * [15:8] hardware/software interface rev#
3145          * [   3] asic-style interface
3146          * [ 2:0] number of slot groups, minus 1 (only valid for asic-style).
3147          */
3148         hwdata = readl(dd->mmio + HOST_HSORG);
3149
3150         dd->product_type = MTIP_PRODUCT_UNKNOWN;
3151         dd->slot_groups = 1;
3152
3153         if (hwdata & 0x8) {
3154                 dd->product_type = MTIP_PRODUCT_ASICFPGA;
3155                 rev = (hwdata & HSORG_HWREV) >> 8;
3156                 slotgroups = (hwdata & HSORG_SLOTGROUPS) + 1;
3157                 dev_info(&dd->pdev->dev,
3158                         "ASIC-FPGA design, HS rev 0x%x, "
3159                         "%i slot groups [%i slots]\n",
3160                          rev,
3161                          slotgroups,
3162                          slotgroups * 32);
3163
3164                 if (slotgroups > MTIP_MAX_SLOT_GROUPS) {
3165                         dev_warn(&dd->pdev->dev,
3166                                 "Warning: driver only supports "
3167                                 "%i slot groups.\n", MTIP_MAX_SLOT_GROUPS);
3168                         slotgroups = MTIP_MAX_SLOT_GROUPS;
3169                 }
3170                 dd->slot_groups = slotgroups;
3171                 return;
3172         }
3173
3174         dev_warn(&dd->pdev->dev, "Unrecognized product id\n");
3175 }
3176
3177 /*
3178  * Blocking wait for FTL rebuild to complete
3179  *
3180  * @dd Pointer to the DRIVER_DATA structure.
3181  *
3182  * return value
3183  *      0       FTL rebuild completed successfully
3184  *      -EFAULT FTL rebuild error/timeout/interruption
3185  */
3186 static int mtip_ftl_rebuild_poll(struct driver_data *dd)
3187 {
3188         unsigned long timeout, cnt = 0, start;
3189
3190         dev_warn(&dd->pdev->dev,
3191                 "FTL rebuild in progress. Polling for completion.\n");
3192
3193         start = jiffies;
3194         timeout = jiffies + msecs_to_jiffies(MTIP_FTL_REBUILD_TIMEOUT_MS);
3195
3196         do {
3197                 if (unlikely(test_bit(MTIP_DDF_REMOVE_PENDING_BIT,
3198                                 &dd->dd_flag)))
3199                         return -EFAULT;
3200                 if (mtip_check_surprise_removal(dd->pdev))
3201                         return -EFAULT;
3202
3203                 if (mtip_get_identify(dd->port, NULL) < 0)
3204                         return -EFAULT;
3205
3206                 if (*(dd->port->identify + MTIP_FTL_REBUILD_OFFSET) ==
3207                         MTIP_FTL_REBUILD_MAGIC) {
3208                         ssleep(1);
3209                         /* Print message every 3 minutes */
3210                         if (cnt++ >= 180) {
3211                                 dev_warn(&dd->pdev->dev,
3212                                 "FTL rebuild in progress (%d secs).\n",
3213                                 jiffies_to_msecs(jiffies - start) / 1000);
3214                                 cnt = 0;
3215                         }
3216                 } else {
3217                         dev_warn(&dd->pdev->dev,
3218                                 "FTL rebuild complete (%d secs).\n",
3219                         jiffies_to_msecs(jiffies - start) / 1000);
3220                         mtip_block_initialize(dd);
3221                         return 0;
3222                 }
3223                 ssleep(10);
3224         } while (time_before(jiffies, timeout));
3225
3226         /* Check for timeout */
3227         dev_err(&dd->pdev->dev,
3228                 "Timed out waiting for FTL rebuild to complete (%d secs).\n",
3229                 jiffies_to_msecs(jiffies - start) / 1000);
3230         return -EFAULT;
3231 }
3232
3233 /*
3234  * service thread to issue queued commands
3235  *
3236  * @data Pointer to the driver data structure.
3237  *
3238  * return value
3239  *      0
3240  */
3241
3242 static int mtip_service_thread(void *data)
3243 {
3244         struct driver_data *dd = (struct driver_data *)data;
3245         unsigned long slot, slot_start, slot_wrap;
3246         unsigned int num_cmd_slots = dd->slot_groups * 32;
3247         struct mtip_port *port = dd->port;
3248         int ret;
3249
3250         while (1) {
3251                 /*
3252                  * the condition is to check neither an internal command is
3253                  * is in progress nor error handling is active
3254                  */
3255                 wait_event_interruptible(port->svc_wait, (port->flags) &&
3256                         !(port->flags & MTIP_PF_PAUSE_IO));
3257
3258                 if (kthread_should_stop())
3259                         goto st_out;
3260
3261                 set_bit(MTIP_PF_SVC_THD_ACTIVE_BIT, &port->flags);
3262
3263                 /* If I am an orphan, start self cleanup */
3264                 if (test_bit(MTIP_PF_SR_CLEANUP_BIT, &port->flags))
3265                         break;
3266
3267                 if (unlikely(test_bit(MTIP_DDF_REMOVE_PENDING_BIT,
3268                                 &dd->dd_flag)))
3269                         goto st_out;
3270
3271                 if (test_bit(MTIP_PF_ISSUE_CMDS_BIT, &port->flags)) {
3272                         slot = 1;
3273                         /* used to restrict the loop to one iteration */
3274                         slot_start = num_cmd_slots;
3275                         slot_wrap = 0;
3276                         while (1) {
3277                                 slot = find_next_bit(port->cmds_to_issue,
3278                                                 num_cmd_slots, slot);
3279                                 if (slot_wrap == 1) {
3280                                         if ((slot_start >= slot) ||
3281                                                 (slot >= num_cmd_slots))
3282                                                 break;
3283                                 }
3284                                 if (unlikely(slot_start == num_cmd_slots))
3285                                         slot_start = slot;
3286
3287                                 if (unlikely(slot == num_cmd_slots)) {
3288                                         slot = 1;
3289                                         slot_wrap = 1;
3290                                         continue;
3291                                 }
3292
3293                                 /* Issue the command to the hardware */
3294                                 mtip_issue_ncq_command(port, slot);
3295
3296                                 clear_bit(slot, port->cmds_to_issue);
3297                         }
3298
3299                         clear_bit(MTIP_PF_ISSUE_CMDS_BIT, &port->flags);
3300                 } else if (test_bit(MTIP_PF_REBUILD_BIT, &port->flags)) {
3301                         if (mtip_ftl_rebuild_poll(dd) < 0)
3302                                 set_bit(MTIP_DDF_REBUILD_FAILED_BIT,
3303                                                         &dd->dd_flag);
3304                         clear_bit(MTIP_PF_REBUILD_BIT, &port->flags);
3305                 }
3306                 clear_bit(MTIP_PF_SVC_THD_ACTIVE_BIT, &port->flags);
3307
3308                 if (test_bit(MTIP_PF_SVC_THD_STOP_BIT, &port->flags))
3309                         goto st_out;
3310         }
3311
3312         /* wait for pci remove to exit */
3313         while (1) {
3314                 if (test_bit(MTIP_DDF_REMOVE_DONE_BIT, &dd->dd_flag))
3315                         break;
3316                 msleep_interruptible(1000);
3317                 if (kthread_should_stop())
3318                         goto st_out;
3319         }
3320
3321         while (1) {
3322                 ret = mtip_free_orphan(dd);
3323                 if (!ret) {
3324                         /* NOTE: All data structures are invalid, do not
3325                          * access any here */
3326                         return 0;
3327                 }
3328                 msleep_interruptible(1000);
3329                 if (kthread_should_stop())
3330                         goto st_out;
3331         }
3332 st_out:
3333         return 0;
3334 }
3335
3336 /*
3337  * DMA region teardown
3338  *
3339  * @dd Pointer to driver_data structure
3340  *
3341  * return value
3342  *      None
3343  */
3344 static void mtip_dma_free(struct driver_data *dd)
3345 {
3346         int i;
3347         struct mtip_port *port = dd->port;
3348
3349         if (port->block1)
3350                 dmam_free_coherent(&dd->pdev->dev, BLOCK_DMA_ALLOC_SZ,
3351                                         port->block1, port->block1_dma);
3352
3353         if (port->command_list) {
3354                 dmam_free_coherent(&dd->pdev->dev, AHCI_CMD_TBL_SZ,
3355                                 port->command_list, port->command_list_dma);
3356         }
3357
3358         for (i = 0; i < MTIP_MAX_COMMAND_SLOTS; i++) {
3359                 if (port->commands[i].command)
3360                         dmam_free_coherent(&dd->pdev->dev, CMD_DMA_ALLOC_SZ,
3361                                 port->commands[i].command,
3362                                 port->commands[i].command_dma);
3363         }
3364 }
3365
3366 /*
3367  * DMA region setup
3368  *
3369  * @dd Pointer to driver_data structure
3370  *
3371  * return value
3372  *      -ENOMEM Not enough free DMA region space to initialize driver
3373  */
3374 static int mtip_dma_alloc(struct driver_data *dd)
3375 {
3376         struct mtip_port *port = dd->port;
3377         int i, rv = 0;
3378         u32 host_cap_64 = readl(dd->mmio + HOST_CAP) & HOST_CAP_64;
3379
3380         /* Allocate dma memory for RX Fis, Identify, and Sector Bufffer */
3381         port->block1 =
3382                 dmam_alloc_coherent(&dd->pdev->dev, BLOCK_DMA_ALLOC_SZ,
3383                                         &port->block1_dma, GFP_KERNEL);
3384         if (!port->block1)
3385                 return -ENOMEM;
3386         memset(port->block1, 0, BLOCK_DMA_ALLOC_SZ);
3387
3388         /* Allocate dma memory for command list */
3389         port->command_list =
3390                 dmam_alloc_coherent(&dd->pdev->dev, AHCI_CMD_TBL_SZ,
3391                                         &port->command_list_dma, GFP_KERNEL);
3392         if (!port->command_list) {
3393                 dmam_free_coherent(&dd->pdev->dev, BLOCK_DMA_ALLOC_SZ,
3394                                         port->block1, port->block1_dma);
3395                 port->block1 = NULL;
3396                 port->block1_dma = 0;
3397                 return -ENOMEM;
3398         }
3399         memset(port->command_list, 0, AHCI_CMD_TBL_SZ);
3400
3401         /* Setup all pointers into first DMA region */
3402         port->rxfis         = port->block1 + AHCI_RX_FIS_OFFSET;
3403         port->rxfis_dma     = port->block1_dma + AHCI_RX_FIS_OFFSET;
3404         port->identify      = port->block1 + AHCI_IDFY_OFFSET;
3405         port->identify_dma  = port->block1_dma + AHCI_IDFY_OFFSET;
3406         port->log_buf       = port->block1 + AHCI_SECTBUF_OFFSET;
3407         port->log_buf_dma   = port->block1_dma + AHCI_SECTBUF_OFFSET;
3408         port->smart_buf     = port->block1 + AHCI_SMARTBUF_OFFSET;
3409         port->smart_buf_dma = port->block1_dma + AHCI_SMARTBUF_OFFSET;
3410
3411         /* Setup per command SGL DMA region */
3412
3413         /* Point the command headers at the command tables */
3414         for (i = 0; i < MTIP_MAX_COMMAND_SLOTS; i++) {
3415                 port->commands[i].command =
3416                         dmam_alloc_coherent(&dd->pdev->dev, CMD_DMA_ALLOC_SZ,
3417                                 &port->commands[i].command_dma, GFP_KERNEL);
3418                 if (!port->commands[i].command) {
3419                         rv = -ENOMEM;
3420                         mtip_dma_free(dd);
3421                         return rv;
3422                 }
3423                 memset(port->commands[i].command, 0, CMD_DMA_ALLOC_SZ);
3424
3425                 port->commands[i].command_header = port->command_list +
3426                                         (sizeof(struct mtip_cmd_hdr) * i);
3427                 port->commands[i].command_header_dma =
3428                                         dd->port->command_list_dma +
3429                                         (sizeof(struct mtip_cmd_hdr) * i);
3430
3431                 if (host_cap_64)
3432                         port->commands[i].command_header->ctbau =
3433                                 __force_bit2int cpu_to_le32(
3434                                 (port->commands[i].command_dma >> 16) >> 16);
3435
3436                 port->commands[i].command_header->ctba =
3437                                 __force_bit2int cpu_to_le32(
3438                                 port->commands[i].command_dma & 0xFFFFFFFF);
3439
3440                 sg_init_table(port->commands[i].sg, MTIP_MAX_SG);
3441
3442                 /* Mark command as currently inactive */
3443                 atomic_set(&dd->port->commands[i].active, 0);
3444         }
3445         return 0;
3446 }
3447
3448 /*
3449  * Called once for each card.
3450  *
3451  * @dd Pointer to the driver data structure.
3452  *
3453  * return value
3454  *      0 on success, else an error code.
3455  */
3456 static int mtip_hw_init(struct driver_data *dd)
3457 {
3458         int i;
3459         int rv;
3460         unsigned int num_command_slots;
3461         unsigned long timeout, timetaken;
3462         unsigned char *buf;
3463         struct smart_attr attr242;
3464
3465         dd->mmio = pcim_iomap_table(dd->pdev)[MTIP_ABAR];
3466
3467         mtip_detect_product(dd);
3468         if (dd->product_type == MTIP_PRODUCT_UNKNOWN) {
3469                 rv = -EIO;
3470                 goto out1;
3471         }
3472         num_command_slots = dd->slot_groups * 32;
3473
3474         hba_setup(dd);
3475
3476         dd->port = kzalloc_node(sizeof(struct mtip_port), GFP_KERNEL,
3477                                 dd->numa_node);
3478         if (!dd->port) {
3479                 dev_err(&dd->pdev->dev,
3480                         "Memory allocation: port structure\n");
3481                 return -ENOMEM;
3482         }
3483
3484         /* Continue workqueue setup */
3485         for (i = 0; i < MTIP_MAX_SLOT_GROUPS; i++)
3486                 dd->work[i].port = dd->port;
3487
3488         /* Enable unaligned IO constraints for some devices */
3489         if (mtip_device_unaligned_constrained(dd))
3490                 dd->unal_qdepth = MTIP_MAX_UNALIGNED_SLOTS;
3491         else
3492                 dd->unal_qdepth = 0;
3493
3494         /* Counting semaphore to track command slot usage */
3495         sema_init(&dd->port->cmd_slot, num_command_slots - 1 - dd->unal_qdepth);
3496         sema_init(&dd->port->cmd_slot_unal, dd->unal_qdepth);
3497
3498         /* Spinlock to prevent concurrent issue */
3499         for (i = 0; i < MTIP_MAX_SLOT_GROUPS; i++)
3500                 spin_lock_init(&dd->port->cmd_issue_lock[i]);
3501
3502         /* Set the port mmio base address. */
3503         dd->port->mmio  = dd->mmio + PORT_OFFSET;
3504         dd->port->dd    = dd;
3505
3506         /* DMA allocations */
3507         rv = mtip_dma_alloc(dd);
3508         if (rv < 0)
3509                 goto out1;
3510
3511         /* Setup the pointers to the extended s_active and CI registers. */
3512         for (i = 0; i < dd->slot_groups; i++) {
3513                 dd->port->s_active[i] =
3514                         dd->port->mmio + i*0x80 + PORT_SCR_ACT;
3515                 dd->port->cmd_issue[i] =
3516                         dd->port->mmio + i*0x80 + PORT_COMMAND_ISSUE;
3517                 dd->port->completed[i] =
3518                         dd->port->mmio + i*0x80 + PORT_SDBV;
3519         }
3520
3521         timetaken = jiffies;
3522         timeout = jiffies + msecs_to_jiffies(30000);
3523         while (((readl(dd->port->mmio + PORT_SCR_STAT) & 0x0F) != 0x03) &&
3524                  time_before(jiffies, timeout)) {
3525                 mdelay(100);
3526         }
3527         if (unlikely(mtip_check_surprise_removal(dd->pdev))) {
3528                 timetaken = jiffies - timetaken;
3529                 dev_warn(&dd->pdev->dev,
3530                         "Surprise removal detected at %u ms\n",
3531                         jiffies_to_msecs(timetaken));
3532                 rv = -ENODEV;
3533                 goto out2 ;
3534         }
3535         if (unlikely(test_bit(MTIP_DDF_REMOVE_PENDING_BIT, &dd->dd_flag))) {
3536                 timetaken = jiffies - timetaken;
3537                 dev_warn(&dd->pdev->dev,
3538                         "Removal detected at %u ms\n",
3539                         jiffies_to_msecs(timetaken));
3540                 rv = -EFAULT;
3541                 goto out2;
3542         }
3543
3544         /* Conditionally reset the HBA. */
3545         if (!(readl(dd->mmio + HOST_CAP) & HOST_CAP_NZDMA)) {
3546                 if (mtip_hba_reset(dd) < 0) {
3547                         dev_err(&dd->pdev->dev,
3548                                 "Card did not reset within timeout\n");
3549                         rv = -EIO;
3550                         goto out2;
3551                 }
3552         } else {
3553                 /* Clear any pending interrupts on the HBA */
3554                 writel(readl(dd->mmio + HOST_IRQ_STAT),
3555                         dd->mmio + HOST_IRQ_STAT);
3556         }
3557
3558         mtip_init_port(dd->port);
3559         mtip_start_port(dd->port);
3560
3561         /* Setup the ISR and enable interrupts. */
3562         rv = devm_request_irq(&dd->pdev->dev,
3563                                 dd->pdev->irq,
3564                                 mtip_irq_handler,
3565                                 IRQF_SHARED,
3566                                 dev_driver_string(&dd->pdev->dev),
3567                                 dd);
3568
3569         if (rv) {
3570                 dev_err(&dd->pdev->dev,
3571                         "Unable to allocate IRQ %d\n", dd->pdev->irq);
3572                 goto out2;
3573         }
3574         irq_set_affinity_hint(dd->pdev->irq, get_cpu_mask(dd->isr_binding));
3575
3576         /* Enable interrupts on the HBA. */
3577         writel(readl(dd->mmio + HOST_CTL) | HOST_IRQ_EN,
3578                                         dd->mmio + HOST_CTL);
3579
3580         init_timer(&dd->port->cmd_timer);
3581         init_waitqueue_head(&dd->port->svc_wait);
3582
3583         dd->port->cmd_timer.data = (unsigned long int) dd->port;
3584         dd->port->cmd_timer.function = mtip_timeout_function;
3585         mod_timer(&dd->port->cmd_timer,
3586                 jiffies + msecs_to_jiffies(MTIP_TIMEOUT_CHECK_PERIOD));
3587
3588
3589         if (test_bit(MTIP_DDF_REMOVE_PENDING_BIT, &dd->dd_flag)) {
3590                 rv = -EFAULT;
3591                 goto out3;
3592         }
3593
3594         if (mtip_get_identify(dd->port, NULL) < 0) {
3595                 rv = -EFAULT;
3596                 goto out3;
3597         }
3598         mtip_dump_identify(dd->port);
3599
3600         if (*(dd->port->identify + MTIP_FTL_REBUILD_OFFSET) ==
3601                 MTIP_FTL_REBUILD_MAGIC) {
3602                 set_bit(MTIP_PF_REBUILD_BIT, &dd->port->flags);
3603                 return MTIP_FTL_REBUILD_MAGIC;
3604         }
3605
3606         /* check write protect, over temp and rebuild statuses */
3607         rv = mtip_read_log_page(dd->port, ATA_LOG_SATA_NCQ,
3608                                 dd->port->log_buf,
3609                                 dd->port->log_buf_dma, 1);
3610         if (rv) {
3611                 dev_warn(&dd->pdev->dev,
3612                         "Error in READ LOG EXT (10h) command\n");
3613                 /* non-critical error, don't fail the load */
3614         } else {
3615                 buf = (unsigned char *)dd->port->log_buf;
3616                 if (buf[259] & 0x1) {
3617                         dev_info(&dd->pdev->dev,
3618                                 "Write protect bit is set.\n");
3619                         set_bit(MTIP_DDF_WRITE_PROTECT_BIT, &dd->dd_flag);
3620                 }
3621                 if (buf[288] == 0xF7) {
3622                         dev_info(&dd->pdev->dev,
3623                                 "Exceeded Tmax, drive in thermal shutdown.\n");
3624                         set_bit(MTIP_DDF_OVER_TEMP_BIT, &dd->dd_flag);
3625                 }
3626                 if (buf[288] == 0xBF) {
3627                         dev_info(&dd->pdev->dev,
3628                                 "Drive is in security locked state.\n");
3629                         set_bit(MTIP_DDF_SEC_LOCK_BIT, &dd->dd_flag);
3630                 }
3631         }
3632
3633         /* get write protect progess */
3634         memset(&attr242, 0, sizeof(struct smart_attr));
3635         if (mtip_get_smart_attr(dd->port, 242, &attr242))
3636                 dev_warn(&dd->pdev->dev,
3637                                 "Unable to check write protect progress\n");
3638         else
3639                 dev_info(&dd->pdev->dev,
3640                                 "Write protect progress: %u%% (%u blocks)\n",
3641                                 attr242.cur, le32_to_cpu(attr242.data));
3642         return rv;
3643
3644 out3:
3645         del_timer_sync(&dd->port->cmd_timer);
3646
3647         /* Disable interrupts on the HBA. */
3648         writel(readl(dd->mmio + HOST_CTL) & ~HOST_IRQ_EN,
3649                         dd->mmio + HOST_CTL);
3650
3651         /* Release the IRQ. */
3652         irq_set_affinity_hint(dd->pdev->irq, NULL);
3653         devm_free_irq(&dd->pdev->dev, dd->pdev->irq, dd);
3654
3655 out2:
3656         mtip_deinit_port(dd->port);
3657         mtip_dma_free(dd);
3658
3659 out1:
3660         /* Free the memory allocated for the for structure. */
3661         kfree(dd->port);
3662
3663         return rv;
3664 }
3665
3666 /*
3667  * Called to deinitialize an interface.
3668  *
3669  * @dd Pointer to the driver data structure.
3670  *
3671  * return value
3672  *      0
3673  */
3674 static int mtip_hw_exit(struct driver_data *dd)
3675 {
3676         /*
3677          * Send standby immediate (E0h) to the drive so that it
3678          * saves its state.
3679          */
3680         if (!dd->sr) {
3681                 if (!test_bit(MTIP_DDF_REBUILD_FAILED_BIT, &dd->dd_flag))
3682                         if (mtip_standby_immediate(dd->port))
3683                                 dev_warn(&dd->pdev->dev,
3684                                         "STANDBY IMMEDIATE failed\n");
3685
3686                 /* de-initialize the port. */
3687                 mtip_deinit_port(dd->port);
3688
3689                 /* Disable interrupts on the HBA. */
3690                 writel(readl(dd->mmio + HOST_CTL) & ~HOST_IRQ_EN,
3691                                 dd->mmio + HOST_CTL);
3692         }
3693
3694         del_timer_sync(&dd->port->cmd_timer);
3695
3696         /* Release the IRQ. */
3697         irq_set_affinity_hint(dd->pdev->irq, NULL);
3698         devm_free_irq(&dd->pdev->dev, dd->pdev->irq, dd);
3699
3700         /* Free dma regions */
3701         mtip_dma_free(dd);
3702
3703         /* Free the memory allocated for the for structure. */
3704         kfree(dd->port);
3705         dd->port = NULL;
3706
3707         return 0;
3708 }
3709
3710 /*
3711  * Issue a Standby Immediate command to the device.
3712  *
3713  * This function is called by the Block Layer just before the
3714  * system powers off during a shutdown.
3715  *
3716  * @dd Pointer to the driver data structure.
3717  *
3718  * return value
3719  *      0
3720  */
3721 static int mtip_hw_shutdown(struct driver_data *dd)
3722 {
3723         /*
3724          * Send standby immediate (E0h) to the drive so that it
3725          * saves its state.
3726          */
3727         if (!dd->sr && dd->port)
3728                 mtip_standby_immediate(dd->port);
3729
3730         return 0;
3731 }
3732
3733 /*
3734  * Suspend function
3735  *
3736  * This function is called by the Block Layer just before the
3737  * system hibernates.
3738  *
3739  * @dd Pointer to the driver data structure.
3740  *
3741  * return value
3742  *      0       Suspend was successful
3743  *      -EFAULT Suspend was not successful
3744  */
3745 static int mtip_hw_suspend(struct driver_data *dd)
3746 {
3747         /*
3748          * Send standby immediate (E0h) to the drive
3749          * so that it saves its state.
3750          */
3751         if (mtip_standby_immediate(dd->port) != 0) {
3752                 dev_err(&dd->pdev->dev,
3753                         "Failed standby-immediate command\n");
3754                 return -EFAULT;
3755         }
3756
3757         /* Disable interrupts on the HBA.*/
3758         writel(readl(dd->mmio + HOST_CTL) & ~HOST_IRQ_EN,
3759                         dd->mmio + HOST_CTL);
3760         mtip_deinit_port(dd->port);
3761
3762         return 0;
3763 }
3764
3765 /*
3766  * Resume function
3767  *
3768  * This function is called by the Block Layer as the
3769  * system resumes.
3770  *
3771  * @dd Pointer to the driver data structure.
3772  *
3773  * return value
3774  *      0       Resume was successful
3775  *      -EFAULT Resume was not successful
3776  */
3777 static int mtip_hw_resume(struct driver_data *dd)
3778 {
3779         /* Perform any needed hardware setup steps */
3780         hba_setup(dd);
3781
3782         /* Reset the HBA */
3783         if (mtip_hba_reset(dd) != 0) {
3784                 dev_err(&dd->pdev->dev,
3785                         "Unable to reset the HBA\n");
3786                 return -EFAULT;
3787         }
3788
3789         /*
3790          * Enable the port, DMA engine, and FIS reception specific
3791          * h/w in controller.
3792          */
3793         mtip_init_port(dd->port);
3794         mtip_start_port(dd->port);
3795
3796         /* Enable interrupts on the HBA.*/
3797         writel(readl(dd->mmio + HOST_CTL) | HOST_IRQ_EN,
3798                         dd->mmio + HOST_CTL);
3799
3800         return 0;
3801 }
3802
3803 /*
3804  * Helper function for reusing disk name
3805  * upon hot insertion.
3806  */
3807 static int rssd_disk_name_format(char *prefix,
3808                                  int index,
3809                                  char *buf,
3810                                  int buflen)
3811 {
3812         const int base = 'z' - 'a' + 1;
3813         char *begin = buf + strlen(prefix);
3814         char *end = buf + buflen;
3815         char *p;
3816         int unit;
3817
3818         p = end - 1;
3819         *p = '\0';
3820         unit = base;
3821         do {
3822                 if (p == begin)
3823                         return -EINVAL;
3824                 *--p = 'a' + (index % unit);
3825                 index = (index / unit) - 1;
3826         } while (index >= 0);
3827
3828         memmove(begin, p, end - p);
3829         memcpy(buf, prefix, strlen(prefix));
3830
3831         return 0;
3832 }
3833
3834 /*
3835  * Block layer IOCTL handler.
3836  *
3837  * @dev Pointer to the block_device structure.
3838  * @mode ignored
3839  * @cmd IOCTL command passed from the user application.
3840  * @arg Argument passed from the user application.
3841  *
3842  * return value
3843  *      0        IOCTL completed successfully.
3844  *      -ENOTTY  IOCTL not supported or invalid driver data
3845  *                 structure pointer.
3846  */
3847 static int mtip_block_ioctl(struct block_device *dev,
3848                             fmode_t mode,
3849                             unsigned cmd,
3850                             unsigned long arg)
3851 {
3852         struct driver_data *dd = dev->bd_disk->private_data;
3853
3854         if (!capable(CAP_SYS_ADMIN))
3855                 return -EACCES;
3856
3857         if (!dd)
3858                 return -ENOTTY;
3859
3860         if (unlikely(test_bit(MTIP_DDF_REMOVE_PENDING_BIT, &dd->dd_flag)))
3861                 return -ENOTTY;
3862
3863         switch (cmd) {
3864         case BLKFLSBUF:
3865                 return -ENOTTY;
3866         default:
3867                 return mtip_hw_ioctl(dd, cmd, arg);
3868         }
3869 }
3870
3871 #ifdef CONFIG_COMPAT
3872 /*
3873  * Block layer compat IOCTL handler.
3874  *
3875  * @dev Pointer to the block_device structure.
3876  * @mode ignored
3877  * @cmd IOCTL command passed from the user application.
3878  * @arg Argument passed from the user application.
3879  *
3880  * return value
3881  *      0        IOCTL completed successfully.
3882  *      -ENOTTY  IOCTL not supported or invalid driver data
3883  *                 structure pointer.
3884  */
3885 static int mtip_block_compat_ioctl(struct block_device *dev,
3886                             fmode_t mode,
3887                             unsigned cmd,
3888                             unsigned long arg)
3889 {
3890         struct driver_data *dd = dev->bd_disk->private_data;
3891
3892         if (!capable(CAP_SYS_ADMIN))
3893                 return -EACCES;
3894
3895         if (!dd)
3896                 return -ENOTTY;
3897
3898         if (unlikely(test_bit(MTIP_DDF_REMOVE_PENDING_BIT, &dd->dd_flag)))
3899                 return -ENOTTY;
3900
3901         switch (cmd) {
3902         case BLKFLSBUF:
3903                 return -ENOTTY;
3904         case HDIO_DRIVE_TASKFILE: {
3905                 struct mtip_compat_ide_task_request_s __user *compat_req_task;
3906                 ide_task_request_t req_task;
3907                 int compat_tasksize, outtotal, ret;
3908
3909                 compat_tasksize =
3910                         sizeof(struct mtip_compat_ide_task_request_s);
3911
3912                 compat_req_task =
3913                         (struct mtip_compat_ide_task_request_s __user *) arg;
3914
3915                 if (copy_from_user(&req_task, (void __user *) arg,
3916                         compat_tasksize - (2 * sizeof(compat_long_t))))
3917                         return -EFAULT;
3918
3919                 if (get_user(req_task.out_size, &compat_req_task->out_size))
3920                         return -EFAULT;
3921
3922                 if (get_user(req_task.in_size, &compat_req_task->in_size))
3923                         return -EFAULT;
3924
3925                 outtotal = sizeof(struct mtip_compat_ide_task_request_s);
3926
3927                 ret = exec_drive_taskfile(dd, (void __user *) arg,
3928                                                 &req_task, outtotal);
3929
3930                 if (copy_to_user((void __user *) arg, &req_task,
3931                                 compat_tasksize -
3932                                 (2 * sizeof(compat_long_t))))
3933                         return -EFAULT;
3934
3935                 if (put_user(req_task.out_size, &compat_req_task->out_size))
3936                         return -EFAULT;
3937
3938                 if (put_user(req_task.in_size, &compat_req_task->in_size))
3939                         return -EFAULT;
3940
3941                 return ret;
3942         }
3943         default:
3944                 return mtip_hw_ioctl(dd, cmd, arg);
3945         }
3946 }
3947 #endif
3948
3949 /*
3950  * Obtain the geometry of the device.
3951  *
3952  * You may think that this function is obsolete, but some applications,
3953  * fdisk for example still used CHS values. This function describes the
3954  * device as having 224 heads and 56 sectors per cylinder. These values are
3955  * chosen so that each cylinder is aligned on a 4KB boundary. Since a
3956  * partition is described in terms of a start and end cylinder this means
3957  * that each partition is also 4KB aligned. Non-aligned partitions adversely
3958  * affects performance.
3959  *
3960  * @dev Pointer to the block_device strucutre.
3961  * @geo Pointer to a hd_geometry structure.
3962  *
3963  * return value
3964  *      0       Operation completed successfully.
3965  *      -ENOTTY An error occurred while reading the drive capacity.
3966  */
3967 static int mtip_block_getgeo(struct block_device *dev,
3968                                 struct hd_geometry *geo)
3969 {
3970         struct driver_data *dd = dev->bd_disk->private_data;
3971         sector_t capacity;
3972
3973         if (!dd)
3974                 return -ENOTTY;
3975
3976         if (!(mtip_hw_get_capacity(dd, &capacity))) {
3977                 dev_warn(&dd->pdev->dev,
3978                         "Could not get drive capacity.\n");
3979                 return -ENOTTY;
3980         }
3981
3982         geo->heads = 224;
3983         geo->sectors = 56;
3984         sector_div(capacity, (geo->heads * geo->sectors));
3985         geo->cylinders = capacity;
3986         return 0;
3987 }
3988
3989 /*
3990  * Block device operation function.
3991  *
3992  * This structure contains pointers to the functions required by the block
3993  * layer.
3994  */
3995 static const struct block_device_operations mtip_block_ops = {
3996         .ioctl          = mtip_block_ioctl,
3997 #ifdef CONFIG_COMPAT
3998         .compat_ioctl   = mtip_block_compat_ioctl,
3999 #endif
4000         .getgeo         = mtip_block_getgeo,
4001         .owner          = THIS_MODULE
4002 };
4003
4004 /*
4005  * Block layer make request function.
4006  *
4007  * This function is called by the kernel to process a BIO for
4008  * the P320 device.
4009  *
4010  * @queue Pointer to the request queue. Unused other than to obtain
4011  *              the driver data structure.
4012  * @bio   Pointer to the BIO.
4013  *
4014  */
4015 static void mtip_make_request(struct request_queue *queue, struct bio *bio)
4016 {
4017         struct driver_data *dd = queue->queuedata;
4018         struct scatterlist *sg;
4019         struct bio_vec bvec;
4020         struct bvec_iter iter;
4021         int nents = 0;
4022         int tag = 0, unaligned = 0;
4023
4024         if (unlikely(dd->dd_flag & MTIP_DDF_STOP_IO)) {
4025                 if (unlikely(test_bit(MTIP_DDF_REMOVE_PENDING_BIT,
4026                                                         &dd->dd_flag))) {
4027                         bio_endio(bio, -ENXIO);
4028                         return;
4029                 }
4030                 if (unlikely(test_bit(MTIP_DDF_OVER_TEMP_BIT, &dd->dd_flag))) {
4031                         bio_endio(bio, -ENODATA);
4032                         return;
4033                 }
4034                 if (unlikely(test_bit(MTIP_DDF_WRITE_PROTECT_BIT,
4035                                                         &dd->dd_flag) &&
4036                                 bio_data_dir(bio))) {
4037                         bio_endio(bio, -ENODATA);
4038                         return;
4039                 }
4040                 if (unlikely(test_bit(MTIP_DDF_SEC_LOCK_BIT, &dd->dd_flag))) {
4041                         bio_endio(bio, -ENODATA);
4042                         return;
4043                 }
4044                 if (test_bit(MTIP_DDF_REBUILD_FAILED_BIT, &dd->dd_flag)) {
4045                         bio_endio(bio, -ENXIO);
4046                         return;
4047                 }
4048         }
4049
4050         if (unlikely(bio->bi_rw & REQ_DISCARD)) {
4051                 bio_endio(bio, mtip_send_trim(dd, bio->bi_iter.bi_sector,
4052                                                 bio_sectors(bio)));
4053                 return;
4054         }
4055
4056         if (unlikely(!bio_has_data(bio))) {
4057                 blk_queue_flush(queue, 0);
4058                 bio_endio(bio, 0);
4059                 return;
4060         }
4061
4062         if (bio_data_dir(bio) == WRITE && bio_sectors(bio) <= 64 &&
4063                                                         dd->unal_qdepth) {
4064                 if (bio->bi_iter.bi_sector % 8 != 0)
4065                         /* Unaligned on 4k boundaries */
4066                         unaligned = 1;
4067                 else if (bio_sectors(bio) % 8 != 0) /* Aligned but not 4k/8k */
4068                         unaligned = 1;
4069         }
4070
4071         sg = mtip_hw_get_scatterlist(dd, &tag, unaligned);
4072         if (likely(sg != NULL)) {
4073                 blk_queue_bounce(queue, &bio);
4074
4075                 if (unlikely((bio)->bi_vcnt > MTIP_MAX_SG)) {
4076                         dev_warn(&dd->pdev->dev,
4077                                 "Maximum number of SGL entries exceeded\n");
4078                         bio_io_error(bio);
4079                         mtip_hw_release_scatterlist(dd, tag, unaligned);
4080                         return;
4081                 }
4082
4083                 /* Create the scatter list for this bio. */
4084                 bio_for_each_segment(bvec, bio, iter) {
4085                         sg_set_page(&sg[nents],
4086                                         bvec.bv_page,
4087                                         bvec.bv_len,
4088                                         bvec.bv_offset);
4089                         nents++;
4090                 }
4091
4092                 /* Issue the read/write. */
4093                 mtip_hw_submit_io(dd,
4094                                 bio->bi_iter.bi_sector,
4095                                 bio_sectors(bio),
4096                                 nents,
4097                                 tag,
4098                                 bio_endio,
4099                                 bio,
4100                                 bio_data_dir(bio),
4101                                 unaligned);
4102         } else
4103                 bio_io_error(bio);
4104 }
4105
4106 /*
4107  * Block layer initialization function.
4108  *
4109  * This function is called once by the PCI layer for each P320
4110  * device that is connected to the system.
4111  *
4112  * @dd Pointer to the driver data structure.
4113  *
4114  * return value
4115  *      0 on success else an error code.
4116  */
4117 static int mtip_block_initialize(struct driver_data *dd)
4118 {
4119         int rv = 0, wait_for_rebuild = 0;
4120         sector_t capacity;
4121         unsigned int index = 0;
4122         struct kobject *kobj;
4123         unsigned char thd_name[16];
4124
4125         if (dd->disk)
4126                 goto skip_create_disk; /* hw init done, before rebuild */
4127
4128         /* Initialize the protocol layer. */
4129         wait_for_rebuild = mtip_hw_init(dd);
4130         if (wait_for_rebuild < 0) {
4131                 dev_err(&dd->pdev->dev,
4132                         "Protocol layer initialization failed\n");
4133                 rv = -EINVAL;
4134                 goto protocol_init_error;
4135         }
4136
4137         dd->disk = alloc_disk_node(MTIP_MAX_MINORS, dd->numa_node);
4138         if (dd->disk  == NULL) {
4139                 dev_err(&dd->pdev->dev,
4140                         "Unable to allocate gendisk structure\n");
4141                 rv = -EINVAL;
4142                 goto alloc_disk_error;
4143         }
4144
4145         /* Generate the disk name, implemented same as in sd.c */
4146         do {
4147                 if (!ida_pre_get(&rssd_index_ida, GFP_KERNEL))
4148                         goto ida_get_error;
4149
4150                 spin_lock(&rssd_index_lock);
4151                 rv = ida_get_new(&rssd_index_ida, &index);
4152                 spin_unlock(&rssd_index_lock);
4153         } while (rv == -EAGAIN);
4154
4155         if (rv)
4156                 goto ida_get_error;
4157
4158         rv = rssd_disk_name_format("rssd",
4159                                 index,
4160                                 dd->disk->disk_name,
4161                                 DISK_NAME_LEN);
4162         if (rv)
4163                 goto disk_index_error;
4164
4165         dd->disk->driverfs_dev  = &dd->pdev->dev;
4166         dd->disk->major         = dd->major;
4167         dd->disk->first_minor   = dd->instance * MTIP_MAX_MINORS;
4168         dd->disk->fops          = &mtip_block_ops;
4169         dd->disk->private_data  = dd;
4170         dd->index               = index;
4171
4172         mtip_hw_debugfs_init(dd);
4173
4174         /*
4175          * if rebuild pending, start the service thread, and delay the block
4176          * queue creation and add_disk()
4177          */
4178         if (wait_for_rebuild == MTIP_FTL_REBUILD_MAGIC)
4179                 goto start_service_thread;
4180
4181 skip_create_disk:
4182         /* Allocate the request queue. */
4183         dd->queue = blk_alloc_queue_node(GFP_KERNEL, dd->numa_node);
4184         if (dd->queue == NULL) {
4185                 dev_err(&dd->pdev->dev,
4186                         "Unable to allocate request queue\n");
4187                 rv = -ENOMEM;
4188                 goto block_queue_alloc_init_error;
4189         }
4190
4191         /* Attach our request function to the request queue. */
4192         blk_queue_make_request(dd->queue, mtip_make_request);
4193
4194         dd->disk->queue         = dd->queue;
4195         dd->queue->queuedata    = dd;
4196
4197         /* Set device limits. */
4198         set_bit(QUEUE_FLAG_NONROT, &dd->queue->queue_flags);
4199         blk_queue_max_segments(dd->queue, MTIP_MAX_SG);
4200         blk_queue_physical_block_size(dd->queue, 4096);
4201         blk_queue_max_hw_sectors(dd->queue, 0xffff);
4202         blk_queue_max_segment_size(dd->queue, 0x400000);
4203         blk_queue_io_min(dd->queue, 4096);
4204
4205         /*
4206          * write back cache is not supported in the device. FUA depends on
4207          * write back cache support, hence setting flush support to zero.
4208          */
4209         blk_queue_flush(dd->queue, 0);
4210
4211         /* Signal trim support */
4212         if (dd->trim_supp == true) {
4213                 set_bit(QUEUE_FLAG_DISCARD, &dd->queue->queue_flags);
4214                 dd->queue->limits.discard_granularity = 4096;
4215                 blk_queue_max_discard_sectors(dd->queue,
4216                         MTIP_MAX_TRIM_ENTRY_LEN * MTIP_MAX_TRIM_ENTRIES);
4217                 dd->queue->limits.discard_zeroes_data = 0;
4218         }
4219
4220         /* Set the capacity of the device in 512 byte sectors. */
4221         if (!(mtip_hw_get_capacity(dd, &capacity))) {
4222                 dev_warn(&dd->pdev->dev,
4223                         "Could not read drive capacity\n");
4224                 rv = -EIO;
4225                 goto read_capacity_error;
4226         }
4227         set_capacity(dd->disk, capacity);
4228
4229         /* Enable the block device and add it to /dev */
4230         add_disk(dd->disk);
4231
4232         dd->bdev = bdget_disk(dd->disk, 0);
4233         /*
4234          * Now that the disk is active, initialize any sysfs attributes
4235          * managed by the protocol layer.
4236          */
4237         kobj = kobject_get(&disk_to_dev(dd->disk)->kobj);
4238         if (kobj) {
4239                 mtip_hw_sysfs_init(dd, kobj);
4240                 kobject_put(kobj);
4241         }
4242
4243         if (dd->mtip_svc_handler) {
4244                 set_bit(MTIP_DDF_INIT_DONE_BIT, &dd->dd_flag);
4245                 return rv; /* service thread created for handling rebuild */
4246         }
4247
4248 start_service_thread:
4249         sprintf(thd_name, "mtip_svc_thd_%02d", index);
4250         dd->mtip_svc_handler = kthread_create_on_node(mtip_service_thread,
4251                                                 dd, dd->numa_node, "%s",
4252                                                 thd_name);
4253
4254         if (IS_ERR(dd->mtip_svc_handler)) {
4255                 dev_err(&dd->pdev->dev, "service thread failed to start\n");
4256                 dd->mtip_svc_handler = NULL;
4257                 rv = -EFAULT;
4258                 goto kthread_run_error;
4259         }
4260         wake_up_process(dd->mtip_svc_handler);
4261         if (wait_for_rebuild == MTIP_FTL_REBUILD_MAGIC)
4262                 rv = wait_for_rebuild;
4263
4264         return rv;
4265
4266 kthread_run_error:
4267         bdput(dd->bdev);
4268         dd->bdev = NULL;
4269
4270         /* Delete our gendisk. This also removes the device from /dev */
4271         del_gendisk(dd->disk);
4272
4273 read_capacity_error:
4274         blk_cleanup_queue(dd->queue);
4275
4276 block_queue_alloc_init_error:
4277         mtip_hw_debugfs_exit(dd);
4278 disk_index_error:
4279         spin_lock(&rssd_index_lock);
4280         ida_remove(&rssd_index_ida, index);
4281         spin_unlock(&rssd_index_lock);
4282
4283 ida_get_error:
4284         put_disk(dd->disk);
4285
4286 alloc_disk_error:
4287         mtip_hw_exit(dd); /* De-initialize the protocol layer. */
4288
4289 protocol_init_error:
4290         return rv;
4291 }
4292
4293 /*
4294  * Block layer deinitialization function.
4295  *
4296  * Called by the PCI layer as each P320 device is removed.
4297  *
4298  * @dd Pointer to the driver data structure.
4299  *
4300  * return value
4301  *      0
4302  */
4303 static int mtip_block_remove(struct driver_data *dd)
4304 {
4305         struct kobject *kobj;
4306
4307         if (!dd->sr) {
4308                 mtip_hw_debugfs_exit(dd);
4309
4310                 if (dd->mtip_svc_handler) {
4311                         set_bit(MTIP_PF_SVC_THD_STOP_BIT, &dd->port->flags);
4312                         wake_up_interruptible(&dd->port->svc_wait);
4313                         kthread_stop(dd->mtip_svc_handler);
4314                 }
4315
4316                 /* Clean up the sysfs attributes, if created */
4317                 if (test_bit(MTIP_DDF_INIT_DONE_BIT, &dd->dd_flag)) {
4318                         kobj = kobject_get(&disk_to_dev(dd->disk)->kobj);
4319                         if (kobj) {
4320                                 mtip_hw_sysfs_exit(dd, kobj);
4321                                 kobject_put(kobj);
4322                         }
4323                 }
4324                 /*
4325                  * Delete our gendisk structure. This also removes the device
4326                  * from /dev
4327                  */
4328                 if (dd->bdev) {
4329                         bdput(dd->bdev);
4330                         dd->bdev = NULL;
4331                 }
4332                 if (dd->disk) {
4333                         if (dd->disk->queue) {
4334                                 del_gendisk(dd->disk);
4335                                 blk_cleanup_queue(dd->queue);
4336                                 dd->queue = NULL;
4337                         } else
4338                                 put_disk(dd->disk);
4339                 }
4340                 dd->disk  = NULL;
4341
4342                 spin_lock(&rssd_index_lock);
4343                 ida_remove(&rssd_index_ida, dd->index);
4344                 spin_unlock(&rssd_index_lock);
4345         } else {
4346                 dev_info(&dd->pdev->dev, "device %s surprise removal\n",
4347                                                 dd->disk->disk_name);
4348         }
4349
4350         /* De-initialize the protocol layer. */
4351         mtip_hw_exit(dd);
4352
4353         return 0;
4354 }
4355
4356 /*
4357  * Function called by the PCI layer when just before the
4358  * machine shuts down.
4359  *
4360  * If a protocol layer shutdown function is present it will be called
4361  * by this function.
4362  *
4363  * @dd Pointer to the driver data structure.
4364  *
4365  * return value
4366  *      0
4367  */
4368 static int mtip_block_shutdown(struct driver_data *dd)
4369 {
4370         /* Delete our gendisk structure, and cleanup the blk queue. */
4371         if (dd->disk) {
4372                 dev_info(&dd->pdev->dev,
4373                         "Shutting down %s ...\n", dd->disk->disk_name);
4374
4375                 if (dd->disk->queue) {
4376                         del_gendisk(dd->disk);
4377                         blk_cleanup_queue(dd->queue);
4378                 } else
4379                         put_disk(dd->disk);
4380                 dd->disk  = NULL;
4381                 dd->queue = NULL;
4382         }
4383
4384         spin_lock(&rssd_index_lock);
4385         ida_remove(&rssd_index_ida, dd->index);
4386         spin_unlock(&rssd_index_lock);
4387
4388         mtip_hw_shutdown(dd);
4389         return 0;
4390 }
4391
4392 static int mtip_block_suspend(struct driver_data *dd)
4393 {
4394         dev_info(&dd->pdev->dev,
4395                 "Suspending %s ...\n", dd->disk->disk_name);
4396         mtip_hw_suspend(dd);
4397         return 0;
4398 }
4399
4400 static int mtip_block_resume(struct driver_data *dd)
4401 {
4402         dev_info(&dd->pdev->dev, "Resuming %s ...\n",
4403                 dd->disk->disk_name);
4404         mtip_hw_resume(dd);
4405         return 0;
4406 }
4407
4408 static void drop_cpu(int cpu)
4409 {
4410         cpu_use[cpu]--;
4411 }
4412
4413 static int get_least_used_cpu_on_node(int node)
4414 {
4415         int cpu, least_used_cpu, least_cnt;
4416         const struct cpumask *node_mask;
4417
4418         node_mask = cpumask_of_node(node);
4419         least_used_cpu = cpumask_first(node_mask);
4420         least_cnt = cpu_use[least_used_cpu];
4421         cpu = least_used_cpu;
4422
4423         for_each_cpu(cpu, node_mask) {
4424                 if (cpu_use[cpu] < least_cnt) {
4425                         least_used_cpu = cpu;
4426                         least_cnt = cpu_use[cpu];
4427                 }
4428         }
4429         cpu_use[least_used_cpu]++;
4430         return least_used_cpu;
4431 }
4432
4433 /* Helper for selecting a node in round robin mode */
4434 static inline int mtip_get_next_rr_node(void)
4435 {
4436         static int next_node = -1;
4437
4438         if (next_node == -1) {
4439                 next_node = first_online_node;
4440                 return next_node;
4441         }
4442
4443         next_node = next_online_node(next_node);
4444         if (next_node == MAX_NUMNODES)
4445                 next_node = first_online_node;
4446         return next_node;
4447 }
4448
4449 static DEFINE_HANDLER(0);
4450 static DEFINE_HANDLER(1);
4451 static DEFINE_HANDLER(2);
4452 static DEFINE_HANDLER(3);
4453 static DEFINE_HANDLER(4);
4454 static DEFINE_HANDLER(5);
4455 static DEFINE_HANDLER(6);
4456 static DEFINE_HANDLER(7);
4457
4458 /*
4459  * Called for each supported PCI device detected.
4460  *
4461  * This function allocates the private data structure, enables the
4462  * PCI device and then calls the block layer initialization function.
4463  *
4464  * return value
4465  *      0 on success else an error code.
4466  */
4467 static int mtip_pci_probe(struct pci_dev *pdev,
4468                         const struct pci_device_id *ent)
4469 {
4470         int rv = 0;
4471         struct driver_data *dd = NULL;
4472         char cpu_list[256];
4473         const struct cpumask *node_mask;
4474         int cpu, i = 0, j = 0;
4475         int my_node = NUMA_NO_NODE;
4476         unsigned long flags;
4477
4478         /* Allocate memory for this devices private data. */
4479         my_node = pcibus_to_node(pdev->bus);
4480         if (my_node != NUMA_NO_NODE) {
4481                 if (!node_online(my_node))
4482                         my_node = mtip_get_next_rr_node();
4483         } else {
4484                 dev_info(&pdev->dev, "Kernel not reporting proximity, choosing a node\n");
4485                 my_node = mtip_get_next_rr_node();
4486         }
4487         dev_info(&pdev->dev, "NUMA node %d (closest: %d,%d, probe on %d:%d)\n",
4488                 my_node, pcibus_to_node(pdev->bus), dev_to_node(&pdev->dev),
4489                 cpu_to_node(smp_processor_id()), smp_processor_id());
4490
4491         dd = kzalloc_node(sizeof(struct driver_data), GFP_KERNEL, my_node);
4492         if (dd == NULL) {
4493                 dev_err(&pdev->dev,
4494                         "Unable to allocate memory for driver data\n");
4495                 return -ENOMEM;
4496         }
4497
4498         /* Attach the private data to this PCI device.  */
4499         pci_set_drvdata(pdev, dd);
4500
4501         rv = pcim_enable_device(pdev);
4502         if (rv < 0) {
4503                 dev_err(&pdev->dev, "Unable to enable device\n");
4504                 goto iomap_err;
4505         }
4506
4507         /* Map BAR5 to memory. */
4508         rv = pcim_iomap_regions(pdev, 1 << MTIP_ABAR, MTIP_DRV_NAME);
4509         if (rv < 0) {
4510                 dev_err(&pdev->dev, "Unable to map regions\n");
4511                 goto iomap_err;
4512         }
4513
4514         if (!pci_set_dma_mask(pdev, DMA_BIT_MASK(64))) {
4515                 rv = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(64));
4516
4517                 if (rv) {
4518                         rv = pci_set_consistent_dma_mask(pdev,
4519                                                 DMA_BIT_MASK(32));
4520                         if (rv) {
4521                                 dev_warn(&pdev->dev,
4522                                         "64-bit DMA enable failed\n");
4523                                 goto setmask_err;
4524                         }
4525                 }
4526         }
4527
4528         /* Copy the info we may need later into the private data structure. */
4529         dd->major       = mtip_major;
4530         dd->instance    = instance;
4531         dd->pdev        = pdev;
4532         dd->numa_node   = my_node;
4533
4534         INIT_LIST_HEAD(&dd->online_list);
4535         INIT_LIST_HEAD(&dd->remove_list);
4536
4537         memset(dd->workq_name, 0, 32);
4538         snprintf(dd->workq_name, 31, "mtipq%d", dd->instance);
4539
4540         dd->isr_workq = create_workqueue(dd->workq_name);
4541         if (!dd->isr_workq) {
4542                 dev_warn(&pdev->dev, "Can't create wq %d\n", dd->instance);
4543                 rv = -ENOMEM;
4544                 goto block_initialize_err;
4545         }
4546
4547         memset(cpu_list, 0, sizeof(cpu_list));
4548
4549         node_mask = cpumask_of_node(dd->numa_node);
4550         if (!cpumask_empty(node_mask)) {
4551                 for_each_cpu(cpu, node_mask)
4552                 {
4553                         snprintf(&cpu_list[j], 256 - j, "%d ", cpu);
4554                         j = strlen(cpu_list);
4555                 }
4556
4557                 dev_info(&pdev->dev, "Node %d on package %d has %d cpu(s): %s\n",
4558                         dd->numa_node,
4559                         topology_physical_package_id(cpumask_first(node_mask)),
4560                         nr_cpus_node(dd->numa_node),
4561                         cpu_list);
4562         } else
4563                 dev_dbg(&pdev->dev, "mtip32xx: node_mask empty\n");
4564
4565         dd->isr_binding = get_least_used_cpu_on_node(dd->numa_node);
4566         dev_info(&pdev->dev, "Initial IRQ binding node:cpu %d:%d\n",
4567                 cpu_to_node(dd->isr_binding), dd->isr_binding);
4568
4569         /* first worker context always runs in ISR */
4570         dd->work[0].cpu_binding = dd->isr_binding;
4571         dd->work[1].cpu_binding = get_least_used_cpu_on_node(dd->numa_node);
4572         dd->work[2].cpu_binding = get_least_used_cpu_on_node(dd->numa_node);
4573         dd->work[3].cpu_binding = dd->work[0].cpu_binding;
4574         dd->work[4].cpu_binding = dd->work[1].cpu_binding;
4575         dd->work[5].cpu_binding = dd->work[2].cpu_binding;
4576         dd->work[6].cpu_binding = dd->work[2].cpu_binding;
4577         dd->work[7].cpu_binding = dd->work[1].cpu_binding;
4578
4579         /* Log the bindings */
4580         for_each_present_cpu(cpu) {
4581                 memset(cpu_list, 0, sizeof(cpu_list));
4582                 for (i = 0, j = 0; i < MTIP_MAX_SLOT_GROUPS; i++) {
4583                         if (dd->work[i].cpu_binding == cpu) {
4584                                 snprintf(&cpu_list[j], 256 - j, "%d ", i);
4585                                 j = strlen(cpu_list);
4586                         }
4587                 }
4588                 if (j)
4589                         dev_info(&pdev->dev, "CPU %d: WQs %s\n", cpu, cpu_list);
4590         }
4591
4592         INIT_WORK(&dd->work[0].work, mtip_workq_sdbf0);
4593         INIT_WORK(&dd->work[1].work, mtip_workq_sdbf1);
4594         INIT_WORK(&dd->work[2].work, mtip_workq_sdbf2);
4595         INIT_WORK(&dd->work[3].work, mtip_workq_sdbf3);
4596         INIT_WORK(&dd->work[4].work, mtip_workq_sdbf4);
4597         INIT_WORK(&dd->work[5].work, mtip_workq_sdbf5);
4598         INIT_WORK(&dd->work[6].work, mtip_workq_sdbf6);
4599         INIT_WORK(&dd->work[7].work, mtip_workq_sdbf7);
4600
4601         pci_set_master(pdev);
4602         rv = pci_enable_msi(pdev);
4603         if (rv) {
4604                 dev_warn(&pdev->dev,
4605                         "Unable to enable MSI interrupt.\n");
4606                 goto block_initialize_err;
4607         }
4608
4609         /* Initialize the block layer. */
4610         rv = mtip_block_initialize(dd);
4611         if (rv < 0) {
4612                 dev_err(&pdev->dev,
4613                         "Unable to initialize block layer\n");
4614                 goto block_initialize_err;
4615         }
4616
4617         /*
4618          * Increment the instance count so that each device has a unique
4619          * instance number.
4620          */
4621         instance++;
4622         if (rv != MTIP_FTL_REBUILD_MAGIC)
4623                 set_bit(MTIP_DDF_INIT_DONE_BIT, &dd->dd_flag);
4624         else
4625                 rv = 0; /* device in rebuild state, return 0 from probe */
4626
4627         /* Add to online list even if in ftl rebuild */
4628         spin_lock_irqsave(&dev_lock, flags);
4629         list_add(&dd->online_list, &online_list);
4630         spin_unlock_irqrestore(&dev_lock, flags);
4631
4632         goto done;
4633
4634 block_initialize_err:
4635         pci_disable_msi(pdev);
4636         if (dd->isr_workq) {
4637                 flush_workqueue(dd->isr_workq);
4638                 destroy_workqueue(dd->isr_workq);
4639                 drop_cpu(dd->work[0].cpu_binding);
4640                 drop_cpu(dd->work[1].cpu_binding);
4641                 drop_cpu(dd->work[2].cpu_binding);
4642         }
4643 setmask_err:
4644         pcim_iounmap_regions(pdev, 1 << MTIP_ABAR);
4645
4646 iomap_err:
4647         kfree(dd);
4648         pci_set_drvdata(pdev, NULL);
4649         return rv;
4650 done:
4651         return rv;
4652 }
4653
4654 /*
4655  * Called for each probed device when the device is removed or the
4656  * driver is unloaded.
4657  *
4658  * return value
4659  *      None
4660  */
4661 static void mtip_pci_remove(struct pci_dev *pdev)
4662 {
4663         struct driver_data *dd = pci_get_drvdata(pdev);
4664         unsigned long flags, to;
4665
4666         set_bit(MTIP_DDF_REMOVE_PENDING_BIT, &dd->dd_flag);
4667
4668         spin_lock_irqsave(&dev_lock, flags);
4669         list_del_init(&dd->online_list);
4670         list_add(&dd->remove_list, &removing_list);
4671         spin_unlock_irqrestore(&dev_lock, flags);
4672
4673         mtip_check_surprise_removal(pdev);
4674         synchronize_irq(dd->pdev->irq);
4675
4676         /* Spin until workers are done */
4677         to = jiffies + msecs_to_jiffies(4000);
4678         do {
4679                 msleep(20);
4680         } while (atomic_read(&dd->irq_workers_active) != 0 &&
4681                 time_before(jiffies, to));
4682
4683         if (atomic_read(&dd->irq_workers_active) != 0) {
4684                 dev_warn(&dd->pdev->dev,
4685                         "Completion workers still active!\n");
4686         }
4687         /* Cleanup the outstanding commands */
4688         mtip_command_cleanup(dd);
4689
4690         /* Clean up the block layer. */
4691         mtip_block_remove(dd);
4692
4693         if (dd->isr_workq) {
4694                 flush_workqueue(dd->isr_workq);
4695                 destroy_workqueue(dd->isr_workq);
4696                 drop_cpu(dd->work[0].cpu_binding);
4697                 drop_cpu(dd->work[1].cpu_binding);
4698                 drop_cpu(dd->work[2].cpu_binding);
4699         }
4700
4701         pci_disable_msi(pdev);
4702
4703         spin_lock_irqsave(&dev_lock, flags);
4704         list_del_init(&dd->remove_list);
4705         spin_unlock_irqrestore(&dev_lock, flags);
4706
4707         if (!dd->sr)
4708                 kfree(dd);
4709         else
4710                 set_bit(MTIP_DDF_REMOVE_DONE_BIT, &dd->dd_flag);
4711
4712         pcim_iounmap_regions(pdev, 1 << MTIP_ABAR);
4713         pci_set_drvdata(pdev, NULL);
4714         pci_dev_put(pdev);
4715
4716 }
4717
4718 /*
4719  * Called for each probed device when the device is suspended.
4720  *
4721  * return value
4722  *      0  Success
4723  *      <0 Error
4724  */
4725 static int mtip_pci_suspend(struct pci_dev *pdev, pm_message_t mesg)
4726 {
4727         int rv = 0;
4728         struct driver_data *dd = pci_get_drvdata(pdev);
4729
4730         if (!dd) {
4731                 dev_err(&pdev->dev,
4732                         "Driver private datastructure is NULL\n");
4733                 return -EFAULT;
4734         }
4735
4736         set_bit(MTIP_DDF_RESUME_BIT, &dd->dd_flag);
4737
4738         /* Disable ports & interrupts then send standby immediate */
4739         rv = mtip_block_suspend(dd);
4740         if (rv < 0) {
4741                 dev_err(&pdev->dev,
4742                         "Failed to suspend controller\n");
4743                 return rv;
4744         }
4745
4746         /*
4747          * Save the pci config space to pdev structure &
4748          * disable the device
4749          */
4750         pci_save_state(pdev);
4751         pci_disable_device(pdev);
4752
4753         /* Move to Low power state*/
4754         pci_set_power_state(pdev, PCI_D3hot);
4755
4756         return rv;
4757 }
4758
4759 /*
4760  * Called for each probed device when the device is resumed.
4761  *
4762  * return value
4763  *      0  Success
4764  *      <0 Error
4765  */
4766 static int mtip_pci_resume(struct pci_dev *pdev)
4767 {
4768         int rv = 0;
4769         struct driver_data *dd;
4770
4771         dd = pci_get_drvdata(pdev);
4772         if (!dd) {
4773                 dev_err(&pdev->dev,
4774                         "Driver private datastructure is NULL\n");
4775                 return -EFAULT;
4776         }
4777
4778         /* Move the device to active State */
4779         pci_set_power_state(pdev, PCI_D0);
4780
4781         /* Restore PCI configuration space */
4782         pci_restore_state(pdev);
4783
4784         /* Enable the PCI device*/
4785         rv = pcim_enable_device(pdev);
4786         if (rv < 0) {
4787                 dev_err(&pdev->dev,
4788                         "Failed to enable card during resume\n");
4789                 goto err;
4790         }
4791         pci_set_master(pdev);
4792
4793         /*
4794          * Calls hbaReset, initPort, & startPort function
4795          * then enables interrupts
4796          */
4797         rv = mtip_block_resume(dd);
4798         if (rv < 0)
4799                 dev_err(&pdev->dev, "Unable to resume\n");
4800
4801 err:
4802         clear_bit(MTIP_DDF_RESUME_BIT, &dd->dd_flag);
4803
4804         return rv;
4805 }
4806
4807 /*
4808  * Shutdown routine
4809  *
4810  * return value
4811  *      None
4812  */
4813 static void mtip_pci_shutdown(struct pci_dev *pdev)
4814 {
4815         struct driver_data *dd = pci_get_drvdata(pdev);
4816         if (dd)
4817                 mtip_block_shutdown(dd);
4818 }
4819
4820 /* Table of device ids supported by this driver. */
4821 static DEFINE_PCI_DEVICE_TABLE(mtip_pci_tbl) = {
4822         { PCI_DEVICE(PCI_VENDOR_ID_MICRON, P320H_DEVICE_ID) },
4823         { PCI_DEVICE(PCI_VENDOR_ID_MICRON, P320M_DEVICE_ID) },
4824         { PCI_DEVICE(PCI_VENDOR_ID_MICRON, P320S_DEVICE_ID) },
4825         { PCI_DEVICE(PCI_VENDOR_ID_MICRON, P325M_DEVICE_ID) },
4826         { PCI_DEVICE(PCI_VENDOR_ID_MICRON, P420H_DEVICE_ID) },
4827         { PCI_DEVICE(PCI_VENDOR_ID_MICRON, P420M_DEVICE_ID) },
4828         { PCI_DEVICE(PCI_VENDOR_ID_MICRON, P425M_DEVICE_ID) },
4829         { 0 }
4830 };
4831
4832 /* Structure that describes the PCI driver functions. */
4833 static struct pci_driver mtip_pci_driver = {
4834         .name                   = MTIP_DRV_NAME,
4835         .id_table               = mtip_pci_tbl,
4836         .probe                  = mtip_pci_probe,
4837         .remove                 = mtip_pci_remove,
4838         .suspend                = mtip_pci_suspend,
4839         .resume                 = mtip_pci_resume,
4840         .shutdown               = mtip_pci_shutdown,
4841 };
4842
4843 MODULE_DEVICE_TABLE(pci, mtip_pci_tbl);
4844
4845 /*
4846  * Module initialization function.
4847  *
4848  * Called once when the module is loaded. This function allocates a major
4849  * block device number to the Cyclone devices and registers the PCI layer
4850  * of the driver.
4851  *
4852  * Return value
4853  *      0 on success else error code.
4854  */
4855 static int __init mtip_init(void)
4856 {
4857         int error;
4858
4859         pr_info(MTIP_DRV_NAME " Version " MTIP_DRV_VERSION "\n");
4860
4861         spin_lock_init(&dev_lock);
4862
4863         INIT_LIST_HEAD(&online_list);
4864         INIT_LIST_HEAD(&removing_list);
4865
4866         /* Allocate a major block device number to use with this driver. */
4867         error = register_blkdev(0, MTIP_DRV_NAME);
4868         if (error <= 0) {
4869                 pr_err("Unable to register block device (%d)\n",
4870                 error);
4871                 return -EBUSY;
4872         }
4873         mtip_major = error;
4874
4875         dfs_parent = debugfs_create_dir("rssd", NULL);
4876         if (IS_ERR_OR_NULL(dfs_parent)) {
4877                 pr_warn("Error creating debugfs parent\n");
4878                 dfs_parent = NULL;
4879         }
4880         if (dfs_parent) {
4881                 dfs_device_status = debugfs_create_file("device_status",
4882                                         S_IRUGO, dfs_parent, NULL,
4883                                         &mtip_device_status_fops);
4884                 if (IS_ERR_OR_NULL(dfs_device_status)) {
4885                         pr_err("Error creating device_status node\n");
4886                         dfs_device_status = NULL;
4887                 }
4888         }
4889
4890         /* Register our PCI operations. */
4891         error = pci_register_driver(&mtip_pci_driver);
4892         if (error) {
4893                 debugfs_remove(dfs_parent);
4894                 unregister_blkdev(mtip_major, MTIP_DRV_NAME);
4895         }
4896
4897         return error;
4898 }
4899
4900 /*
4901  * Module de-initialization function.
4902  *
4903  * Called once when the module is unloaded. This function deallocates
4904  * the major block device number allocated by mtip_init() and
4905  * unregisters the PCI layer of the driver.
4906  *
4907  * Return value
4908  *      none
4909  */
4910 static void __exit mtip_exit(void)
4911 {
4912         debugfs_remove_recursive(dfs_parent);
4913
4914         /* Release the allocated major block device number. */
4915         unregister_blkdev(mtip_major, MTIP_DRV_NAME);
4916
4917         /* Unregister the PCI driver. */
4918         pci_unregister_driver(&mtip_pci_driver);
4919 }
4920
4921 MODULE_AUTHOR("Micron Technology, Inc");
4922 MODULE_DESCRIPTION("Micron RealSSD PCIe Block Driver");
4923 MODULE_LICENSE("GPL");
4924 MODULE_VERSION(MTIP_DRV_VERSION);
4925
4926 module_init(mtip_init);
4927 module_exit(mtip_exit);