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