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