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