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