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