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