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