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