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