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