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