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