]> Git Repo - linux.git/blob - drivers/ata/libata-core.c
move asm/unaligned.h to linux/unaligned.h
[linux.git] / drivers / ata / libata-core.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *  libata-core.c - helper library for ATA
4  *
5  *  Copyright 2003-2004 Red Hat, Inc.  All rights reserved.
6  *  Copyright 2003-2004 Jeff Garzik
7  *
8  *  libata documentation is available via 'make {ps|pdf}docs',
9  *  as Documentation/driver-api/libata.rst
10  *
11  *  Hardware documentation available from http://www.t13.org/ and
12  *  http://www.sata-io.org/
13  *
14  *  Standards documents from:
15  *      http://www.t13.org (ATA standards, PCI DMA IDE spec)
16  *      http://www.t10.org (SCSI MMC - for ATAPI MMC)
17  *      http://www.sata-io.org (SATA)
18  *      http://www.compactflash.org (CF)
19  *      http://www.qic.org (QIC157 - Tape and DSC)
20  *      http://www.ce-ata.org (CE-ATA: not supported)
21  *
22  * libata is essentially a library of internal helper functions for
23  * low-level ATA host controller drivers.  As such, the API/ABI is
24  * likely to change as new drivers are added and updated.
25  * Do not depend on ABI/API stability.
26  */
27
28 #include <linux/kernel.h>
29 #include <linux/module.h>
30 #include <linux/pci.h>
31 #include <linux/init.h>
32 #include <linux/list.h>
33 #include <linux/mm.h>
34 #include <linux/spinlock.h>
35 #include <linux/blkdev.h>
36 #include <linux/delay.h>
37 #include <linux/timer.h>
38 #include <linux/time.h>
39 #include <linux/interrupt.h>
40 #include <linux/completion.h>
41 #include <linux/suspend.h>
42 #include <linux/workqueue.h>
43 #include <linux/scatterlist.h>
44 #include <linux/io.h>
45 #include <linux/log2.h>
46 #include <linux/slab.h>
47 #include <linux/glob.h>
48 #include <scsi/scsi.h>
49 #include <scsi/scsi_cmnd.h>
50 #include <scsi/scsi_host.h>
51 #include <linux/libata.h>
52 #include <asm/byteorder.h>
53 #include <linux/unaligned.h>
54 #include <linux/cdrom.h>
55 #include <linux/ratelimit.h>
56 #include <linux/leds.h>
57 #include <linux/pm_runtime.h>
58 #include <linux/platform_device.h>
59 #include <asm/setup.h>
60
61 #define CREATE_TRACE_POINTS
62 #include <trace/events/libata.h>
63
64 #include "libata.h"
65 #include "libata-transport.h"
66
67 const struct ata_port_operations ata_base_port_ops = {
68         .prereset               = ata_std_prereset,
69         .postreset              = ata_std_postreset,
70         .error_handler          = ata_std_error_handler,
71         .sched_eh               = ata_std_sched_eh,
72         .end_eh                 = ata_std_end_eh,
73 };
74
75 static unsigned int ata_dev_init_params(struct ata_device *dev,
76                                         u16 heads, u16 sectors);
77 static unsigned int ata_dev_set_xfermode(struct ata_device *dev);
78 static void ata_dev_xfermask(struct ata_device *dev);
79 static unsigned int ata_dev_quirks(const struct ata_device *dev);
80
81 static DEFINE_IDA(ata_ida);
82
83 #ifdef CONFIG_ATA_FORCE
84 struct ata_force_param {
85         const char      *name;
86         u8              cbl;
87         u8              spd_limit;
88         unsigned int    xfer_mask;
89         unsigned int    quirk_on;
90         unsigned int    quirk_off;
91         u16             lflags_on;
92         u16             lflags_off;
93 };
94
95 struct ata_force_ent {
96         int                     port;
97         int                     device;
98         struct ata_force_param  param;
99 };
100
101 static struct ata_force_ent *ata_force_tbl;
102 static int ata_force_tbl_size;
103
104 static char ata_force_param_buf[COMMAND_LINE_SIZE] __initdata;
105 /* param_buf is thrown away after initialization, disallow read */
106 module_param_string(force, ata_force_param_buf, sizeof(ata_force_param_buf), 0);
107 MODULE_PARM_DESC(force, "Force ATA configurations including cable type, link speed and transfer mode (see Documentation/admin-guide/kernel-parameters.rst for details)");
108 #endif
109
110 static int atapi_enabled = 1;
111 module_param(atapi_enabled, int, 0444);
112 MODULE_PARM_DESC(atapi_enabled, "Enable discovery of ATAPI devices (0=off, 1=on [default])");
113
114 static int atapi_dmadir = 0;
115 module_param(atapi_dmadir, int, 0444);
116 MODULE_PARM_DESC(atapi_dmadir, "Enable ATAPI DMADIR bridge support (0=off [default], 1=on)");
117
118 int atapi_passthru16 = 1;
119 module_param(atapi_passthru16, int, 0444);
120 MODULE_PARM_DESC(atapi_passthru16, "Enable ATA_16 passthru for ATAPI devices (0=off, 1=on [default])");
121
122 int libata_fua = 0;
123 module_param_named(fua, libata_fua, int, 0444);
124 MODULE_PARM_DESC(fua, "FUA support (0=off [default], 1=on)");
125
126 static int ata_ignore_hpa;
127 module_param_named(ignore_hpa, ata_ignore_hpa, int, 0644);
128 MODULE_PARM_DESC(ignore_hpa, "Ignore HPA limit (0=keep BIOS limits, 1=ignore limits, using full disk)");
129
130 static int libata_dma_mask = ATA_DMA_MASK_ATA|ATA_DMA_MASK_ATAPI|ATA_DMA_MASK_CFA;
131 module_param_named(dma, libata_dma_mask, int, 0444);
132 MODULE_PARM_DESC(dma, "DMA enable/disable (0x1==ATA, 0x2==ATAPI, 0x4==CF)");
133
134 static int ata_probe_timeout;
135 module_param(ata_probe_timeout, int, 0444);
136 MODULE_PARM_DESC(ata_probe_timeout, "Set ATA probing timeout (seconds)");
137
138 int libata_noacpi = 0;
139 module_param_named(noacpi, libata_noacpi, int, 0444);
140 MODULE_PARM_DESC(noacpi, "Disable the use of ACPI in probe/suspend/resume (0=off [default], 1=on)");
141
142 int libata_allow_tpm = 0;
143 module_param_named(allow_tpm, libata_allow_tpm, int, 0444);
144 MODULE_PARM_DESC(allow_tpm, "Permit the use of TPM commands (0=off [default], 1=on)");
145
146 static int atapi_an;
147 module_param(atapi_an, int, 0444);
148 MODULE_PARM_DESC(atapi_an, "Enable ATAPI AN media presence notification (0=0ff [default], 1=on)");
149
150 MODULE_AUTHOR("Jeff Garzik");
151 MODULE_DESCRIPTION("Library module for ATA devices");
152 MODULE_LICENSE("GPL");
153 MODULE_VERSION(DRV_VERSION);
154
155 static inline bool ata_dev_print_info(const struct ata_device *dev)
156 {
157         struct ata_eh_context *ehc = &dev->link->eh_context;
158
159         return ehc->i.flags & ATA_EHI_PRINTINFO;
160 }
161
162 /**
163  *      ata_link_next - link iteration helper
164  *      @link: the previous link, NULL to start
165  *      @ap: ATA port containing links to iterate
166  *      @mode: iteration mode, one of ATA_LITER_*
167  *
168  *      LOCKING:
169  *      Host lock or EH context.
170  *
171  *      RETURNS:
172  *      Pointer to the next link.
173  */
174 struct ata_link *ata_link_next(struct ata_link *link, struct ata_port *ap,
175                                enum ata_link_iter_mode mode)
176 {
177         BUG_ON(mode != ATA_LITER_EDGE &&
178                mode != ATA_LITER_PMP_FIRST && mode != ATA_LITER_HOST_FIRST);
179
180         /* NULL link indicates start of iteration */
181         if (!link)
182                 switch (mode) {
183                 case ATA_LITER_EDGE:
184                 case ATA_LITER_PMP_FIRST:
185                         if (sata_pmp_attached(ap))
186                                 return ap->pmp_link;
187                         fallthrough;
188                 case ATA_LITER_HOST_FIRST:
189                         return &ap->link;
190                 }
191
192         /* we just iterated over the host link, what's next? */
193         if (link == &ap->link)
194                 switch (mode) {
195                 case ATA_LITER_HOST_FIRST:
196                         if (sata_pmp_attached(ap))
197                                 return ap->pmp_link;
198                         fallthrough;
199                 case ATA_LITER_PMP_FIRST:
200                         if (unlikely(ap->slave_link))
201                                 return ap->slave_link;
202                         fallthrough;
203                 case ATA_LITER_EDGE:
204                         return NULL;
205                 }
206
207         /* slave_link excludes PMP */
208         if (unlikely(link == ap->slave_link))
209                 return NULL;
210
211         /* we were over a PMP link */
212         if (++link < ap->pmp_link + ap->nr_pmp_links)
213                 return link;
214
215         if (mode == ATA_LITER_PMP_FIRST)
216                 return &ap->link;
217
218         return NULL;
219 }
220 EXPORT_SYMBOL_GPL(ata_link_next);
221
222 /**
223  *      ata_dev_next - device iteration helper
224  *      @dev: the previous device, NULL to start
225  *      @link: ATA link containing devices to iterate
226  *      @mode: iteration mode, one of ATA_DITER_*
227  *
228  *      LOCKING:
229  *      Host lock or EH context.
230  *
231  *      RETURNS:
232  *      Pointer to the next device.
233  */
234 struct ata_device *ata_dev_next(struct ata_device *dev, struct ata_link *link,
235                                 enum ata_dev_iter_mode mode)
236 {
237         BUG_ON(mode != ATA_DITER_ENABLED && mode != ATA_DITER_ENABLED_REVERSE &&
238                mode != ATA_DITER_ALL && mode != ATA_DITER_ALL_REVERSE);
239
240         /* NULL dev indicates start of iteration */
241         if (!dev)
242                 switch (mode) {
243                 case ATA_DITER_ENABLED:
244                 case ATA_DITER_ALL:
245                         dev = link->device;
246                         goto check;
247                 case ATA_DITER_ENABLED_REVERSE:
248                 case ATA_DITER_ALL_REVERSE:
249                         dev = link->device + ata_link_max_devices(link) - 1;
250                         goto check;
251                 }
252
253  next:
254         /* move to the next one */
255         switch (mode) {
256         case ATA_DITER_ENABLED:
257         case ATA_DITER_ALL:
258                 if (++dev < link->device + ata_link_max_devices(link))
259                         goto check;
260                 return NULL;
261         case ATA_DITER_ENABLED_REVERSE:
262         case ATA_DITER_ALL_REVERSE:
263                 if (--dev >= link->device)
264                         goto check;
265                 return NULL;
266         }
267
268  check:
269         if ((mode == ATA_DITER_ENABLED || mode == ATA_DITER_ENABLED_REVERSE) &&
270             !ata_dev_enabled(dev))
271                 goto next;
272         return dev;
273 }
274 EXPORT_SYMBOL_GPL(ata_dev_next);
275
276 /**
277  *      ata_dev_phys_link - find physical link for a device
278  *      @dev: ATA device to look up physical link for
279  *
280  *      Look up physical link which @dev is attached to.  Note that
281  *      this is different from @dev->link only when @dev is on slave
282  *      link.  For all other cases, it's the same as @dev->link.
283  *
284  *      LOCKING:
285  *      Don't care.
286  *
287  *      RETURNS:
288  *      Pointer to the found physical link.
289  */
290 struct ata_link *ata_dev_phys_link(struct ata_device *dev)
291 {
292         struct ata_port *ap = dev->link->ap;
293
294         if (!ap->slave_link)
295                 return dev->link;
296         if (!dev->devno)
297                 return &ap->link;
298         return ap->slave_link;
299 }
300
301 #ifdef CONFIG_ATA_FORCE
302 /**
303  *      ata_force_cbl - force cable type according to libata.force
304  *      @ap: ATA port of interest
305  *
306  *      Force cable type according to libata.force and whine about it.
307  *      The last entry which has matching port number is used, so it
308  *      can be specified as part of device force parameters.  For
309  *      example, both "a:40c,1.00:udma4" and "1.00:40c,udma4" have the
310  *      same effect.
311  *
312  *      LOCKING:
313  *      EH context.
314  */
315 void ata_force_cbl(struct ata_port *ap)
316 {
317         int i;
318
319         for (i = ata_force_tbl_size - 1; i >= 0; i--) {
320                 const struct ata_force_ent *fe = &ata_force_tbl[i];
321
322                 if (fe->port != -1 && fe->port != ap->print_id)
323                         continue;
324
325                 if (fe->param.cbl == ATA_CBL_NONE)
326                         continue;
327
328                 ap->cbl = fe->param.cbl;
329                 ata_port_notice(ap, "FORCE: cable set to %s\n", fe->param.name);
330                 return;
331         }
332 }
333
334 /**
335  *      ata_force_link_limits - force link limits according to libata.force
336  *      @link: ATA link of interest
337  *
338  *      Force link flags and SATA spd limit according to libata.force
339  *      and whine about it.  When only the port part is specified
340  *      (e.g. 1:), the limit applies to all links connected to both
341  *      the host link and all fan-out ports connected via PMP.  If the
342  *      device part is specified as 0 (e.g. 1.00:), it specifies the
343  *      first fan-out link not the host link.  Device number 15 always
344  *      points to the host link whether PMP is attached or not.  If the
345  *      controller has slave link, device number 16 points to it.
346  *
347  *      LOCKING:
348  *      EH context.
349  */
350 static void ata_force_link_limits(struct ata_link *link)
351 {
352         bool did_spd = false;
353         int linkno = link->pmp;
354         int i;
355
356         if (ata_is_host_link(link))
357                 linkno += 15;
358
359         for (i = ata_force_tbl_size - 1; i >= 0; i--) {
360                 const struct ata_force_ent *fe = &ata_force_tbl[i];
361
362                 if (fe->port != -1 && fe->port != link->ap->print_id)
363                         continue;
364
365                 if (fe->device != -1 && fe->device != linkno)
366                         continue;
367
368                 /* only honor the first spd limit */
369                 if (!did_spd && fe->param.spd_limit) {
370                         link->hw_sata_spd_limit = (1 << fe->param.spd_limit) - 1;
371                         ata_link_notice(link, "FORCE: PHY spd limit set to %s\n",
372                                         fe->param.name);
373                         did_spd = true;
374                 }
375
376                 /* let lflags stack */
377                 if (fe->param.lflags_on) {
378                         link->flags |= fe->param.lflags_on;
379                         ata_link_notice(link,
380                                         "FORCE: link flag 0x%x forced -> 0x%x\n",
381                                         fe->param.lflags_on, link->flags);
382                 }
383                 if (fe->param.lflags_off) {
384                         link->flags &= ~fe->param.lflags_off;
385                         ata_link_notice(link,
386                                 "FORCE: link flag 0x%x cleared -> 0x%x\n",
387                                 fe->param.lflags_off, link->flags);
388                 }
389         }
390 }
391
392 /**
393  *      ata_force_xfermask - force xfermask according to libata.force
394  *      @dev: ATA device of interest
395  *
396  *      Force xfer_mask according to libata.force and whine about it.
397  *      For consistency with link selection, device number 15 selects
398  *      the first device connected to the host link.
399  *
400  *      LOCKING:
401  *      EH context.
402  */
403 static void ata_force_xfermask(struct ata_device *dev)
404 {
405         int devno = dev->link->pmp + dev->devno;
406         int alt_devno = devno;
407         int i;
408
409         /* allow n.15/16 for devices attached to host port */
410         if (ata_is_host_link(dev->link))
411                 alt_devno += 15;
412
413         for (i = ata_force_tbl_size - 1; i >= 0; i--) {
414                 const struct ata_force_ent *fe = &ata_force_tbl[i];
415                 unsigned int pio_mask, mwdma_mask, udma_mask;
416
417                 if (fe->port != -1 && fe->port != dev->link->ap->print_id)
418                         continue;
419
420                 if (fe->device != -1 && fe->device != devno &&
421                     fe->device != alt_devno)
422                         continue;
423
424                 if (!fe->param.xfer_mask)
425                         continue;
426
427                 ata_unpack_xfermask(fe->param.xfer_mask,
428                                     &pio_mask, &mwdma_mask, &udma_mask);
429                 if (udma_mask)
430                         dev->udma_mask = udma_mask;
431                 else if (mwdma_mask) {
432                         dev->udma_mask = 0;
433                         dev->mwdma_mask = mwdma_mask;
434                 } else {
435                         dev->udma_mask = 0;
436                         dev->mwdma_mask = 0;
437                         dev->pio_mask = pio_mask;
438                 }
439
440                 ata_dev_notice(dev, "FORCE: xfer_mask set to %s\n",
441                                fe->param.name);
442                 return;
443         }
444 }
445
446 /**
447  *      ata_force_quirks - force quirks according to libata.force
448  *      @dev: ATA device of interest
449  *
450  *      Force quirks according to libata.force and whine about it.
451  *      For consistency with link selection, device number 15 selects
452  *      the first device connected to the host link.
453  *
454  *      LOCKING:
455  *      EH context.
456  */
457 static void ata_force_quirks(struct ata_device *dev)
458 {
459         int devno = dev->link->pmp + dev->devno;
460         int alt_devno = devno;
461         int i;
462
463         /* allow n.15/16 for devices attached to host port */
464         if (ata_is_host_link(dev->link))
465                 alt_devno += 15;
466
467         for (i = 0; i < ata_force_tbl_size; i++) {
468                 const struct ata_force_ent *fe = &ata_force_tbl[i];
469
470                 if (fe->port != -1 && fe->port != dev->link->ap->print_id)
471                         continue;
472
473                 if (fe->device != -1 && fe->device != devno &&
474                     fe->device != alt_devno)
475                         continue;
476
477                 if (!(~dev->quirks & fe->param.quirk_on) &&
478                     !(dev->quirks & fe->param.quirk_off))
479                         continue;
480
481                 dev->quirks |= fe->param.quirk_on;
482                 dev->quirks &= ~fe->param.quirk_off;
483
484                 ata_dev_notice(dev, "FORCE: modified (%s)\n",
485                                fe->param.name);
486         }
487 }
488 #else
489 static inline void ata_force_link_limits(struct ata_link *link) { }
490 static inline void ata_force_xfermask(struct ata_device *dev) { }
491 static inline void ata_force_quirks(struct ata_device *dev) { }
492 #endif
493
494 /**
495  *      atapi_cmd_type - Determine ATAPI command type from SCSI opcode
496  *      @opcode: SCSI opcode
497  *
498  *      Determine ATAPI command type from @opcode.
499  *
500  *      LOCKING:
501  *      None.
502  *
503  *      RETURNS:
504  *      ATAPI_{READ|WRITE|READ_CD|PASS_THRU|MISC}
505  */
506 int atapi_cmd_type(u8 opcode)
507 {
508         switch (opcode) {
509         case GPCMD_READ_10:
510         case GPCMD_READ_12:
511                 return ATAPI_READ;
512
513         case GPCMD_WRITE_10:
514         case GPCMD_WRITE_12:
515         case GPCMD_WRITE_AND_VERIFY_10:
516                 return ATAPI_WRITE;
517
518         case GPCMD_READ_CD:
519         case GPCMD_READ_CD_MSF:
520                 return ATAPI_READ_CD;
521
522         case ATA_16:
523         case ATA_12:
524                 if (atapi_passthru16)
525                         return ATAPI_PASS_THRU;
526                 fallthrough;
527         default:
528                 return ATAPI_MISC;
529         }
530 }
531 EXPORT_SYMBOL_GPL(atapi_cmd_type);
532
533 static const u8 ata_rw_cmds[] = {
534         /* pio multi */
535         ATA_CMD_READ_MULTI,
536         ATA_CMD_WRITE_MULTI,
537         ATA_CMD_READ_MULTI_EXT,
538         ATA_CMD_WRITE_MULTI_EXT,
539         0,
540         0,
541         0,
542         0,
543         /* pio */
544         ATA_CMD_PIO_READ,
545         ATA_CMD_PIO_WRITE,
546         ATA_CMD_PIO_READ_EXT,
547         ATA_CMD_PIO_WRITE_EXT,
548         0,
549         0,
550         0,
551         0,
552         /* dma */
553         ATA_CMD_READ,
554         ATA_CMD_WRITE,
555         ATA_CMD_READ_EXT,
556         ATA_CMD_WRITE_EXT,
557         0,
558         0,
559         0,
560         ATA_CMD_WRITE_FUA_EXT
561 };
562
563 /**
564  *      ata_set_rwcmd_protocol - set taskfile r/w command and protocol
565  *      @dev: target device for the taskfile
566  *      @tf: taskfile to examine and configure
567  *
568  *      Examine the device configuration and tf->flags to determine
569  *      the proper read/write command and protocol to use for @tf.
570  *
571  *      LOCKING:
572  *      caller.
573  */
574 static bool ata_set_rwcmd_protocol(struct ata_device *dev,
575                                    struct ata_taskfile *tf)
576 {
577         u8 cmd;
578
579         int index, fua, lba48, write;
580
581         fua = (tf->flags & ATA_TFLAG_FUA) ? 4 : 0;
582         lba48 = (tf->flags & ATA_TFLAG_LBA48) ? 2 : 0;
583         write = (tf->flags & ATA_TFLAG_WRITE) ? 1 : 0;
584
585         if (dev->flags & ATA_DFLAG_PIO) {
586                 tf->protocol = ATA_PROT_PIO;
587                 index = dev->multi_count ? 0 : 8;
588         } else if (lba48 && (dev->link->ap->flags & ATA_FLAG_PIO_LBA48)) {
589                 /* Unable to use DMA due to host limitation */
590                 tf->protocol = ATA_PROT_PIO;
591                 index = dev->multi_count ? 0 : 8;
592         } else {
593                 tf->protocol = ATA_PROT_DMA;
594                 index = 16;
595         }
596
597         cmd = ata_rw_cmds[index + fua + lba48 + write];
598         if (!cmd)
599                 return false;
600
601         tf->command = cmd;
602
603         return true;
604 }
605
606 /**
607  *      ata_tf_read_block - Read block address from ATA taskfile
608  *      @tf: ATA taskfile of interest
609  *      @dev: ATA device @tf belongs to
610  *
611  *      LOCKING:
612  *      None.
613  *
614  *      Read block address from @tf.  This function can handle all
615  *      three address formats - LBA, LBA48 and CHS.  tf->protocol and
616  *      flags select the address format to use.
617  *
618  *      RETURNS:
619  *      Block address read from @tf.
620  */
621 u64 ata_tf_read_block(const struct ata_taskfile *tf, struct ata_device *dev)
622 {
623         u64 block = 0;
624
625         if (tf->flags & ATA_TFLAG_LBA) {
626                 if (tf->flags & ATA_TFLAG_LBA48) {
627                         block |= (u64)tf->hob_lbah << 40;
628                         block |= (u64)tf->hob_lbam << 32;
629                         block |= (u64)tf->hob_lbal << 24;
630                 } else
631                         block |= (tf->device & 0xf) << 24;
632
633                 block |= tf->lbah << 16;
634                 block |= tf->lbam << 8;
635                 block |= tf->lbal;
636         } else {
637                 u32 cyl, head, sect;
638
639                 cyl = tf->lbam | (tf->lbah << 8);
640                 head = tf->device & 0xf;
641                 sect = tf->lbal;
642
643                 if (!sect) {
644                         ata_dev_warn(dev,
645                                      "device reported invalid CHS sector 0\n");
646                         return U64_MAX;
647                 }
648
649                 block = (cyl * dev->heads + head) * dev->sectors + sect - 1;
650         }
651
652         return block;
653 }
654
655 /*
656  * Set a taskfile command duration limit index.
657  */
658 static inline void ata_set_tf_cdl(struct ata_queued_cmd *qc, int cdl)
659 {
660         struct ata_taskfile *tf = &qc->tf;
661
662         if (tf->protocol == ATA_PROT_NCQ)
663                 tf->auxiliary |= cdl;
664         else
665                 tf->feature |= cdl;
666
667         /*
668          * Mark this command as having a CDL and request the result
669          * task file so that we can inspect the sense data available
670          * bit on completion.
671          */
672         qc->flags |= ATA_QCFLAG_HAS_CDL | ATA_QCFLAG_RESULT_TF;
673 }
674
675 /**
676  *      ata_build_rw_tf - Build ATA taskfile for given read/write request
677  *      @qc: Metadata associated with the taskfile to build
678  *      @block: Block address
679  *      @n_block: Number of blocks
680  *      @tf_flags: RW/FUA etc...
681  *      @cdl: Command duration limit index
682  *      @class: IO priority class
683  *
684  *      LOCKING:
685  *      None.
686  *
687  *      Build ATA taskfile for the command @qc for read/write request described
688  *      by @block, @n_block, @tf_flags and @class.
689  *
690  *      RETURNS:
691  *
692  *      0 on success, -ERANGE if the request is too large for @dev,
693  *      -EINVAL if the request is invalid.
694  */
695 int ata_build_rw_tf(struct ata_queued_cmd *qc, u64 block, u32 n_block,
696                     unsigned int tf_flags, int cdl, int class)
697 {
698         struct ata_taskfile *tf = &qc->tf;
699         struct ata_device *dev = qc->dev;
700
701         tf->flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE;
702         tf->flags |= tf_flags;
703
704         if (ata_ncq_enabled(dev)) {
705                 /* yay, NCQ */
706                 if (!lba_48_ok(block, n_block))
707                         return -ERANGE;
708
709                 tf->protocol = ATA_PROT_NCQ;
710                 tf->flags |= ATA_TFLAG_LBA | ATA_TFLAG_LBA48;
711
712                 if (tf->flags & ATA_TFLAG_WRITE)
713                         tf->command = ATA_CMD_FPDMA_WRITE;
714                 else
715                         tf->command = ATA_CMD_FPDMA_READ;
716
717                 tf->nsect = qc->hw_tag << 3;
718                 tf->hob_feature = (n_block >> 8) & 0xff;
719                 tf->feature = n_block & 0xff;
720
721                 tf->hob_lbah = (block >> 40) & 0xff;
722                 tf->hob_lbam = (block >> 32) & 0xff;
723                 tf->hob_lbal = (block >> 24) & 0xff;
724                 tf->lbah = (block >> 16) & 0xff;
725                 tf->lbam = (block >> 8) & 0xff;
726                 tf->lbal = block & 0xff;
727
728                 tf->device = ATA_LBA;
729                 if (tf->flags & ATA_TFLAG_FUA)
730                         tf->device |= 1 << 7;
731
732                 if (dev->flags & ATA_DFLAG_NCQ_PRIO_ENABLED &&
733                     class == IOPRIO_CLASS_RT)
734                         tf->hob_nsect |= ATA_PRIO_HIGH << ATA_SHIFT_PRIO;
735
736                 if ((dev->flags & ATA_DFLAG_CDL_ENABLED) && cdl)
737                         ata_set_tf_cdl(qc, cdl);
738
739         } else if (dev->flags & ATA_DFLAG_LBA) {
740                 tf->flags |= ATA_TFLAG_LBA;
741
742                 if ((dev->flags & ATA_DFLAG_CDL_ENABLED) && cdl)
743                         ata_set_tf_cdl(qc, cdl);
744
745                 /* Both FUA writes and a CDL index require 48-bit commands */
746                 if (!(tf->flags & ATA_TFLAG_FUA) &&
747                     !(qc->flags & ATA_QCFLAG_HAS_CDL) &&
748                     lba_28_ok(block, n_block)) {
749                         /* use LBA28 */
750                         tf->device |= (block >> 24) & 0xf;
751                 } else if (lba_48_ok(block, n_block)) {
752                         if (!(dev->flags & ATA_DFLAG_LBA48))
753                                 return -ERANGE;
754
755                         /* use LBA48 */
756                         tf->flags |= ATA_TFLAG_LBA48;
757
758                         tf->hob_nsect = (n_block >> 8) & 0xff;
759
760                         tf->hob_lbah = (block >> 40) & 0xff;
761                         tf->hob_lbam = (block >> 32) & 0xff;
762                         tf->hob_lbal = (block >> 24) & 0xff;
763                 } else {
764                         /* request too large even for LBA48 */
765                         return -ERANGE;
766                 }
767
768                 if (unlikely(!ata_set_rwcmd_protocol(dev, tf)))
769                         return -EINVAL;
770
771                 tf->nsect = n_block & 0xff;
772
773                 tf->lbah = (block >> 16) & 0xff;
774                 tf->lbam = (block >> 8) & 0xff;
775                 tf->lbal = block & 0xff;
776
777                 tf->device |= ATA_LBA;
778         } else {
779                 /* CHS */
780                 u32 sect, head, cyl, track;
781
782                 /* The request -may- be too large for CHS addressing. */
783                 if (!lba_28_ok(block, n_block))
784                         return -ERANGE;
785
786                 if (unlikely(!ata_set_rwcmd_protocol(dev, tf)))
787                         return -EINVAL;
788
789                 /* Convert LBA to CHS */
790                 track = (u32)block / dev->sectors;
791                 cyl   = track / dev->heads;
792                 head  = track % dev->heads;
793                 sect  = (u32)block % dev->sectors + 1;
794
795                 /* Check whether the converted CHS can fit.
796                    Cylinder: 0-65535
797                    Head: 0-15
798                    Sector: 1-255*/
799                 if ((cyl >> 16) || (head >> 4) || (sect >> 8) || (!sect))
800                         return -ERANGE;
801
802                 tf->nsect = n_block & 0xff; /* Sector count 0 means 256 sectors */
803                 tf->lbal = sect;
804                 tf->lbam = cyl;
805                 tf->lbah = cyl >> 8;
806                 tf->device |= head;
807         }
808
809         return 0;
810 }
811
812 /**
813  *      ata_pack_xfermask - Pack pio, mwdma and udma masks into xfer_mask
814  *      @pio_mask: pio_mask
815  *      @mwdma_mask: mwdma_mask
816  *      @udma_mask: udma_mask
817  *
818  *      Pack @pio_mask, @mwdma_mask and @udma_mask into a single
819  *      unsigned int xfer_mask.
820  *
821  *      LOCKING:
822  *      None.
823  *
824  *      RETURNS:
825  *      Packed xfer_mask.
826  */
827 unsigned int ata_pack_xfermask(unsigned int pio_mask,
828                                unsigned int mwdma_mask,
829                                unsigned int udma_mask)
830 {
831         return  ((pio_mask << ATA_SHIFT_PIO) & ATA_MASK_PIO) |
832                 ((mwdma_mask << ATA_SHIFT_MWDMA) & ATA_MASK_MWDMA) |
833                 ((udma_mask << ATA_SHIFT_UDMA) & ATA_MASK_UDMA);
834 }
835 EXPORT_SYMBOL_GPL(ata_pack_xfermask);
836
837 /**
838  *      ata_unpack_xfermask - Unpack xfer_mask into pio, mwdma and udma masks
839  *      @xfer_mask: xfer_mask to unpack
840  *      @pio_mask: resulting pio_mask
841  *      @mwdma_mask: resulting mwdma_mask
842  *      @udma_mask: resulting udma_mask
843  *
844  *      Unpack @xfer_mask into @pio_mask, @mwdma_mask and @udma_mask.
845  *      Any NULL destination masks will be ignored.
846  */
847 void ata_unpack_xfermask(unsigned int xfer_mask, unsigned int *pio_mask,
848                          unsigned int *mwdma_mask, unsigned int *udma_mask)
849 {
850         if (pio_mask)
851                 *pio_mask = (xfer_mask & ATA_MASK_PIO) >> ATA_SHIFT_PIO;
852         if (mwdma_mask)
853                 *mwdma_mask = (xfer_mask & ATA_MASK_MWDMA) >> ATA_SHIFT_MWDMA;
854         if (udma_mask)
855                 *udma_mask = (xfer_mask & ATA_MASK_UDMA) >> ATA_SHIFT_UDMA;
856 }
857
858 static const struct ata_xfer_ent {
859         int shift, bits;
860         u8 base;
861 } ata_xfer_tbl[] = {
862         { ATA_SHIFT_PIO, ATA_NR_PIO_MODES, XFER_PIO_0 },
863         { ATA_SHIFT_MWDMA, ATA_NR_MWDMA_MODES, XFER_MW_DMA_0 },
864         { ATA_SHIFT_UDMA, ATA_NR_UDMA_MODES, XFER_UDMA_0 },
865         { -1, },
866 };
867
868 /**
869  *      ata_xfer_mask2mode - Find matching XFER_* for the given xfer_mask
870  *      @xfer_mask: xfer_mask of interest
871  *
872  *      Return matching XFER_* value for @xfer_mask.  Only the highest
873  *      bit of @xfer_mask is considered.
874  *
875  *      LOCKING:
876  *      None.
877  *
878  *      RETURNS:
879  *      Matching XFER_* value, 0xff if no match found.
880  */
881 u8 ata_xfer_mask2mode(unsigned int xfer_mask)
882 {
883         int highbit = fls(xfer_mask) - 1;
884         const struct ata_xfer_ent *ent;
885
886         for (ent = ata_xfer_tbl; ent->shift >= 0; ent++)
887                 if (highbit >= ent->shift && highbit < ent->shift + ent->bits)
888                         return ent->base + highbit - ent->shift;
889         return 0xff;
890 }
891 EXPORT_SYMBOL_GPL(ata_xfer_mask2mode);
892
893 /**
894  *      ata_xfer_mode2mask - Find matching xfer_mask for XFER_*
895  *      @xfer_mode: XFER_* of interest
896  *
897  *      Return matching xfer_mask for @xfer_mode.
898  *
899  *      LOCKING:
900  *      None.
901  *
902  *      RETURNS:
903  *      Matching xfer_mask, 0 if no match found.
904  */
905 unsigned int ata_xfer_mode2mask(u8 xfer_mode)
906 {
907         const struct ata_xfer_ent *ent;
908
909         for (ent = ata_xfer_tbl; ent->shift >= 0; ent++)
910                 if (xfer_mode >= ent->base && xfer_mode < ent->base + ent->bits)
911                         return ((2 << (ent->shift + xfer_mode - ent->base)) - 1)
912                                 & ~((1 << ent->shift) - 1);
913         return 0;
914 }
915 EXPORT_SYMBOL_GPL(ata_xfer_mode2mask);
916
917 /**
918  *      ata_xfer_mode2shift - Find matching xfer_shift for XFER_*
919  *      @xfer_mode: XFER_* of interest
920  *
921  *      Return matching xfer_shift for @xfer_mode.
922  *
923  *      LOCKING:
924  *      None.
925  *
926  *      RETURNS:
927  *      Matching xfer_shift, -1 if no match found.
928  */
929 int ata_xfer_mode2shift(u8 xfer_mode)
930 {
931         const struct ata_xfer_ent *ent;
932
933         for (ent = ata_xfer_tbl; ent->shift >= 0; ent++)
934                 if (xfer_mode >= ent->base && xfer_mode < ent->base + ent->bits)
935                         return ent->shift;
936         return -1;
937 }
938 EXPORT_SYMBOL_GPL(ata_xfer_mode2shift);
939
940 /**
941  *      ata_mode_string - convert xfer_mask to string
942  *      @xfer_mask: mask of bits supported; only highest bit counts.
943  *
944  *      Determine string which represents the highest speed
945  *      (highest bit in @modemask).
946  *
947  *      LOCKING:
948  *      None.
949  *
950  *      RETURNS:
951  *      Constant C string representing highest speed listed in
952  *      @mode_mask, or the constant C string "<n/a>".
953  */
954 const char *ata_mode_string(unsigned int xfer_mask)
955 {
956         static const char * const xfer_mode_str[] = {
957                 "PIO0",
958                 "PIO1",
959                 "PIO2",
960                 "PIO3",
961                 "PIO4",
962                 "PIO5",
963                 "PIO6",
964                 "MWDMA0",
965                 "MWDMA1",
966                 "MWDMA2",
967                 "MWDMA3",
968                 "MWDMA4",
969                 "UDMA/16",
970                 "UDMA/25",
971                 "UDMA/33",
972                 "UDMA/44",
973                 "UDMA/66",
974                 "UDMA/100",
975                 "UDMA/133",
976                 "UDMA7",
977         };
978         int highbit;
979
980         highbit = fls(xfer_mask) - 1;
981         if (highbit >= 0 && highbit < ARRAY_SIZE(xfer_mode_str))
982                 return xfer_mode_str[highbit];
983         return "<n/a>";
984 }
985 EXPORT_SYMBOL_GPL(ata_mode_string);
986
987 const char *sata_spd_string(unsigned int spd)
988 {
989         static const char * const spd_str[] = {
990                 "1.5 Gbps",
991                 "3.0 Gbps",
992                 "6.0 Gbps",
993         };
994
995         if (spd == 0 || (spd - 1) >= ARRAY_SIZE(spd_str))
996                 return "<unknown>";
997         return spd_str[spd - 1];
998 }
999
1000 /**
1001  *      ata_dev_classify - determine device type based on ATA-spec signature
1002  *      @tf: ATA taskfile register set for device to be identified
1003  *
1004  *      Determine from taskfile register contents whether a device is
1005  *      ATA or ATAPI, as per "Signature and persistence" section
1006  *      of ATA/PI spec (volume 1, sect 5.14).
1007  *
1008  *      LOCKING:
1009  *      None.
1010  *
1011  *      RETURNS:
1012  *      Device type, %ATA_DEV_ATA, %ATA_DEV_ATAPI, %ATA_DEV_PMP,
1013  *      %ATA_DEV_ZAC, or %ATA_DEV_UNKNOWN the event of failure.
1014  */
1015 unsigned int ata_dev_classify(const struct ata_taskfile *tf)
1016 {
1017         /* Apple's open source Darwin code hints that some devices only
1018          * put a proper signature into the LBA mid/high registers,
1019          * So, we only check those.  It's sufficient for uniqueness.
1020          *
1021          * ATA/ATAPI-7 (d1532v1r1: Feb. 19, 2003) specified separate
1022          * signatures for ATA and ATAPI devices attached on SerialATA,
1023          * 0x3c/0xc3 and 0x69/0x96 respectively.  However, SerialATA
1024          * spec has never mentioned about using different signatures
1025          * for ATA/ATAPI devices.  Then, Serial ATA II: Port
1026          * Multiplier specification began to use 0x69/0x96 to identify
1027          * port multpliers and 0x3c/0xc3 to identify SEMB device.
1028          * ATA/ATAPI-7 dropped descriptions about 0x3c/0xc3 and
1029          * 0x69/0x96 shortly and described them as reserved for
1030          * SerialATA.
1031          *
1032          * We follow the current spec and consider that 0x69/0x96
1033          * identifies a port multiplier and 0x3c/0xc3 a SEMB device.
1034          * Unfortunately, WDC WD1600JS-62MHB5 (a hard drive) reports
1035          * SEMB signature.  This is worked around in
1036          * ata_dev_read_id().
1037          */
1038         if (tf->lbam == 0 && tf->lbah == 0)
1039                 return ATA_DEV_ATA;
1040
1041         if (tf->lbam == 0x14 && tf->lbah == 0xeb)
1042                 return ATA_DEV_ATAPI;
1043
1044         if (tf->lbam == 0x69 && tf->lbah == 0x96)
1045                 return ATA_DEV_PMP;
1046
1047         if (tf->lbam == 0x3c && tf->lbah == 0xc3)
1048                 return ATA_DEV_SEMB;
1049
1050         if (tf->lbam == 0xcd && tf->lbah == 0xab)
1051                 return ATA_DEV_ZAC;
1052
1053         return ATA_DEV_UNKNOWN;
1054 }
1055 EXPORT_SYMBOL_GPL(ata_dev_classify);
1056
1057 /**
1058  *      ata_id_string - Convert IDENTIFY DEVICE page into string
1059  *      @id: IDENTIFY DEVICE results we will examine
1060  *      @s: string into which data is output
1061  *      @ofs: offset into identify device page
1062  *      @len: length of string to return. must be an even number.
1063  *
1064  *      The strings in the IDENTIFY DEVICE page are broken up into
1065  *      16-bit chunks.  Run through the string, and output each
1066  *      8-bit chunk linearly, regardless of platform.
1067  *
1068  *      LOCKING:
1069  *      caller.
1070  */
1071
1072 void ata_id_string(const u16 *id, unsigned char *s,
1073                    unsigned int ofs, unsigned int len)
1074 {
1075         unsigned int c;
1076
1077         BUG_ON(len & 1);
1078
1079         while (len > 0) {
1080                 c = id[ofs] >> 8;
1081                 *s = c;
1082                 s++;
1083
1084                 c = id[ofs] & 0xff;
1085                 *s = c;
1086                 s++;
1087
1088                 ofs++;
1089                 len -= 2;
1090         }
1091 }
1092 EXPORT_SYMBOL_GPL(ata_id_string);
1093
1094 /**
1095  *      ata_id_c_string - Convert IDENTIFY DEVICE page into C string
1096  *      @id: IDENTIFY DEVICE results we will examine
1097  *      @s: string into which data is output
1098  *      @ofs: offset into identify device page
1099  *      @len: length of string to return. must be an odd number.
1100  *
1101  *      This function is identical to ata_id_string except that it
1102  *      trims trailing spaces and terminates the resulting string with
1103  *      null.  @len must be actual maximum length (even number) + 1.
1104  *
1105  *      LOCKING:
1106  *      caller.
1107  */
1108 void ata_id_c_string(const u16 *id, unsigned char *s,
1109                      unsigned int ofs, unsigned int len)
1110 {
1111         unsigned char *p;
1112
1113         ata_id_string(id, s, ofs, len - 1);
1114
1115         p = s + strnlen(s, len - 1);
1116         while (p > s && p[-1] == ' ')
1117                 p--;
1118         *p = '\0';
1119 }
1120 EXPORT_SYMBOL_GPL(ata_id_c_string);
1121
1122 static u64 ata_id_n_sectors(const u16 *id)
1123 {
1124         if (ata_id_has_lba(id)) {
1125                 if (ata_id_has_lba48(id))
1126                         return ata_id_u64(id, ATA_ID_LBA_CAPACITY_2);
1127
1128                 return ata_id_u32(id, ATA_ID_LBA_CAPACITY);
1129         }
1130
1131         if (ata_id_current_chs_valid(id))
1132                 return (u32)id[ATA_ID_CUR_CYLS] * (u32)id[ATA_ID_CUR_HEADS] *
1133                        (u32)id[ATA_ID_CUR_SECTORS];
1134
1135         return (u32)id[ATA_ID_CYLS] * (u32)id[ATA_ID_HEADS] *
1136                (u32)id[ATA_ID_SECTORS];
1137 }
1138
1139 u64 ata_tf_to_lba48(const struct ata_taskfile *tf)
1140 {
1141         u64 sectors = 0;
1142
1143         sectors |= ((u64)(tf->hob_lbah & 0xff)) << 40;
1144         sectors |= ((u64)(tf->hob_lbam & 0xff)) << 32;
1145         sectors |= ((u64)(tf->hob_lbal & 0xff)) << 24;
1146         sectors |= (tf->lbah & 0xff) << 16;
1147         sectors |= (tf->lbam & 0xff) << 8;
1148         sectors |= (tf->lbal & 0xff);
1149
1150         return sectors;
1151 }
1152
1153 u64 ata_tf_to_lba(const struct ata_taskfile *tf)
1154 {
1155         u64 sectors = 0;
1156
1157         sectors |= (tf->device & 0x0f) << 24;
1158         sectors |= (tf->lbah & 0xff) << 16;
1159         sectors |= (tf->lbam & 0xff) << 8;
1160         sectors |= (tf->lbal & 0xff);
1161
1162         return sectors;
1163 }
1164
1165 /**
1166  *      ata_read_native_max_address - Read native max address
1167  *      @dev: target device
1168  *      @max_sectors: out parameter for the result native max address
1169  *
1170  *      Perform an LBA48 or LBA28 native size query upon the device in
1171  *      question.
1172  *
1173  *      RETURNS:
1174  *      0 on success, -EACCES if command is aborted by the drive.
1175  *      -EIO on other errors.
1176  */
1177 static int ata_read_native_max_address(struct ata_device *dev, u64 *max_sectors)
1178 {
1179         unsigned int err_mask;
1180         struct ata_taskfile tf;
1181         int lba48 = ata_id_has_lba48(dev->id);
1182
1183         ata_tf_init(dev, &tf);
1184
1185         /* always clear all address registers */
1186         tf.flags |= ATA_TFLAG_DEVICE | ATA_TFLAG_ISADDR;
1187
1188         if (lba48) {
1189                 tf.command = ATA_CMD_READ_NATIVE_MAX_EXT;
1190                 tf.flags |= ATA_TFLAG_LBA48;
1191         } else
1192                 tf.command = ATA_CMD_READ_NATIVE_MAX;
1193
1194         tf.protocol = ATA_PROT_NODATA;
1195         tf.device |= ATA_LBA;
1196
1197         err_mask = ata_exec_internal(dev, &tf, NULL, DMA_NONE, NULL, 0, 0);
1198         if (err_mask) {
1199                 ata_dev_warn(dev,
1200                              "failed to read native max address (err_mask=0x%x)\n",
1201                              err_mask);
1202                 if (err_mask == AC_ERR_DEV && (tf.error & ATA_ABORTED))
1203                         return -EACCES;
1204                 return -EIO;
1205         }
1206
1207         if (lba48)
1208                 *max_sectors = ata_tf_to_lba48(&tf) + 1;
1209         else
1210                 *max_sectors = ata_tf_to_lba(&tf) + 1;
1211         if (dev->quirks & ATA_QUIRK_HPA_SIZE)
1212                 (*max_sectors)--;
1213         return 0;
1214 }
1215
1216 /**
1217  *      ata_set_max_sectors - Set max sectors
1218  *      @dev: target device
1219  *      @new_sectors: new max sectors value to set for the device
1220  *
1221  *      Set max sectors of @dev to @new_sectors.
1222  *
1223  *      RETURNS:
1224  *      0 on success, -EACCES if command is aborted or denied (due to
1225  *      previous non-volatile SET_MAX) by the drive.  -EIO on other
1226  *      errors.
1227  */
1228 static int ata_set_max_sectors(struct ata_device *dev, u64 new_sectors)
1229 {
1230         unsigned int err_mask;
1231         struct ata_taskfile tf;
1232         int lba48 = ata_id_has_lba48(dev->id);
1233
1234         new_sectors--;
1235
1236         ata_tf_init(dev, &tf);
1237
1238         tf.flags |= ATA_TFLAG_DEVICE | ATA_TFLAG_ISADDR;
1239
1240         if (lba48) {
1241                 tf.command = ATA_CMD_SET_MAX_EXT;
1242                 tf.flags |= ATA_TFLAG_LBA48;
1243
1244                 tf.hob_lbal = (new_sectors >> 24) & 0xff;
1245                 tf.hob_lbam = (new_sectors >> 32) & 0xff;
1246                 tf.hob_lbah = (new_sectors >> 40) & 0xff;
1247         } else {
1248                 tf.command = ATA_CMD_SET_MAX;
1249
1250                 tf.device |= (new_sectors >> 24) & 0xf;
1251         }
1252
1253         tf.protocol = ATA_PROT_NODATA;
1254         tf.device |= ATA_LBA;
1255
1256         tf.lbal = (new_sectors >> 0) & 0xff;
1257         tf.lbam = (new_sectors >> 8) & 0xff;
1258         tf.lbah = (new_sectors >> 16) & 0xff;
1259
1260         err_mask = ata_exec_internal(dev, &tf, NULL, DMA_NONE, NULL, 0, 0);
1261         if (err_mask) {
1262                 ata_dev_warn(dev,
1263                              "failed to set max address (err_mask=0x%x)\n",
1264                              err_mask);
1265                 if (err_mask == AC_ERR_DEV &&
1266                     (tf.error & (ATA_ABORTED | ATA_IDNF)))
1267                         return -EACCES;
1268                 return -EIO;
1269         }
1270
1271         return 0;
1272 }
1273
1274 /**
1275  *      ata_hpa_resize          -       Resize a device with an HPA set
1276  *      @dev: Device to resize
1277  *
1278  *      Read the size of an LBA28 or LBA48 disk with HPA features and resize
1279  *      it if required to the full size of the media. The caller must check
1280  *      the drive has the HPA feature set enabled.
1281  *
1282  *      RETURNS:
1283  *      0 on success, -errno on failure.
1284  */
1285 static int ata_hpa_resize(struct ata_device *dev)
1286 {
1287         bool print_info = ata_dev_print_info(dev);
1288         bool unlock_hpa = ata_ignore_hpa || dev->flags & ATA_DFLAG_UNLOCK_HPA;
1289         u64 sectors = ata_id_n_sectors(dev->id);
1290         u64 native_sectors;
1291         int rc;
1292
1293         /* do we need to do it? */
1294         if ((dev->class != ATA_DEV_ATA && dev->class != ATA_DEV_ZAC) ||
1295             !ata_id_has_lba(dev->id) || !ata_id_hpa_enabled(dev->id) ||
1296             (dev->quirks & ATA_QUIRK_BROKEN_HPA))
1297                 return 0;
1298
1299         /* read native max address */
1300         rc = ata_read_native_max_address(dev, &native_sectors);
1301         if (rc) {
1302                 /* If device aborted the command or HPA isn't going to
1303                  * be unlocked, skip HPA resizing.
1304                  */
1305                 if (rc == -EACCES || !unlock_hpa) {
1306                         ata_dev_warn(dev,
1307                                      "HPA support seems broken, skipping HPA handling\n");
1308                         dev->quirks |= ATA_QUIRK_BROKEN_HPA;
1309
1310                         /* we can continue if device aborted the command */
1311                         if (rc == -EACCES)
1312                                 rc = 0;
1313                 }
1314
1315                 return rc;
1316         }
1317         dev->n_native_sectors = native_sectors;
1318
1319         /* nothing to do? */
1320         if (native_sectors <= sectors || !unlock_hpa) {
1321                 if (!print_info || native_sectors == sectors)
1322                         return 0;
1323
1324                 if (native_sectors > sectors)
1325                         ata_dev_info(dev,
1326                                 "HPA detected: current %llu, native %llu\n",
1327                                 (unsigned long long)sectors,
1328                                 (unsigned long long)native_sectors);
1329                 else if (native_sectors < sectors)
1330                         ata_dev_warn(dev,
1331                                 "native sectors (%llu) is smaller than sectors (%llu)\n",
1332                                 (unsigned long long)native_sectors,
1333                                 (unsigned long long)sectors);
1334                 return 0;
1335         }
1336
1337         /* let's unlock HPA */
1338         rc = ata_set_max_sectors(dev, native_sectors);
1339         if (rc == -EACCES) {
1340                 /* if device aborted the command, skip HPA resizing */
1341                 ata_dev_warn(dev,
1342                              "device aborted resize (%llu -> %llu), skipping HPA handling\n",
1343                              (unsigned long long)sectors,
1344                              (unsigned long long)native_sectors);
1345                 dev->quirks |= ATA_QUIRK_BROKEN_HPA;
1346                 return 0;
1347         } else if (rc)
1348                 return rc;
1349
1350         /* re-read IDENTIFY data */
1351         rc = ata_dev_reread_id(dev, 0);
1352         if (rc) {
1353                 ata_dev_err(dev,
1354                             "failed to re-read IDENTIFY data after HPA resizing\n");
1355                 return rc;
1356         }
1357
1358         if (print_info) {
1359                 u64 new_sectors = ata_id_n_sectors(dev->id);
1360                 ata_dev_info(dev,
1361                         "HPA unlocked: %llu -> %llu, native %llu\n",
1362                         (unsigned long long)sectors,
1363                         (unsigned long long)new_sectors,
1364                         (unsigned long long)native_sectors);
1365         }
1366
1367         return 0;
1368 }
1369
1370 /**
1371  *      ata_dump_id - IDENTIFY DEVICE info debugging output
1372  *      @dev: device from which the information is fetched
1373  *      @id: IDENTIFY DEVICE page to dump
1374  *
1375  *      Dump selected 16-bit words from the given IDENTIFY DEVICE
1376  *      page.
1377  *
1378  *      LOCKING:
1379  *      caller.
1380  */
1381
1382 static inline void ata_dump_id(struct ata_device *dev, const u16 *id)
1383 {
1384         ata_dev_dbg(dev,
1385                 "49==0x%04x  53==0x%04x  63==0x%04x  64==0x%04x  75==0x%04x\n"
1386                 "80==0x%04x  81==0x%04x  82==0x%04x  83==0x%04x  84==0x%04x\n"
1387                 "88==0x%04x  93==0x%04x\n",
1388                 id[49], id[53], id[63], id[64], id[75], id[80],
1389                 id[81], id[82], id[83], id[84], id[88], id[93]);
1390 }
1391
1392 /**
1393  *      ata_id_xfermask - Compute xfermask from the given IDENTIFY data
1394  *      @id: IDENTIFY data to compute xfer mask from
1395  *
1396  *      Compute the xfermask for this device. This is not as trivial
1397  *      as it seems if we must consider early devices correctly.
1398  *
1399  *      FIXME: pre IDE drive timing (do we care ?).
1400  *
1401  *      LOCKING:
1402  *      None.
1403  *
1404  *      RETURNS:
1405  *      Computed xfermask
1406  */
1407 unsigned int ata_id_xfermask(const u16 *id)
1408 {
1409         unsigned int pio_mask, mwdma_mask, udma_mask;
1410
1411         /* Usual case. Word 53 indicates word 64 is valid */
1412         if (id[ATA_ID_FIELD_VALID] & (1 << 1)) {
1413                 pio_mask = id[ATA_ID_PIO_MODES] & 0x03;
1414                 pio_mask <<= 3;
1415                 pio_mask |= 0x7;
1416         } else {
1417                 /* If word 64 isn't valid then Word 51 high byte holds
1418                  * the PIO timing number for the maximum. Turn it into
1419                  * a mask.
1420                  */
1421                 u8 mode = (id[ATA_ID_OLD_PIO_MODES] >> 8) & 0xFF;
1422                 if (mode < 5)   /* Valid PIO range */
1423                         pio_mask = (2 << mode) - 1;
1424                 else
1425                         pio_mask = 1;
1426
1427                 /* But wait.. there's more. Design your standards by
1428                  * committee and you too can get a free iordy field to
1429                  * process. However it is the speeds not the modes that
1430                  * are supported... Note drivers using the timing API
1431                  * will get this right anyway
1432                  */
1433         }
1434
1435         mwdma_mask = id[ATA_ID_MWDMA_MODES] & 0x07;
1436
1437         if (ata_id_is_cfa(id)) {
1438                 /*
1439                  *      Process compact flash extended modes
1440                  */
1441                 int pio = (id[ATA_ID_CFA_MODES] >> 0) & 0x7;
1442                 int dma = (id[ATA_ID_CFA_MODES] >> 3) & 0x7;
1443
1444                 if (pio)
1445                         pio_mask |= (1 << 5);
1446                 if (pio > 1)
1447                         pio_mask |= (1 << 6);
1448                 if (dma)
1449                         mwdma_mask |= (1 << 3);
1450                 if (dma > 1)
1451                         mwdma_mask |= (1 << 4);
1452         }
1453
1454         udma_mask = 0;
1455         if (id[ATA_ID_FIELD_VALID] & (1 << 2))
1456                 udma_mask = id[ATA_ID_UDMA_MODES] & 0xff;
1457
1458         return ata_pack_xfermask(pio_mask, mwdma_mask, udma_mask);
1459 }
1460 EXPORT_SYMBOL_GPL(ata_id_xfermask);
1461
1462 static void ata_qc_complete_internal(struct ata_queued_cmd *qc)
1463 {
1464         struct completion *waiting = qc->private_data;
1465
1466         complete(waiting);
1467 }
1468
1469 /**
1470  *      ata_exec_internal - execute libata internal command
1471  *      @dev: Device to which the command is sent
1472  *      @tf: Taskfile registers for the command and the result
1473  *      @cdb: CDB for packet command
1474  *      @dma_dir: Data transfer direction of the command
1475  *      @buf: Data buffer of the command
1476  *      @buflen: Length of data buffer
1477  *      @timeout: Timeout in msecs (0 for default)
1478  *
1479  *      Executes libata internal command with timeout. @tf contains
1480  *      the command on entry and the result on return. Timeout and error
1481  *      conditions are reported via the return value. No recovery action
1482  *      is taken after a command times out. It is the caller's duty to
1483  *      clean up after timeout.
1484  *
1485  *      LOCKING:
1486  *      None.  Should be called with kernel context, might sleep.
1487  *
1488  *      RETURNS:
1489  *      Zero on success, AC_ERR_* mask on failure
1490  */
1491 unsigned int ata_exec_internal(struct ata_device *dev, struct ata_taskfile *tf,
1492                                const u8 *cdb, enum dma_data_direction dma_dir,
1493                                void *buf, unsigned int buflen,
1494                                unsigned int timeout)
1495 {
1496         struct ata_link *link = dev->link;
1497         struct ata_port *ap = link->ap;
1498         u8 command = tf->command;
1499         struct ata_queued_cmd *qc;
1500         struct scatterlist sgl;
1501         unsigned int preempted_tag;
1502         u32 preempted_sactive;
1503         u64 preempted_qc_active;
1504         int preempted_nr_active_links;
1505         bool auto_timeout = false;
1506         DECLARE_COMPLETION_ONSTACK(wait);
1507         unsigned long flags;
1508         unsigned int err_mask;
1509         int rc;
1510
1511         if (WARN_ON(dma_dir != DMA_NONE && !buf))
1512                 return AC_ERR_INVALID;
1513
1514         spin_lock_irqsave(ap->lock, flags);
1515
1516         /* No internal command while frozen */
1517         if (ata_port_is_frozen(ap)) {
1518                 spin_unlock_irqrestore(ap->lock, flags);
1519                 return AC_ERR_SYSTEM;
1520         }
1521
1522         /* Initialize internal qc */
1523         qc = __ata_qc_from_tag(ap, ATA_TAG_INTERNAL);
1524
1525         qc->tag = ATA_TAG_INTERNAL;
1526         qc->hw_tag = 0;
1527         qc->scsicmd = NULL;
1528         qc->ap = ap;
1529         qc->dev = dev;
1530         ata_qc_reinit(qc);
1531
1532         preempted_tag = link->active_tag;
1533         preempted_sactive = link->sactive;
1534         preempted_qc_active = ap->qc_active;
1535         preempted_nr_active_links = ap->nr_active_links;
1536         link->active_tag = ATA_TAG_POISON;
1537         link->sactive = 0;
1538         ap->qc_active = 0;
1539         ap->nr_active_links = 0;
1540
1541         /* Prepare and issue qc */
1542         qc->tf = *tf;
1543         if (cdb)
1544                 memcpy(qc->cdb, cdb, ATAPI_CDB_LEN);
1545
1546         /* Some SATA bridges need us to indicate data xfer direction */
1547         if (tf->protocol == ATAPI_PROT_DMA && (dev->flags & ATA_DFLAG_DMADIR) &&
1548             dma_dir == DMA_FROM_DEVICE)
1549                 qc->tf.feature |= ATAPI_DMADIR;
1550
1551         qc->flags |= ATA_QCFLAG_RESULT_TF;
1552         qc->dma_dir = dma_dir;
1553         if (dma_dir != DMA_NONE) {
1554                 sg_init_one(&sgl, buf, buflen);
1555                 ata_sg_init(qc, &sgl, 1);
1556                 qc->nbytes = buflen;
1557         }
1558
1559         qc->private_data = &wait;
1560         qc->complete_fn = ata_qc_complete_internal;
1561
1562         ata_qc_issue(qc);
1563
1564         spin_unlock_irqrestore(ap->lock, flags);
1565
1566         if (!timeout) {
1567                 if (ata_probe_timeout) {
1568                         timeout = ata_probe_timeout * 1000;
1569                 } else {
1570                         timeout = ata_internal_cmd_timeout(dev, command);
1571                         auto_timeout = true;
1572                 }
1573         }
1574
1575         ata_eh_release(ap);
1576
1577         rc = wait_for_completion_timeout(&wait, msecs_to_jiffies(timeout));
1578
1579         ata_eh_acquire(ap);
1580
1581         ata_sff_flush_pio_task(ap);
1582
1583         if (!rc) {
1584                 /*
1585                  * We are racing with irq here. If we lose, the following test
1586                  * prevents us from completing the qc twice. If we win, the port
1587                  * is frozen and will be cleaned up by ->post_internal_cmd().
1588                  */
1589                 spin_lock_irqsave(ap->lock, flags);
1590                 if (qc->flags & ATA_QCFLAG_ACTIVE) {
1591                         qc->err_mask |= AC_ERR_TIMEOUT;
1592                         ata_port_freeze(ap);
1593                         ata_dev_warn(dev, "qc timeout after %u msecs (cmd 0x%x)\n",
1594                                      timeout, command);
1595                 }
1596                 spin_unlock_irqrestore(ap->lock, flags);
1597         }
1598
1599         if (ap->ops->post_internal_cmd)
1600                 ap->ops->post_internal_cmd(qc);
1601
1602         /* Perform minimal error analysis */
1603         if (qc->flags & ATA_QCFLAG_EH) {
1604                 if (qc->result_tf.status & (ATA_ERR | ATA_DF))
1605                         qc->err_mask |= AC_ERR_DEV;
1606
1607                 if (!qc->err_mask)
1608                         qc->err_mask |= AC_ERR_OTHER;
1609
1610                 if (qc->err_mask & ~AC_ERR_OTHER)
1611                         qc->err_mask &= ~AC_ERR_OTHER;
1612         } else if (qc->tf.command == ATA_CMD_REQ_SENSE_DATA) {
1613                 qc->result_tf.status |= ATA_SENSE;
1614         }
1615
1616         /* Finish up */
1617         spin_lock_irqsave(ap->lock, flags);
1618
1619         *tf = qc->result_tf;
1620         err_mask = qc->err_mask;
1621
1622         ata_qc_free(qc);
1623         link->active_tag = preempted_tag;
1624         link->sactive = preempted_sactive;
1625         ap->qc_active = preempted_qc_active;
1626         ap->nr_active_links = preempted_nr_active_links;
1627
1628         spin_unlock_irqrestore(ap->lock, flags);
1629
1630         if ((err_mask & AC_ERR_TIMEOUT) && auto_timeout)
1631                 ata_internal_cmd_timed_out(dev, command);
1632
1633         return err_mask;
1634 }
1635
1636 /**
1637  *      ata_pio_need_iordy      -       check if iordy needed
1638  *      @adev: ATA device
1639  *
1640  *      Check if the current speed of the device requires IORDY. Used
1641  *      by various controllers for chip configuration.
1642  */
1643 unsigned int ata_pio_need_iordy(const struct ata_device *adev)
1644 {
1645         /* Don't set IORDY if we're preparing for reset.  IORDY may
1646          * lead to controller lock up on certain controllers if the
1647          * port is not occupied.  See bko#11703 for details.
1648          */
1649         if (adev->link->ap->pflags & ATA_PFLAG_RESETTING)
1650                 return 0;
1651         /* Controller doesn't support IORDY.  Probably a pointless
1652          * check as the caller should know this.
1653          */
1654         if (adev->link->ap->flags & ATA_FLAG_NO_IORDY)
1655                 return 0;
1656         /* CF spec. r4.1 Table 22 says no iordy on PIO5 and PIO6.  */
1657         if (ata_id_is_cfa(adev->id)
1658             && (adev->pio_mode == XFER_PIO_5 || adev->pio_mode == XFER_PIO_6))
1659                 return 0;
1660         /* PIO3 and higher it is mandatory */
1661         if (adev->pio_mode > XFER_PIO_2)
1662                 return 1;
1663         /* We turn it on when possible */
1664         if (ata_id_has_iordy(adev->id))
1665                 return 1;
1666         return 0;
1667 }
1668 EXPORT_SYMBOL_GPL(ata_pio_need_iordy);
1669
1670 /**
1671  *      ata_pio_mask_no_iordy   -       Return the non IORDY mask
1672  *      @adev: ATA device
1673  *
1674  *      Compute the highest mode possible if we are not using iordy. Return
1675  *      -1 if no iordy mode is available.
1676  */
1677 static u32 ata_pio_mask_no_iordy(const struct ata_device *adev)
1678 {
1679         /* If we have no drive specific rule, then PIO 2 is non IORDY */
1680         if (adev->id[ATA_ID_FIELD_VALID] & 2) { /* EIDE */
1681                 u16 pio = adev->id[ATA_ID_EIDE_PIO];
1682                 /* Is the speed faster than the drive allows non IORDY ? */
1683                 if (pio) {
1684                         /* This is cycle times not frequency - watch the logic! */
1685                         if (pio > 240)  /* PIO2 is 240nS per cycle */
1686                                 return 3 << ATA_SHIFT_PIO;
1687                         return 7 << ATA_SHIFT_PIO;
1688                 }
1689         }
1690         return 3 << ATA_SHIFT_PIO;
1691 }
1692
1693 /**
1694  *      ata_do_dev_read_id              -       default ID read method
1695  *      @dev: device
1696  *      @tf: proposed taskfile
1697  *      @id: data buffer
1698  *
1699  *      Issue the identify taskfile and hand back the buffer containing
1700  *      identify data. For some RAID controllers and for pre ATA devices
1701  *      this function is wrapped or replaced by the driver
1702  */
1703 unsigned int ata_do_dev_read_id(struct ata_device *dev,
1704                                 struct ata_taskfile *tf, __le16 *id)
1705 {
1706         return ata_exec_internal(dev, tf, NULL, DMA_FROM_DEVICE,
1707                                      id, sizeof(id[0]) * ATA_ID_WORDS, 0);
1708 }
1709 EXPORT_SYMBOL_GPL(ata_do_dev_read_id);
1710
1711 /**
1712  *      ata_dev_read_id - Read ID data from the specified device
1713  *      @dev: target device
1714  *      @p_class: pointer to class of the target device (may be changed)
1715  *      @flags: ATA_READID_* flags
1716  *      @id: buffer to read IDENTIFY data into
1717  *
1718  *      Read ID data from the specified device.  ATA_CMD_ID_ATA is
1719  *      performed on ATA devices and ATA_CMD_ID_ATAPI on ATAPI
1720  *      devices.  This function also issues ATA_CMD_INIT_DEV_PARAMS
1721  *      for pre-ATA4 drives.
1722  *
1723  *      FIXME: ATA_CMD_ID_ATA is optional for early drives and right
1724  *      now we abort if we hit that case.
1725  *
1726  *      LOCKING:
1727  *      Kernel thread context (may sleep)
1728  *
1729  *      RETURNS:
1730  *      0 on success, -errno otherwise.
1731  */
1732 int ata_dev_read_id(struct ata_device *dev, unsigned int *p_class,
1733                     unsigned int flags, u16 *id)
1734 {
1735         struct ata_port *ap = dev->link->ap;
1736         unsigned int class = *p_class;
1737         struct ata_taskfile tf;
1738         unsigned int err_mask = 0;
1739         const char *reason;
1740         bool is_semb = class == ATA_DEV_SEMB;
1741         int may_fallback = 1, tried_spinup = 0;
1742         int rc;
1743
1744 retry:
1745         ata_tf_init(dev, &tf);
1746
1747         switch (class) {
1748         case ATA_DEV_SEMB:
1749                 class = ATA_DEV_ATA;    /* some hard drives report SEMB sig */
1750                 fallthrough;
1751         case ATA_DEV_ATA:
1752         case ATA_DEV_ZAC:
1753                 tf.command = ATA_CMD_ID_ATA;
1754                 break;
1755         case ATA_DEV_ATAPI:
1756                 tf.command = ATA_CMD_ID_ATAPI;
1757                 break;
1758         default:
1759                 rc = -ENODEV;
1760                 reason = "unsupported class";
1761                 goto err_out;
1762         }
1763
1764         tf.protocol = ATA_PROT_PIO;
1765
1766         /* Some devices choke if TF registers contain garbage.  Make
1767          * sure those are properly initialized.
1768          */
1769         tf.flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE;
1770
1771         /* Device presence detection is unreliable on some
1772          * controllers.  Always poll IDENTIFY if available.
1773          */
1774         tf.flags |= ATA_TFLAG_POLLING;
1775
1776         if (ap->ops->read_id)
1777                 err_mask = ap->ops->read_id(dev, &tf, (__le16 *)id);
1778         else
1779                 err_mask = ata_do_dev_read_id(dev, &tf, (__le16 *)id);
1780
1781         if (err_mask) {
1782                 if (err_mask & AC_ERR_NODEV_HINT) {
1783                         ata_dev_dbg(dev, "NODEV after polling detection\n");
1784                         return -ENOENT;
1785                 }
1786
1787                 if (is_semb) {
1788                         ata_dev_info(dev,
1789                      "IDENTIFY failed on device w/ SEMB sig, disabled\n");
1790                         /* SEMB is not supported yet */
1791                         *p_class = ATA_DEV_SEMB_UNSUP;
1792                         return 0;
1793                 }
1794
1795                 if ((err_mask == AC_ERR_DEV) && (tf.error & ATA_ABORTED)) {
1796                         /* Device or controller might have reported
1797                          * the wrong device class.  Give a shot at the
1798                          * other IDENTIFY if the current one is
1799                          * aborted by the device.
1800                          */
1801                         if (may_fallback) {
1802                                 may_fallback = 0;
1803
1804                                 if (class == ATA_DEV_ATA)
1805                                         class = ATA_DEV_ATAPI;
1806                                 else
1807                                         class = ATA_DEV_ATA;
1808                                 goto retry;
1809                         }
1810
1811                         /* Control reaches here iff the device aborted
1812                          * both flavors of IDENTIFYs which happens
1813                          * sometimes with phantom devices.
1814                          */
1815                         ata_dev_dbg(dev,
1816                                     "both IDENTIFYs aborted, assuming NODEV\n");
1817                         return -ENOENT;
1818                 }
1819
1820                 rc = -EIO;
1821                 reason = "I/O error";
1822                 goto err_out;
1823         }
1824
1825         if (dev->quirks & ATA_QUIRK_DUMP_ID) {
1826                 ata_dev_info(dev, "dumping IDENTIFY data, "
1827                             "class=%d may_fallback=%d tried_spinup=%d\n",
1828                             class, may_fallback, tried_spinup);
1829                 print_hex_dump(KERN_INFO, "", DUMP_PREFIX_OFFSET,
1830                                16, 2, id, ATA_ID_WORDS * sizeof(*id), true);
1831         }
1832
1833         /* Falling back doesn't make sense if ID data was read
1834          * successfully at least once.
1835          */
1836         may_fallback = 0;
1837
1838         swap_buf_le16(id, ATA_ID_WORDS);
1839
1840         /* sanity check */
1841         rc = -EINVAL;
1842         reason = "device reports invalid type";
1843
1844         if (class == ATA_DEV_ATA || class == ATA_DEV_ZAC) {
1845                 if (!ata_id_is_ata(id) && !ata_id_is_cfa(id))
1846                         goto err_out;
1847                 if (ap->host->flags & ATA_HOST_IGNORE_ATA &&
1848                                                         ata_id_is_ata(id)) {
1849                         ata_dev_dbg(dev,
1850                                 "host indicates ignore ATA devices, ignored\n");
1851                         return -ENOENT;
1852                 }
1853         } else {
1854                 if (ata_id_is_ata(id))
1855                         goto err_out;
1856         }
1857
1858         if (!tried_spinup && (id[2] == 0x37c8 || id[2] == 0x738c)) {
1859                 tried_spinup = 1;
1860                 /*
1861                  * Drive powered-up in standby mode, and requires a specific
1862                  * SET_FEATURES spin-up subcommand before it will accept
1863                  * anything other than the original IDENTIFY command.
1864                  */
1865                 err_mask = ata_dev_set_feature(dev, SETFEATURES_SPINUP, 0);
1866                 if (err_mask && id[2] != 0x738c) {
1867                         rc = -EIO;
1868                         reason = "SPINUP failed";
1869                         goto err_out;
1870                 }
1871                 /*
1872                  * If the drive initially returned incomplete IDENTIFY info,
1873                  * we now must reissue the IDENTIFY command.
1874                  */
1875                 if (id[2] == 0x37c8)
1876                         goto retry;
1877         }
1878
1879         if ((flags & ATA_READID_POSTRESET) &&
1880             (class == ATA_DEV_ATA || class == ATA_DEV_ZAC)) {
1881                 /*
1882                  * The exact sequence expected by certain pre-ATA4 drives is:
1883                  * SRST RESET
1884                  * IDENTIFY (optional in early ATA)
1885                  * INITIALIZE DEVICE PARAMETERS (later IDE and ATA)
1886                  * anything else..
1887                  * Some drives were very specific about that exact sequence.
1888                  *
1889                  * Note that ATA4 says lba is mandatory so the second check
1890                  * should never trigger.
1891                  */
1892                 if (ata_id_major_version(id) < 4 || !ata_id_has_lba(id)) {
1893                         err_mask = ata_dev_init_params(dev, id[3], id[6]);
1894                         if (err_mask) {
1895                                 rc = -EIO;
1896                                 reason = "INIT_DEV_PARAMS failed";
1897                                 goto err_out;
1898                         }
1899
1900                         /* current CHS translation info (id[53-58]) might be
1901                          * changed. reread the identify device info.
1902                          */
1903                         flags &= ~ATA_READID_POSTRESET;
1904                         goto retry;
1905                 }
1906         }
1907
1908         *p_class = class;
1909
1910         return 0;
1911
1912  err_out:
1913         ata_dev_warn(dev, "failed to IDENTIFY (%s, err_mask=0x%x)\n",
1914                      reason, err_mask);
1915         return rc;
1916 }
1917
1918 bool ata_dev_power_init_tf(struct ata_device *dev, struct ata_taskfile *tf,
1919                            bool set_active)
1920 {
1921         /* Only applies to ATA and ZAC devices */
1922         if (dev->class != ATA_DEV_ATA && dev->class != ATA_DEV_ZAC)
1923                 return false;
1924
1925         ata_tf_init(dev, tf);
1926         tf->flags |= ATA_TFLAG_DEVICE | ATA_TFLAG_ISADDR;
1927         tf->protocol = ATA_PROT_NODATA;
1928
1929         if (set_active) {
1930                 /* VERIFY for 1 sector at lba=0 */
1931                 tf->command = ATA_CMD_VERIFY;
1932                 tf->nsect = 1;
1933                 if (dev->flags & ATA_DFLAG_LBA) {
1934                         tf->flags |= ATA_TFLAG_LBA;
1935                         tf->device |= ATA_LBA;
1936                 } else {
1937                         /* CHS */
1938                         tf->lbal = 0x1; /* sect */
1939                 }
1940         } else {
1941                 tf->command = ATA_CMD_STANDBYNOW1;
1942         }
1943
1944         return true;
1945 }
1946
1947 static bool ata_dev_power_is_active(struct ata_device *dev)
1948 {
1949         struct ata_taskfile tf;
1950         unsigned int err_mask;
1951
1952         ata_tf_init(dev, &tf);
1953         tf.flags |= ATA_TFLAG_DEVICE | ATA_TFLAG_ISADDR;
1954         tf.protocol = ATA_PROT_NODATA;
1955         tf.command = ATA_CMD_CHK_POWER;
1956
1957         err_mask = ata_exec_internal(dev, &tf, NULL, DMA_NONE, NULL, 0, 0);
1958         if (err_mask) {
1959                 ata_dev_err(dev, "Check power mode failed (err_mask=0x%x)\n",
1960                             err_mask);
1961                 /*
1962                  * Assume we are in standby mode so that we always force a
1963                  * spinup in ata_dev_power_set_active().
1964                  */
1965                 return false;
1966         }
1967
1968         ata_dev_dbg(dev, "Power mode: 0x%02x\n", tf.nsect);
1969
1970         /* Active or idle */
1971         return tf.nsect == 0xff;
1972 }
1973
1974 /**
1975  *      ata_dev_power_set_standby - Set a device power mode to standby
1976  *      @dev: target device
1977  *
1978  *      Issue a STANDBY IMMEDIATE command to set a device power mode to standby.
1979  *      For an HDD device, this spins down the disks.
1980  *
1981  *      LOCKING:
1982  *      Kernel thread context (may sleep).
1983  */
1984 void ata_dev_power_set_standby(struct ata_device *dev)
1985 {
1986         unsigned long ap_flags = dev->link->ap->flags;
1987         struct ata_taskfile tf;
1988         unsigned int err_mask;
1989
1990         /* If the device is already sleeping or in standby, do nothing. */
1991         if ((dev->flags & ATA_DFLAG_SLEEPING) ||
1992             !ata_dev_power_is_active(dev))
1993                 return;
1994
1995         /*
1996          * Some odd clown BIOSes issue spindown on power off (ACPI S4 or S5)
1997          * causing some drives to spin up and down again. For these, do nothing
1998          * if we are being called on shutdown.
1999          */
2000         if ((ap_flags & ATA_FLAG_NO_POWEROFF_SPINDOWN) &&
2001             system_state == SYSTEM_POWER_OFF)
2002                 return;
2003
2004         if ((ap_flags & ATA_FLAG_NO_HIBERNATE_SPINDOWN) &&
2005             system_entering_hibernation())
2006                 return;
2007
2008         /* Issue STANDBY IMMEDIATE command only if supported by the device */
2009         if (!ata_dev_power_init_tf(dev, &tf, false))
2010                 return;
2011
2012         ata_dev_notice(dev, "Entering standby power mode\n");
2013
2014         err_mask = ata_exec_internal(dev, &tf, NULL, DMA_NONE, NULL, 0, 0);
2015         if (err_mask)
2016                 ata_dev_err(dev, "STANDBY IMMEDIATE failed (err_mask=0x%x)\n",
2017                             err_mask);
2018 }
2019
2020 /**
2021  *      ata_dev_power_set_active -  Set a device power mode to active
2022  *      @dev: target device
2023  *
2024  *      Issue a VERIFY command to enter to ensure that the device is in the
2025  *      active power mode. For a spun-down HDD (standby or idle power mode),
2026  *      the VERIFY command will complete after the disk spins up.
2027  *
2028  *      LOCKING:
2029  *      Kernel thread context (may sleep).
2030  */
2031 void ata_dev_power_set_active(struct ata_device *dev)
2032 {
2033         struct ata_taskfile tf;
2034         unsigned int err_mask;
2035
2036         /*
2037          * Issue READ VERIFY SECTORS command for 1 sector at lba=0 only
2038          * if supported by the device.
2039          */
2040         if (!ata_dev_power_init_tf(dev, &tf, true))
2041                 return;
2042
2043         /*
2044          * Check the device power state & condition and force a spinup with
2045          * VERIFY command only if the drive is not already ACTIVE or IDLE.
2046          */
2047         if (ata_dev_power_is_active(dev))
2048                 return;
2049
2050         ata_dev_notice(dev, "Entering active power mode\n");
2051
2052         err_mask = ata_exec_internal(dev, &tf, NULL, DMA_NONE, NULL, 0, 0);
2053         if (err_mask)
2054                 ata_dev_err(dev, "VERIFY failed (err_mask=0x%x)\n",
2055                             err_mask);
2056 }
2057
2058 /**
2059  *      ata_read_log_page - read a specific log page
2060  *      @dev: target device
2061  *      @log: log to read
2062  *      @page: page to read
2063  *      @buf: buffer to store read page
2064  *      @sectors: number of sectors to read
2065  *
2066  *      Read log page using READ_LOG_EXT command.
2067  *
2068  *      LOCKING:
2069  *      Kernel thread context (may sleep).
2070  *
2071  *      RETURNS:
2072  *      0 on success, AC_ERR_* mask otherwise.
2073  */
2074 unsigned int ata_read_log_page(struct ata_device *dev, u8 log,
2075                                u8 page, void *buf, unsigned int sectors)
2076 {
2077         unsigned long ap_flags = dev->link->ap->flags;
2078         struct ata_taskfile tf;
2079         unsigned int err_mask;
2080         bool dma = false;
2081
2082         ata_dev_dbg(dev, "read log page - log 0x%x, page 0x%x\n", log, page);
2083
2084         /*
2085          * Return error without actually issuing the command on controllers
2086          * which e.g. lockup on a read log page.
2087          */
2088         if (ap_flags & ATA_FLAG_NO_LOG_PAGE)
2089                 return AC_ERR_DEV;
2090
2091 retry:
2092         ata_tf_init(dev, &tf);
2093         if (ata_dma_enabled(dev) && ata_id_has_read_log_dma_ext(dev->id) &&
2094             !(dev->quirks & ATA_QUIRK_NO_DMA_LOG)) {
2095                 tf.command = ATA_CMD_READ_LOG_DMA_EXT;
2096                 tf.protocol = ATA_PROT_DMA;
2097                 dma = true;
2098         } else {
2099                 tf.command = ATA_CMD_READ_LOG_EXT;
2100                 tf.protocol = ATA_PROT_PIO;
2101                 dma = false;
2102         }
2103         tf.lbal = log;
2104         tf.lbam = page;
2105         tf.nsect = sectors;
2106         tf.hob_nsect = sectors >> 8;
2107         tf.flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_LBA48 | ATA_TFLAG_DEVICE;
2108
2109         err_mask = ata_exec_internal(dev, &tf, NULL, DMA_FROM_DEVICE,
2110                                      buf, sectors * ATA_SECT_SIZE, 0);
2111
2112         if (err_mask) {
2113                 if (dma) {
2114                         dev->quirks |= ATA_QUIRK_NO_DMA_LOG;
2115                         if (!ata_port_is_frozen(dev->link->ap))
2116                                 goto retry;
2117                 }
2118                 ata_dev_err(dev,
2119                             "Read log 0x%02x page 0x%02x failed, Emask 0x%x\n",
2120                             (unsigned int)log, (unsigned int)page, err_mask);
2121         }
2122
2123         return err_mask;
2124 }
2125
2126 static int ata_log_supported(struct ata_device *dev, u8 log)
2127 {
2128         if (dev->quirks & ATA_QUIRK_NO_LOG_DIR)
2129                 return 0;
2130
2131         if (ata_read_log_page(dev, ATA_LOG_DIRECTORY, 0, dev->sector_buf, 1))
2132                 return 0;
2133         return get_unaligned_le16(&dev->sector_buf[log * 2]);
2134 }
2135
2136 static bool ata_identify_page_supported(struct ata_device *dev, u8 page)
2137 {
2138         unsigned int err, i;
2139
2140         if (dev->quirks & ATA_QUIRK_NO_ID_DEV_LOG)
2141                 return false;
2142
2143         if (!ata_log_supported(dev, ATA_LOG_IDENTIFY_DEVICE)) {
2144                 /*
2145                  * IDENTIFY DEVICE data log is defined as mandatory starting
2146                  * with ACS-3 (ATA version 10). Warn about the missing log
2147                  * for drives which implement this ATA level or above.
2148                  */
2149                 if (ata_id_major_version(dev->id) >= 10)
2150                         ata_dev_warn(dev,
2151                                 "ATA Identify Device Log not supported\n");
2152                 dev->quirks |= ATA_QUIRK_NO_ID_DEV_LOG;
2153                 return false;
2154         }
2155
2156         /*
2157          * Read IDENTIFY DEVICE data log, page 0, to figure out if the page is
2158          * supported.
2159          */
2160         err = ata_read_log_page(dev, ATA_LOG_IDENTIFY_DEVICE, 0,
2161                                 dev->sector_buf, 1);
2162         if (err)
2163                 return false;
2164
2165         for (i = 0; i < dev->sector_buf[8]; i++) {
2166                 if (dev->sector_buf[9 + i] == page)
2167                         return true;
2168         }
2169
2170         return false;
2171 }
2172
2173 static int ata_do_link_spd_quirk(struct ata_device *dev)
2174 {
2175         struct ata_link *plink = ata_dev_phys_link(dev);
2176         u32 target, target_limit;
2177
2178         if (!sata_scr_valid(plink))
2179                 return 0;
2180
2181         if (dev->quirks & ATA_QUIRK_1_5_GBPS)
2182                 target = 1;
2183         else
2184                 return 0;
2185
2186         target_limit = (1 << target) - 1;
2187
2188         /* if already on stricter limit, no need to push further */
2189         if (plink->sata_spd_limit <= target_limit)
2190                 return 0;
2191
2192         plink->sata_spd_limit = target_limit;
2193
2194         /* Request another EH round by returning -EAGAIN if link is
2195          * going faster than the target speed.  Forward progress is
2196          * guaranteed by setting sata_spd_limit to target_limit above.
2197          */
2198         if (plink->sata_spd > target) {
2199                 ata_dev_info(dev, "applying link speed limit quirk to %s\n",
2200                              sata_spd_string(target));
2201                 return -EAGAIN;
2202         }
2203         return 0;
2204 }
2205
2206 static inline bool ata_dev_knobble(struct ata_device *dev)
2207 {
2208         struct ata_port *ap = dev->link->ap;
2209
2210         if (ata_dev_quirks(dev) & ATA_QUIRK_BRIDGE_OK)
2211                 return false;
2212
2213         return ((ap->cbl == ATA_CBL_SATA) && (!ata_id_is_sata(dev->id)));
2214 }
2215
2216 static void ata_dev_config_ncq_send_recv(struct ata_device *dev)
2217 {
2218         unsigned int err_mask;
2219
2220         if (!ata_log_supported(dev, ATA_LOG_NCQ_SEND_RECV)) {
2221                 ata_dev_warn(dev, "NCQ Send/Recv Log not supported\n");
2222                 return;
2223         }
2224         err_mask = ata_read_log_page(dev, ATA_LOG_NCQ_SEND_RECV,
2225                                      0, dev->sector_buf, 1);
2226         if (!err_mask) {
2227                 u8 *cmds = dev->ncq_send_recv_cmds;
2228
2229                 dev->flags |= ATA_DFLAG_NCQ_SEND_RECV;
2230                 memcpy(cmds, dev->sector_buf, ATA_LOG_NCQ_SEND_RECV_SIZE);
2231
2232                 if (dev->quirks & ATA_QUIRK_NO_NCQ_TRIM) {
2233                         ata_dev_dbg(dev, "disabling queued TRIM support\n");
2234                         cmds[ATA_LOG_NCQ_SEND_RECV_DSM_OFFSET] &=
2235                                 ~ATA_LOG_NCQ_SEND_RECV_DSM_TRIM;
2236                 }
2237         }
2238 }
2239
2240 static void ata_dev_config_ncq_non_data(struct ata_device *dev)
2241 {
2242         unsigned int err_mask;
2243
2244         if (!ata_log_supported(dev, ATA_LOG_NCQ_NON_DATA)) {
2245                 ata_dev_warn(dev,
2246                              "NCQ Send/Recv Log not supported\n");
2247                 return;
2248         }
2249         err_mask = ata_read_log_page(dev, ATA_LOG_NCQ_NON_DATA,
2250                                      0, dev->sector_buf, 1);
2251         if (!err_mask)
2252                 memcpy(dev->ncq_non_data_cmds, dev->sector_buf,
2253                        ATA_LOG_NCQ_NON_DATA_SIZE);
2254 }
2255
2256 static void ata_dev_config_ncq_prio(struct ata_device *dev)
2257 {
2258         unsigned int err_mask;
2259
2260         if (!ata_identify_page_supported(dev, ATA_LOG_SATA_SETTINGS))
2261                 return;
2262
2263         err_mask = ata_read_log_page(dev,
2264                                      ATA_LOG_IDENTIFY_DEVICE,
2265                                      ATA_LOG_SATA_SETTINGS,
2266                                      dev->sector_buf, 1);
2267         if (err_mask)
2268                 goto not_supported;
2269
2270         if (!(dev->sector_buf[ATA_LOG_NCQ_PRIO_OFFSET] & BIT(3)))
2271                 goto not_supported;
2272
2273         dev->flags |= ATA_DFLAG_NCQ_PRIO;
2274
2275         return;
2276
2277 not_supported:
2278         dev->flags &= ~ATA_DFLAG_NCQ_PRIO_ENABLED;
2279         dev->flags &= ~ATA_DFLAG_NCQ_PRIO;
2280 }
2281
2282 static bool ata_dev_check_adapter(struct ata_device *dev,
2283                                   unsigned short vendor_id)
2284 {
2285         struct pci_dev *pcidev = NULL;
2286         struct device *parent_dev = NULL;
2287
2288         for (parent_dev = dev->tdev.parent; parent_dev != NULL;
2289              parent_dev = parent_dev->parent) {
2290                 if (dev_is_pci(parent_dev)) {
2291                         pcidev = to_pci_dev(parent_dev);
2292                         if (pcidev->vendor == vendor_id)
2293                                 return true;
2294                         break;
2295                 }
2296         }
2297
2298         return false;
2299 }
2300
2301 static int ata_dev_config_ncq(struct ata_device *dev,
2302                                char *desc, size_t desc_sz)
2303 {
2304         struct ata_port *ap = dev->link->ap;
2305         int hdepth = 0, ddepth = ata_id_queue_depth(dev->id);
2306         unsigned int err_mask;
2307         char *aa_desc = "";
2308
2309         if (!ata_id_has_ncq(dev->id)) {
2310                 desc[0] = '\0';
2311                 return 0;
2312         }
2313         if (!IS_ENABLED(CONFIG_SATA_HOST))
2314                 return 0;
2315         if (dev->quirks & ATA_QUIRK_NONCQ) {
2316                 snprintf(desc, desc_sz, "NCQ (not used)");
2317                 return 0;
2318         }
2319
2320         if (dev->quirks & ATA_QUIRK_NO_NCQ_ON_ATI &&
2321             ata_dev_check_adapter(dev, PCI_VENDOR_ID_ATI)) {
2322                 snprintf(desc, desc_sz, "NCQ (not used)");
2323                 return 0;
2324         }
2325
2326         if (ap->flags & ATA_FLAG_NCQ) {
2327                 hdepth = min(ap->scsi_host->can_queue, ATA_MAX_QUEUE);
2328                 dev->flags |= ATA_DFLAG_NCQ;
2329         }
2330
2331         if (!(dev->quirks & ATA_QUIRK_BROKEN_FPDMA_AA) &&
2332                 (ap->flags & ATA_FLAG_FPDMA_AA) &&
2333                 ata_id_has_fpdma_aa(dev->id)) {
2334                 err_mask = ata_dev_set_feature(dev, SETFEATURES_SATA_ENABLE,
2335                         SATA_FPDMA_AA);
2336                 if (err_mask) {
2337                         ata_dev_err(dev,
2338                                     "failed to enable AA (error_mask=0x%x)\n",
2339                                     err_mask);
2340                         if (err_mask != AC_ERR_DEV) {
2341                                 dev->quirks |= ATA_QUIRK_BROKEN_FPDMA_AA;
2342                                 return -EIO;
2343                         }
2344                 } else
2345                         aa_desc = ", AA";
2346         }
2347
2348         if (hdepth >= ddepth)
2349                 snprintf(desc, desc_sz, "NCQ (depth %d)%s", ddepth, aa_desc);
2350         else
2351                 snprintf(desc, desc_sz, "NCQ (depth %d/%d)%s", hdepth,
2352                         ddepth, aa_desc);
2353
2354         if ((ap->flags & ATA_FLAG_FPDMA_AUX)) {
2355                 if (ata_id_has_ncq_send_and_recv(dev->id))
2356                         ata_dev_config_ncq_send_recv(dev);
2357                 if (ata_id_has_ncq_non_data(dev->id))
2358                         ata_dev_config_ncq_non_data(dev);
2359                 if (ata_id_has_ncq_prio(dev->id))
2360                         ata_dev_config_ncq_prio(dev);
2361         }
2362
2363         return 0;
2364 }
2365
2366 static void ata_dev_config_sense_reporting(struct ata_device *dev)
2367 {
2368         unsigned int err_mask;
2369
2370         if (!ata_id_has_sense_reporting(dev->id))
2371                 return;
2372
2373         if (ata_id_sense_reporting_enabled(dev->id))
2374                 return;
2375
2376         err_mask = ata_dev_set_feature(dev, SETFEATURE_SENSE_DATA, 0x1);
2377         if (err_mask) {
2378                 ata_dev_dbg(dev,
2379                             "failed to enable Sense Data Reporting, Emask 0x%x\n",
2380                             err_mask);
2381         }
2382 }
2383
2384 static void ata_dev_config_zac(struct ata_device *dev)
2385 {
2386         unsigned int err_mask;
2387         u8 *identify_buf = dev->sector_buf;
2388
2389         dev->zac_zones_optimal_open = U32_MAX;
2390         dev->zac_zones_optimal_nonseq = U32_MAX;
2391         dev->zac_zones_max_open = U32_MAX;
2392
2393         /*
2394          * Always set the 'ZAC' flag for Host-managed devices.
2395          */
2396         if (dev->class == ATA_DEV_ZAC)
2397                 dev->flags |= ATA_DFLAG_ZAC;
2398         else if (ata_id_zoned_cap(dev->id) == 0x01)
2399                 /*
2400                  * Check for host-aware devices.
2401                  */
2402                 dev->flags |= ATA_DFLAG_ZAC;
2403
2404         if (!(dev->flags & ATA_DFLAG_ZAC))
2405                 return;
2406
2407         if (!ata_identify_page_supported(dev, ATA_LOG_ZONED_INFORMATION)) {
2408                 ata_dev_warn(dev,
2409                              "ATA Zoned Information Log not supported\n");
2410                 return;
2411         }
2412
2413         /*
2414          * Read IDENTIFY DEVICE data log, page 9 (Zoned-device information)
2415          */
2416         err_mask = ata_read_log_page(dev, ATA_LOG_IDENTIFY_DEVICE,
2417                                      ATA_LOG_ZONED_INFORMATION,
2418                                      identify_buf, 1);
2419         if (!err_mask) {
2420                 u64 zoned_cap, opt_open, opt_nonseq, max_open;
2421
2422                 zoned_cap = get_unaligned_le64(&identify_buf[8]);
2423                 if ((zoned_cap >> 63))
2424                         dev->zac_zoned_cap = (zoned_cap & 1);
2425                 opt_open = get_unaligned_le64(&identify_buf[24]);
2426                 if ((opt_open >> 63))
2427                         dev->zac_zones_optimal_open = (u32)opt_open;
2428                 opt_nonseq = get_unaligned_le64(&identify_buf[32]);
2429                 if ((opt_nonseq >> 63))
2430                         dev->zac_zones_optimal_nonseq = (u32)opt_nonseq;
2431                 max_open = get_unaligned_le64(&identify_buf[40]);
2432                 if ((max_open >> 63))
2433                         dev->zac_zones_max_open = (u32)max_open;
2434         }
2435 }
2436
2437 static void ata_dev_config_trusted(struct ata_device *dev)
2438 {
2439         u64 trusted_cap;
2440         unsigned int err;
2441
2442         if (!ata_id_has_trusted(dev->id))
2443                 return;
2444
2445         if (!ata_identify_page_supported(dev, ATA_LOG_SECURITY)) {
2446                 ata_dev_warn(dev,
2447                              "Security Log not supported\n");
2448                 return;
2449         }
2450
2451         err = ata_read_log_page(dev, ATA_LOG_IDENTIFY_DEVICE, ATA_LOG_SECURITY,
2452                                 dev->sector_buf, 1);
2453         if (err)
2454                 return;
2455
2456         trusted_cap = get_unaligned_le64(&dev->sector_buf[40]);
2457         if (!(trusted_cap & (1ULL << 63))) {
2458                 ata_dev_dbg(dev,
2459                             "Trusted Computing capability qword not valid!\n");
2460                 return;
2461         }
2462
2463         if (trusted_cap & (1 << 0))
2464                 dev->flags |= ATA_DFLAG_TRUSTED;
2465 }
2466
2467 void ata_dev_cleanup_cdl_resources(struct ata_device *dev)
2468 {
2469         kfree(dev->cdl);
2470         dev->cdl = NULL;
2471 }
2472
2473 static int ata_dev_init_cdl_resources(struct ata_device *dev)
2474 {
2475         struct ata_cdl *cdl = dev->cdl;
2476         unsigned int err_mask;
2477
2478         if (!cdl) {
2479                 cdl = kzalloc(sizeof(*cdl), GFP_KERNEL);
2480                 if (!cdl)
2481                         return -ENOMEM;
2482                 dev->cdl = cdl;
2483         }
2484
2485         err_mask = ata_read_log_page(dev, ATA_LOG_CDL, 0, cdl->desc_log_buf,
2486                                      ATA_LOG_CDL_SIZE / ATA_SECT_SIZE);
2487         if (err_mask) {
2488                 ata_dev_warn(dev, "Read Command Duration Limits log failed\n");
2489                 ata_dev_cleanup_cdl_resources(dev);
2490                 return -EIO;
2491         }
2492
2493         return 0;
2494 }
2495
2496 static void ata_dev_config_cdl(struct ata_device *dev)
2497 {
2498         unsigned int err_mask;
2499         bool cdl_enabled;
2500         u64 val;
2501         int ret;
2502
2503         if (ata_id_major_version(dev->id) < 11)
2504                 goto not_supported;
2505
2506         if (!ata_log_supported(dev, ATA_LOG_IDENTIFY_DEVICE) ||
2507             !ata_identify_page_supported(dev, ATA_LOG_SUPPORTED_CAPABILITIES) ||
2508             !ata_identify_page_supported(dev, ATA_LOG_CURRENT_SETTINGS))
2509                 goto not_supported;
2510
2511         err_mask = ata_read_log_page(dev, ATA_LOG_IDENTIFY_DEVICE,
2512                                      ATA_LOG_SUPPORTED_CAPABILITIES,
2513                                      dev->sector_buf, 1);
2514         if (err_mask)
2515                 goto not_supported;
2516
2517         /* Check Command Duration Limit Supported bits */
2518         val = get_unaligned_le64(&dev->sector_buf[168]);
2519         if (!(val & BIT_ULL(63)) || !(val & BIT_ULL(0)))
2520                 goto not_supported;
2521
2522         /* Warn the user if command duration guideline is not supported */
2523         if (!(val & BIT_ULL(1)))
2524                 ata_dev_warn(dev,
2525                         "Command duration guideline is not supported\n");
2526
2527         /*
2528          * We must have support for the sense data for successful NCQ commands
2529          * log indicated by the successful NCQ command sense data supported bit.
2530          */
2531         val = get_unaligned_le64(&dev->sector_buf[8]);
2532         if (!(val & BIT_ULL(63)) || !(val & BIT_ULL(47))) {
2533                 ata_dev_warn(dev,
2534                         "CDL supported but Successful NCQ Command Sense Data is not supported\n");
2535                 goto not_supported;
2536         }
2537
2538         /* Without NCQ autosense, the successful NCQ commands log is useless. */
2539         if (!ata_id_has_ncq_autosense(dev->id)) {
2540                 ata_dev_warn(dev,
2541                         "CDL supported but NCQ autosense is not supported\n");
2542                 goto not_supported;
2543         }
2544
2545         /*
2546          * If CDL is marked as enabled, make sure the feature is enabled too.
2547          * Conversely, if CDL is disabled, make sure the feature is turned off.
2548          */
2549         err_mask = ata_read_log_page(dev, ATA_LOG_IDENTIFY_DEVICE,
2550                                      ATA_LOG_CURRENT_SETTINGS,
2551                                      dev->sector_buf, 1);
2552         if (err_mask)
2553                 goto not_supported;
2554
2555         val = get_unaligned_le64(&dev->sector_buf[8]);
2556         cdl_enabled = val & BIT_ULL(63) && val & BIT_ULL(21);
2557         if (dev->flags & ATA_DFLAG_CDL_ENABLED) {
2558                 if (!cdl_enabled) {
2559                         /* Enable CDL on the device */
2560                         err_mask = ata_dev_set_feature(dev, SETFEATURES_CDL, 1);
2561                         if (err_mask) {
2562                                 ata_dev_err(dev,
2563                                             "Enable CDL feature failed\n");
2564                                 goto not_supported;
2565                         }
2566                 }
2567         } else {
2568                 if (cdl_enabled) {
2569                         /* Disable CDL on the device */
2570                         err_mask = ata_dev_set_feature(dev, SETFEATURES_CDL, 0);
2571                         if (err_mask) {
2572                                 ata_dev_err(dev,
2573                                             "Disable CDL feature failed\n");
2574                                 goto not_supported;
2575                         }
2576                 }
2577         }
2578
2579         /*
2580          * While CDL itself has to be enabled using sysfs, CDL requires that
2581          * sense data for successful NCQ commands is enabled to work properly.
2582          * Just like ata_dev_config_sense_reporting(), enable it unconditionally
2583          * if supported.
2584          */
2585         if (!(val & BIT_ULL(63)) || !(val & BIT_ULL(18))) {
2586                 err_mask = ata_dev_set_feature(dev,
2587                                         SETFEATURE_SENSE_DATA_SUCC_NCQ, 0x1);
2588                 if (err_mask) {
2589                         ata_dev_warn(dev,
2590                                      "failed to enable Sense Data for successful NCQ commands, Emask 0x%x\n",
2591                                      err_mask);
2592                         goto not_supported;
2593                 }
2594         }
2595
2596         /* CDL is supported: allocate and initialize needed resources. */
2597         ret = ata_dev_init_cdl_resources(dev);
2598         if (ret) {
2599                 ata_dev_warn(dev, "Initialize CDL resources failed\n");
2600                 goto not_supported;
2601         }
2602
2603         dev->flags |= ATA_DFLAG_CDL;
2604
2605         return;
2606
2607 not_supported:
2608         dev->flags &= ~(ATA_DFLAG_CDL | ATA_DFLAG_CDL_ENABLED);
2609         ata_dev_cleanup_cdl_resources(dev);
2610 }
2611
2612 static int ata_dev_config_lba(struct ata_device *dev)
2613 {
2614         const u16 *id = dev->id;
2615         const char *lba_desc;
2616         char ncq_desc[32];
2617         int ret;
2618
2619         dev->flags |= ATA_DFLAG_LBA;
2620
2621         if (ata_id_has_lba48(id)) {
2622                 lba_desc = "LBA48";
2623                 dev->flags |= ATA_DFLAG_LBA48;
2624                 if (dev->n_sectors >= (1UL << 28) &&
2625                     ata_id_has_flush_ext(id))
2626                         dev->flags |= ATA_DFLAG_FLUSH_EXT;
2627         } else {
2628                 lba_desc = "LBA";
2629         }
2630
2631         /* config NCQ */
2632         ret = ata_dev_config_ncq(dev, ncq_desc, sizeof(ncq_desc));
2633
2634         /* print device info to dmesg */
2635         if (ata_dev_print_info(dev))
2636                 ata_dev_info(dev,
2637                              "%llu sectors, multi %u: %s %s\n",
2638                              (unsigned long long)dev->n_sectors,
2639                              dev->multi_count, lba_desc, ncq_desc);
2640
2641         return ret;
2642 }
2643
2644 static void ata_dev_config_chs(struct ata_device *dev)
2645 {
2646         const u16 *id = dev->id;
2647
2648         if (ata_id_current_chs_valid(id)) {
2649                 /* Current CHS translation is valid. */
2650                 dev->cylinders = id[54];
2651                 dev->heads     = id[55];
2652                 dev->sectors   = id[56];
2653         } else {
2654                 /* Default translation */
2655                 dev->cylinders  = id[1];
2656                 dev->heads      = id[3];
2657                 dev->sectors    = id[6];
2658         }
2659
2660         /* print device info to dmesg */
2661         if (ata_dev_print_info(dev))
2662                 ata_dev_info(dev,
2663                              "%llu sectors, multi %u, CHS %u/%u/%u\n",
2664                              (unsigned long long)dev->n_sectors,
2665                              dev->multi_count, dev->cylinders,
2666                              dev->heads, dev->sectors);
2667 }
2668
2669 static void ata_dev_config_fua(struct ata_device *dev)
2670 {
2671         /* Ignore FUA support if its use is disabled globally */
2672         if (!libata_fua)
2673                 goto nofua;
2674
2675         /* Ignore devices without support for WRITE DMA FUA EXT */
2676         if (!(dev->flags & ATA_DFLAG_LBA48) || !ata_id_has_fua(dev->id))
2677                 goto nofua;
2678
2679         /* Ignore known bad devices and devices that lack NCQ support */
2680         if (!ata_ncq_supported(dev) || (dev->quirks & ATA_QUIRK_NO_FUA))
2681                 goto nofua;
2682
2683         dev->flags |= ATA_DFLAG_FUA;
2684
2685         return;
2686
2687 nofua:
2688         dev->flags &= ~ATA_DFLAG_FUA;
2689 }
2690
2691 static void ata_dev_config_devslp(struct ata_device *dev)
2692 {
2693         u8 *sata_setting = dev->sector_buf;
2694         unsigned int err_mask;
2695         int i, j;
2696
2697         /*
2698          * Check device sleep capability. Get DevSlp timing variables
2699          * from SATA Settings page of Identify Device Data Log.
2700          */
2701         if (!ata_id_has_devslp(dev->id) ||
2702             !ata_identify_page_supported(dev, ATA_LOG_SATA_SETTINGS))
2703                 return;
2704
2705         err_mask = ata_read_log_page(dev,
2706                                      ATA_LOG_IDENTIFY_DEVICE,
2707                                      ATA_LOG_SATA_SETTINGS,
2708                                      sata_setting, 1);
2709         if (err_mask)
2710                 return;
2711
2712         dev->flags |= ATA_DFLAG_DEVSLP;
2713         for (i = 0; i < ATA_LOG_DEVSLP_SIZE; i++) {
2714                 j = ATA_LOG_DEVSLP_OFFSET + i;
2715                 dev->devslp_timing[i] = sata_setting[j];
2716         }
2717 }
2718
2719 static void ata_dev_config_cpr(struct ata_device *dev)
2720 {
2721         unsigned int err_mask;
2722         size_t buf_len;
2723         int i, nr_cpr = 0;
2724         struct ata_cpr_log *cpr_log = NULL;
2725         u8 *desc, *buf = NULL;
2726
2727         if (ata_id_major_version(dev->id) < 11)
2728                 goto out;
2729
2730         buf_len = ata_log_supported(dev, ATA_LOG_CONCURRENT_POSITIONING_RANGES);
2731         if (buf_len == 0)
2732                 goto out;
2733
2734         /*
2735          * Read the concurrent positioning ranges log (0x47). We can have at
2736          * most 255 32B range descriptors plus a 64B header. This log varies in
2737          * size, so use the size reported in the GPL directory. Reading beyond
2738          * the supported length will result in an error.
2739          */
2740         buf_len <<= 9;
2741         buf = kzalloc(buf_len, GFP_KERNEL);
2742         if (!buf)
2743                 goto out;
2744
2745         err_mask = ata_read_log_page(dev, ATA_LOG_CONCURRENT_POSITIONING_RANGES,
2746                                      0, buf, buf_len >> 9);
2747         if (err_mask)
2748                 goto out;
2749
2750         nr_cpr = buf[0];
2751         if (!nr_cpr)
2752                 goto out;
2753
2754         cpr_log = kzalloc(struct_size(cpr_log, cpr, nr_cpr), GFP_KERNEL);
2755         if (!cpr_log)
2756                 goto out;
2757
2758         cpr_log->nr_cpr = nr_cpr;
2759         desc = &buf[64];
2760         for (i = 0; i < nr_cpr; i++, desc += 32) {
2761                 cpr_log->cpr[i].num = desc[0];
2762                 cpr_log->cpr[i].num_storage_elements = desc[1];
2763                 cpr_log->cpr[i].start_lba = get_unaligned_le64(&desc[8]);
2764                 cpr_log->cpr[i].num_lbas = get_unaligned_le64(&desc[16]);
2765         }
2766
2767 out:
2768         swap(dev->cpr_log, cpr_log);
2769         kfree(cpr_log);
2770         kfree(buf);
2771 }
2772
2773 static void ata_dev_print_features(struct ata_device *dev)
2774 {
2775         if (!(dev->flags & ATA_DFLAG_FEATURES_MASK))
2776                 return;
2777
2778         ata_dev_info(dev,
2779                      "Features:%s%s%s%s%s%s%s%s\n",
2780                      dev->flags & ATA_DFLAG_FUA ? " FUA" : "",
2781                      dev->flags & ATA_DFLAG_TRUSTED ? " Trust" : "",
2782                      dev->flags & ATA_DFLAG_DA ? " Dev-Attention" : "",
2783                      dev->flags & ATA_DFLAG_DEVSLP ? " Dev-Sleep" : "",
2784                      dev->flags & ATA_DFLAG_NCQ_SEND_RECV ? " NCQ-sndrcv" : "",
2785                      dev->flags & ATA_DFLAG_NCQ_PRIO ? " NCQ-prio" : "",
2786                      dev->flags & ATA_DFLAG_CDL ? " CDL" : "",
2787                      dev->cpr_log ? " CPR" : "");
2788 }
2789
2790 /**
2791  *      ata_dev_configure - Configure the specified ATA/ATAPI device
2792  *      @dev: Target device to configure
2793  *
2794  *      Configure @dev according to @dev->id.  Generic and low-level
2795  *      driver specific fixups are also applied.
2796  *
2797  *      LOCKING:
2798  *      Kernel thread context (may sleep)
2799  *
2800  *      RETURNS:
2801  *      0 on success, -errno otherwise
2802  */
2803 int ata_dev_configure(struct ata_device *dev)
2804 {
2805         struct ata_port *ap = dev->link->ap;
2806         bool print_info = ata_dev_print_info(dev);
2807         const u16 *id = dev->id;
2808         unsigned int xfer_mask;
2809         unsigned int err_mask;
2810         char revbuf[7];         /* XYZ-99\0 */
2811         char fwrevbuf[ATA_ID_FW_REV_LEN+1];
2812         char modelbuf[ATA_ID_PROD_LEN+1];
2813         int rc;
2814
2815         if (!ata_dev_enabled(dev)) {
2816                 ata_dev_dbg(dev, "no device\n");
2817                 return 0;
2818         }
2819
2820         /* Set quirks */
2821         dev->quirks |= ata_dev_quirks(dev);
2822         ata_force_quirks(dev);
2823
2824         if (dev->quirks & ATA_QUIRK_DISABLE) {
2825                 ata_dev_info(dev, "unsupported device, disabling\n");
2826                 ata_dev_disable(dev);
2827                 return 0;
2828         }
2829
2830         if ((!atapi_enabled || (ap->flags & ATA_FLAG_NO_ATAPI)) &&
2831             dev->class == ATA_DEV_ATAPI) {
2832                 ata_dev_warn(dev, "WARNING: ATAPI is %s, device ignored\n",
2833                              atapi_enabled ? "not supported with this driver"
2834                              : "disabled");
2835                 ata_dev_disable(dev);
2836                 return 0;
2837         }
2838
2839         rc = ata_do_link_spd_quirk(dev);
2840         if (rc)
2841                 return rc;
2842
2843         /* some WD SATA-1 drives have issues with LPM, turn on NOLPM for them */
2844         if ((dev->quirks & ATA_QUIRK_WD_BROKEN_LPM) &&
2845             (id[ATA_ID_SATA_CAPABILITY] & 0xe) == 0x2)
2846                 dev->quirks |= ATA_QUIRK_NOLPM;
2847
2848         if (ap->flags & ATA_FLAG_NO_LPM)
2849                 dev->quirks |= ATA_QUIRK_NOLPM;
2850
2851         if (dev->quirks & ATA_QUIRK_NOLPM) {
2852                 ata_dev_warn(dev, "LPM support broken, forcing max_power\n");
2853                 dev->link->ap->target_lpm_policy = ATA_LPM_MAX_POWER;
2854         }
2855
2856         /* let ACPI work its magic */
2857         rc = ata_acpi_on_devcfg(dev);
2858         if (rc)
2859                 return rc;
2860
2861         /* massage HPA, do it early as it might change IDENTIFY data */
2862         rc = ata_hpa_resize(dev);
2863         if (rc)
2864                 return rc;
2865
2866         /* print device capabilities */
2867         ata_dev_dbg(dev,
2868                     "%s: cfg 49:%04x 82:%04x 83:%04x 84:%04x "
2869                     "85:%04x 86:%04x 87:%04x 88:%04x\n",
2870                     __func__,
2871                     id[49], id[82], id[83], id[84],
2872                     id[85], id[86], id[87], id[88]);
2873
2874         /* initialize to-be-configured parameters */
2875         dev->flags &= ~ATA_DFLAG_CFG_MASK;
2876         dev->max_sectors = 0;
2877         dev->cdb_len = 0;
2878         dev->n_sectors = 0;
2879         dev->cylinders = 0;
2880         dev->heads = 0;
2881         dev->sectors = 0;
2882         dev->multi_count = 0;
2883
2884         /*
2885          * common ATA, ATAPI feature tests
2886          */
2887
2888         /* find max transfer mode; for printk only */
2889         xfer_mask = ata_id_xfermask(id);
2890
2891         ata_dump_id(dev, id);
2892
2893         /* SCSI only uses 4-char revisions, dump full 8 chars from ATA */
2894         ata_id_c_string(dev->id, fwrevbuf, ATA_ID_FW_REV,
2895                         sizeof(fwrevbuf));
2896
2897         ata_id_c_string(dev->id, modelbuf, ATA_ID_PROD,
2898                         sizeof(modelbuf));
2899
2900         /* ATA-specific feature tests */
2901         if (dev->class == ATA_DEV_ATA || dev->class == ATA_DEV_ZAC) {
2902                 if (ata_id_is_cfa(id)) {
2903                         /* CPRM may make this media unusable */
2904                         if (id[ATA_ID_CFA_KEY_MGMT] & 1)
2905                                 ata_dev_warn(dev,
2906         "supports DRM functions and may not be fully accessible\n");
2907                         snprintf(revbuf, 7, "CFA");
2908                 } else {
2909                         snprintf(revbuf, 7, "ATA-%d", ata_id_major_version(id));
2910                         /* Warn the user if the device has TPM extensions */
2911                         if (ata_id_has_tpm(id))
2912                                 ata_dev_warn(dev,
2913         "supports DRM functions and may not be fully accessible\n");
2914                 }
2915
2916                 dev->n_sectors = ata_id_n_sectors(id);
2917
2918                 /* get current R/W Multiple count setting */
2919                 if ((dev->id[47] >> 8) == 0x80 && (dev->id[59] & 0x100)) {
2920                         unsigned int max = dev->id[47] & 0xff;
2921                         unsigned int cnt = dev->id[59] & 0xff;
2922                         /* only recognize/allow powers of two here */
2923                         if (is_power_of_2(max) && is_power_of_2(cnt))
2924                                 if (cnt <= max)
2925                                         dev->multi_count = cnt;
2926                 }
2927
2928                 /* print device info to dmesg */
2929                 if (print_info)
2930                         ata_dev_info(dev, "%s: %s, %s, max %s\n",
2931                                      revbuf, modelbuf, fwrevbuf,
2932                                      ata_mode_string(xfer_mask));
2933
2934                 if (ata_id_has_lba(id)) {
2935                         rc = ata_dev_config_lba(dev);
2936                         if (rc)
2937                                 return rc;
2938                 } else {
2939                         ata_dev_config_chs(dev);
2940                 }
2941
2942                 ata_dev_config_fua(dev);
2943                 ata_dev_config_devslp(dev);
2944                 ata_dev_config_sense_reporting(dev);
2945                 ata_dev_config_zac(dev);
2946                 ata_dev_config_trusted(dev);
2947                 ata_dev_config_cpr(dev);
2948                 ata_dev_config_cdl(dev);
2949                 dev->cdb_len = 32;
2950
2951                 if (print_info)
2952                         ata_dev_print_features(dev);
2953         }
2954
2955         /* ATAPI-specific feature tests */
2956         else if (dev->class == ATA_DEV_ATAPI) {
2957                 const char *cdb_intr_string = "";
2958                 const char *atapi_an_string = "";
2959                 const char *dma_dir_string = "";
2960                 u32 sntf;
2961
2962                 rc = atapi_cdb_len(id);
2963                 if ((rc < 12) || (rc > ATAPI_CDB_LEN)) {
2964                         ata_dev_warn(dev, "unsupported CDB len %d\n", rc);
2965                         rc = -EINVAL;
2966                         goto err_out_nosup;
2967                 }
2968                 dev->cdb_len = (unsigned int) rc;
2969
2970                 /* Enable ATAPI AN if both the host and device have
2971                  * the support.  If PMP is attached, SNTF is required
2972                  * to enable ATAPI AN to discern between PHY status
2973                  * changed notifications and ATAPI ANs.
2974                  */
2975                 if (atapi_an &&
2976                     (ap->flags & ATA_FLAG_AN) && ata_id_has_atapi_AN(id) &&
2977                     (!sata_pmp_attached(ap) ||
2978                      sata_scr_read(&ap->link, SCR_NOTIFICATION, &sntf) == 0)) {
2979                         /* issue SET feature command to turn this on */
2980                         err_mask = ata_dev_set_feature(dev,
2981                                         SETFEATURES_SATA_ENABLE, SATA_AN);
2982                         if (err_mask)
2983                                 ata_dev_err(dev,
2984                                             "failed to enable ATAPI AN (err_mask=0x%x)\n",
2985                                             err_mask);
2986                         else {
2987                                 dev->flags |= ATA_DFLAG_AN;
2988                                 atapi_an_string = ", ATAPI AN";
2989                         }
2990                 }
2991
2992                 if (ata_id_cdb_intr(dev->id)) {
2993                         dev->flags |= ATA_DFLAG_CDB_INTR;
2994                         cdb_intr_string = ", CDB intr";
2995                 }
2996
2997                 if (atapi_dmadir || (dev->quirks & ATA_QUIRK_ATAPI_DMADIR) ||
2998                     atapi_id_dmadir(dev->id)) {
2999                         dev->flags |= ATA_DFLAG_DMADIR;
3000                         dma_dir_string = ", DMADIR";
3001                 }
3002
3003                 if (ata_id_has_da(dev->id)) {
3004                         dev->flags |= ATA_DFLAG_DA;
3005                         zpodd_init(dev);
3006                 }
3007
3008                 /* print device info to dmesg */
3009                 if (print_info)
3010                         ata_dev_info(dev,
3011                                      "ATAPI: %s, %s, max %s%s%s%s\n",
3012                                      modelbuf, fwrevbuf,
3013                                      ata_mode_string(xfer_mask),
3014                                      cdb_intr_string, atapi_an_string,
3015                                      dma_dir_string);
3016         }
3017
3018         /* determine max_sectors */
3019         dev->max_sectors = ATA_MAX_SECTORS;
3020         if (dev->flags & ATA_DFLAG_LBA48)
3021                 dev->max_sectors = ATA_MAX_SECTORS_LBA48;
3022
3023         /* Limit PATA drive on SATA cable bridge transfers to udma5,
3024            200 sectors */
3025         if (ata_dev_knobble(dev)) {
3026                 if (print_info)
3027                         ata_dev_info(dev, "applying bridge limits\n");
3028                 dev->udma_mask &= ATA_UDMA5;
3029                 dev->max_sectors = ATA_MAX_SECTORS;
3030         }
3031
3032         if ((dev->class == ATA_DEV_ATAPI) &&
3033             (atapi_command_packet_set(id) == TYPE_TAPE)) {
3034                 dev->max_sectors = ATA_MAX_SECTORS_TAPE;
3035                 dev->quirks |= ATA_QUIRK_STUCK_ERR;
3036         }
3037
3038         if (dev->quirks & ATA_QUIRK_MAX_SEC_128)
3039                 dev->max_sectors = min_t(unsigned int, ATA_MAX_SECTORS_128,
3040                                          dev->max_sectors);
3041
3042         if (dev->quirks & ATA_QUIRK_MAX_SEC_1024)
3043                 dev->max_sectors = min_t(unsigned int, ATA_MAX_SECTORS_1024,
3044                                          dev->max_sectors);
3045
3046         if (dev->quirks & ATA_QUIRK_MAX_SEC_LBA48)
3047                 dev->max_sectors = ATA_MAX_SECTORS_LBA48;
3048
3049         if (ap->ops->dev_config)
3050                 ap->ops->dev_config(dev);
3051
3052         if (dev->quirks & ATA_QUIRK_DIAGNOSTIC) {
3053                 /* Let the user know. We don't want to disallow opens for
3054                    rescue purposes, or in case the vendor is just a blithering
3055                    idiot. Do this after the dev_config call as some controllers
3056                    with buggy firmware may want to avoid reporting false device
3057                    bugs */
3058
3059                 if (print_info) {
3060                         ata_dev_warn(dev,
3061 "Drive reports diagnostics failure. This may indicate a drive\n");
3062                         ata_dev_warn(dev,
3063 "fault or invalid emulation. Contact drive vendor for information.\n");
3064                 }
3065         }
3066
3067         if ((dev->quirks & ATA_QUIRK_FIRMWARE_WARN) && print_info) {
3068                 ata_dev_warn(dev, "WARNING: device requires firmware update to be fully functional\n");
3069                 ata_dev_warn(dev, "         contact the vendor or visit http://ata.wiki.kernel.org\n");
3070         }
3071
3072         return 0;
3073
3074 err_out_nosup:
3075         return rc;
3076 }
3077
3078 /**
3079  *      ata_cable_40wire        -       return 40 wire cable type
3080  *      @ap: port
3081  *
3082  *      Helper method for drivers which want to hardwire 40 wire cable
3083  *      detection.
3084  */
3085
3086 int ata_cable_40wire(struct ata_port *ap)
3087 {
3088         return ATA_CBL_PATA40;
3089 }
3090 EXPORT_SYMBOL_GPL(ata_cable_40wire);
3091
3092 /**
3093  *      ata_cable_80wire        -       return 80 wire cable type
3094  *      @ap: port
3095  *
3096  *      Helper method for drivers which want to hardwire 80 wire cable
3097  *      detection.
3098  */
3099
3100 int ata_cable_80wire(struct ata_port *ap)
3101 {
3102         return ATA_CBL_PATA80;
3103 }
3104 EXPORT_SYMBOL_GPL(ata_cable_80wire);
3105
3106 /**
3107  *      ata_cable_unknown       -       return unknown PATA cable.
3108  *      @ap: port
3109  *
3110  *      Helper method for drivers which have no PATA cable detection.
3111  */
3112
3113 int ata_cable_unknown(struct ata_port *ap)
3114 {
3115         return ATA_CBL_PATA_UNK;
3116 }
3117 EXPORT_SYMBOL_GPL(ata_cable_unknown);
3118
3119 /**
3120  *      ata_cable_ignore        -       return ignored PATA cable.
3121  *      @ap: port
3122  *
3123  *      Helper method for drivers which don't use cable type to limit
3124  *      transfer mode.
3125  */
3126 int ata_cable_ignore(struct ata_port *ap)
3127 {
3128         return ATA_CBL_PATA_IGN;
3129 }
3130 EXPORT_SYMBOL_GPL(ata_cable_ignore);
3131
3132 /**
3133  *      ata_cable_sata  -       return SATA cable type
3134  *      @ap: port
3135  *
3136  *      Helper method for drivers which have SATA cables
3137  */
3138
3139 int ata_cable_sata(struct ata_port *ap)
3140 {
3141         return ATA_CBL_SATA;
3142 }
3143 EXPORT_SYMBOL_GPL(ata_cable_sata);
3144
3145 /**
3146  *      sata_print_link_status - Print SATA link status
3147  *      @link: SATA link to printk link status about
3148  *
3149  *      This function prints link speed and status of a SATA link.
3150  *
3151  *      LOCKING:
3152  *      None.
3153  */
3154 static void sata_print_link_status(struct ata_link *link)
3155 {
3156         u32 sstatus, scontrol, tmp;
3157
3158         if (sata_scr_read(link, SCR_STATUS, &sstatus))
3159                 return;
3160         if (sata_scr_read(link, SCR_CONTROL, &scontrol))
3161                 return;
3162
3163         if (ata_phys_link_online(link)) {
3164                 tmp = (sstatus >> 4) & 0xf;
3165                 ata_link_info(link, "SATA link up %s (SStatus %X SControl %X)\n",
3166                               sata_spd_string(tmp), sstatus, scontrol);
3167         } else {
3168                 ata_link_info(link, "SATA link down (SStatus %X SControl %X)\n",
3169                               sstatus, scontrol);
3170         }
3171 }
3172
3173 /**
3174  *      ata_dev_pair            -       return other device on cable
3175  *      @adev: device
3176  *
3177  *      Obtain the other device on the same cable, or if none is
3178  *      present NULL is returned
3179  */
3180
3181 struct ata_device *ata_dev_pair(struct ata_device *adev)
3182 {
3183         struct ata_link *link = adev->link;
3184         struct ata_device *pair = &link->device[1 - adev->devno];
3185         if (!ata_dev_enabled(pair))
3186                 return NULL;
3187         return pair;
3188 }
3189 EXPORT_SYMBOL_GPL(ata_dev_pair);
3190
3191 #ifdef CONFIG_ATA_ACPI
3192 /**
3193  *      ata_timing_cycle2mode - find xfer mode for the specified cycle duration
3194  *      @xfer_shift: ATA_SHIFT_* value for transfer type to examine.
3195  *      @cycle: cycle duration in ns
3196  *
3197  *      Return matching xfer mode for @cycle.  The returned mode is of
3198  *      the transfer type specified by @xfer_shift.  If @cycle is too
3199  *      slow for @xfer_shift, 0xff is returned.  If @cycle is faster
3200  *      than the fastest known mode, the fasted mode is returned.
3201  *
3202  *      LOCKING:
3203  *      None.
3204  *
3205  *      RETURNS:
3206  *      Matching xfer_mode, 0xff if no match found.
3207  */
3208 u8 ata_timing_cycle2mode(unsigned int xfer_shift, int cycle)
3209 {
3210         u8 base_mode = 0xff, last_mode = 0xff;
3211         const struct ata_xfer_ent *ent;
3212         const struct ata_timing *t;
3213
3214         for (ent = ata_xfer_tbl; ent->shift >= 0; ent++)
3215                 if (ent->shift == xfer_shift)
3216                         base_mode = ent->base;
3217
3218         for (t = ata_timing_find_mode(base_mode);
3219              t && ata_xfer_mode2shift(t->mode) == xfer_shift; t++) {
3220                 unsigned short this_cycle;
3221
3222                 switch (xfer_shift) {
3223                 case ATA_SHIFT_PIO:
3224                 case ATA_SHIFT_MWDMA:
3225                         this_cycle = t->cycle;
3226                         break;
3227                 case ATA_SHIFT_UDMA:
3228                         this_cycle = t->udma;
3229                         break;
3230                 default:
3231                         return 0xff;
3232                 }
3233
3234                 if (cycle > this_cycle)
3235                         break;
3236
3237                 last_mode = t->mode;
3238         }
3239
3240         return last_mode;
3241 }
3242 #endif
3243
3244 /**
3245  *      ata_down_xfermask_limit - adjust dev xfer masks downward
3246  *      @dev: Device to adjust xfer masks
3247  *      @sel: ATA_DNXFER_* selector
3248  *
3249  *      Adjust xfer masks of @dev downward.  Note that this function
3250  *      does not apply the change.  Invoking ata_set_mode() afterwards
3251  *      will apply the limit.
3252  *
3253  *      LOCKING:
3254  *      Inherited from caller.
3255  *
3256  *      RETURNS:
3257  *      0 on success, negative errno on failure
3258  */
3259 int ata_down_xfermask_limit(struct ata_device *dev, unsigned int sel)
3260 {
3261         char buf[32];
3262         unsigned int orig_mask, xfer_mask;
3263         unsigned int pio_mask, mwdma_mask, udma_mask;
3264         int quiet, highbit;
3265
3266         quiet = !!(sel & ATA_DNXFER_QUIET);
3267         sel &= ~ATA_DNXFER_QUIET;
3268
3269         xfer_mask = orig_mask = ata_pack_xfermask(dev->pio_mask,
3270                                                   dev->mwdma_mask,
3271                                                   dev->udma_mask);
3272         ata_unpack_xfermask(xfer_mask, &pio_mask, &mwdma_mask, &udma_mask);
3273
3274         switch (sel) {
3275         case ATA_DNXFER_PIO:
3276                 highbit = fls(pio_mask) - 1;
3277                 pio_mask &= ~(1 << highbit);
3278                 break;
3279
3280         case ATA_DNXFER_DMA:
3281                 if (udma_mask) {
3282                         highbit = fls(udma_mask) - 1;
3283                         udma_mask &= ~(1 << highbit);
3284                         if (!udma_mask)
3285                                 return -ENOENT;
3286                 } else if (mwdma_mask) {
3287                         highbit = fls(mwdma_mask) - 1;
3288                         mwdma_mask &= ~(1 << highbit);
3289                         if (!mwdma_mask)
3290                                 return -ENOENT;
3291                 }
3292                 break;
3293
3294         case ATA_DNXFER_40C:
3295                 udma_mask &= ATA_UDMA_MASK_40C;
3296                 break;
3297
3298         case ATA_DNXFER_FORCE_PIO0:
3299                 pio_mask &= 1;
3300                 fallthrough;
3301         case ATA_DNXFER_FORCE_PIO:
3302                 mwdma_mask = 0;
3303                 udma_mask = 0;
3304                 break;
3305
3306         default:
3307                 BUG();
3308         }
3309
3310         xfer_mask &= ata_pack_xfermask(pio_mask, mwdma_mask, udma_mask);
3311
3312         if (!(xfer_mask & ATA_MASK_PIO) || xfer_mask == orig_mask)
3313                 return -ENOENT;
3314
3315         if (!quiet) {
3316                 if (xfer_mask & (ATA_MASK_MWDMA | ATA_MASK_UDMA))
3317                         snprintf(buf, sizeof(buf), "%s:%s",
3318                                  ata_mode_string(xfer_mask),
3319                                  ata_mode_string(xfer_mask & ATA_MASK_PIO));
3320                 else
3321                         snprintf(buf, sizeof(buf), "%s",
3322                                  ata_mode_string(xfer_mask));
3323
3324                 ata_dev_warn(dev, "limiting speed to %s\n", buf);
3325         }
3326
3327         ata_unpack_xfermask(xfer_mask, &dev->pio_mask, &dev->mwdma_mask,
3328                             &dev->udma_mask);
3329
3330         return 0;
3331 }
3332
3333 static int ata_dev_set_mode(struct ata_device *dev)
3334 {
3335         struct ata_port *ap = dev->link->ap;
3336         struct ata_eh_context *ehc = &dev->link->eh_context;
3337         const bool nosetxfer = dev->quirks & ATA_QUIRK_NOSETXFER;
3338         const char *dev_err_whine = "";
3339         int ign_dev_err = 0;
3340         unsigned int err_mask = 0;
3341         int rc;
3342
3343         dev->flags &= ~ATA_DFLAG_PIO;
3344         if (dev->xfer_shift == ATA_SHIFT_PIO)
3345                 dev->flags |= ATA_DFLAG_PIO;
3346
3347         if (nosetxfer && ap->flags & ATA_FLAG_SATA && ata_id_is_sata(dev->id))
3348                 dev_err_whine = " (SET_XFERMODE skipped)";
3349         else {
3350                 if (nosetxfer)
3351                         ata_dev_warn(dev,
3352                                      "NOSETXFER but PATA detected - can't "
3353                                      "skip SETXFER, might malfunction\n");
3354                 err_mask = ata_dev_set_xfermode(dev);
3355         }
3356
3357         if (err_mask & ~AC_ERR_DEV)
3358                 goto fail;
3359
3360         /* revalidate */
3361         ehc->i.flags |= ATA_EHI_POST_SETMODE;
3362         rc = ata_dev_revalidate(dev, ATA_DEV_UNKNOWN, 0);
3363         ehc->i.flags &= ~ATA_EHI_POST_SETMODE;
3364         if (rc)
3365                 return rc;
3366
3367         if (dev->xfer_shift == ATA_SHIFT_PIO) {
3368                 /* Old CFA may refuse this command, which is just fine */
3369                 if (ata_id_is_cfa(dev->id))
3370                         ign_dev_err = 1;
3371                 /* Catch several broken garbage emulations plus some pre
3372                    ATA devices */
3373                 if (ata_id_major_version(dev->id) == 0 &&
3374                                         dev->pio_mode <= XFER_PIO_2)
3375                         ign_dev_err = 1;
3376                 /* Some very old devices and some bad newer ones fail
3377                    any kind of SET_XFERMODE request but support PIO0-2
3378                    timings and no IORDY */
3379                 if (!ata_id_has_iordy(dev->id) && dev->pio_mode <= XFER_PIO_2)
3380                         ign_dev_err = 1;
3381         }
3382         /* Early MWDMA devices do DMA but don't allow DMA mode setting.
3383            Don't fail an MWDMA0 set IFF the device indicates it is in MWDMA0 */
3384         if (dev->xfer_shift == ATA_SHIFT_MWDMA &&
3385             dev->dma_mode == XFER_MW_DMA_0 &&
3386             (dev->id[63] >> 8) & 1)
3387                 ign_dev_err = 1;
3388
3389         /* if the device is actually configured correctly, ignore dev err */
3390         if (dev->xfer_mode == ata_xfer_mask2mode(ata_id_xfermask(dev->id)))
3391                 ign_dev_err = 1;
3392
3393         if (err_mask & AC_ERR_DEV) {
3394                 if (!ign_dev_err)
3395                         goto fail;
3396                 else
3397                         dev_err_whine = " (device error ignored)";
3398         }
3399
3400         ata_dev_dbg(dev, "xfer_shift=%u, xfer_mode=0x%x\n",
3401                     dev->xfer_shift, (int)dev->xfer_mode);
3402
3403         if (!(ehc->i.flags & ATA_EHI_QUIET) ||
3404             ehc->i.flags & ATA_EHI_DID_HARDRESET)
3405                 ata_dev_info(dev, "configured for %s%s\n",
3406                              ata_mode_string(ata_xfer_mode2mask(dev->xfer_mode)),
3407                              dev_err_whine);
3408
3409         return 0;
3410
3411  fail:
3412         ata_dev_err(dev, "failed to set xfermode (err_mask=0x%x)\n", err_mask);
3413         return -EIO;
3414 }
3415
3416 /**
3417  *      ata_do_set_mode - Program timings and issue SET FEATURES - XFER
3418  *      @link: link on which timings will be programmed
3419  *      @r_failed_dev: out parameter for failed device
3420  *
3421  *      Standard implementation of the function used to tune and set
3422  *      ATA device disk transfer mode (PIO3, UDMA6, etc.).  If
3423  *      ata_dev_set_mode() fails, pointer to the failing device is
3424  *      returned in @r_failed_dev.
3425  *
3426  *      LOCKING:
3427  *      PCI/etc. bus probe sem.
3428  *
3429  *      RETURNS:
3430  *      0 on success, negative errno otherwise
3431  */
3432
3433 int ata_do_set_mode(struct ata_link *link, struct ata_device **r_failed_dev)
3434 {
3435         struct ata_port *ap = link->ap;
3436         struct ata_device *dev;
3437         int rc = 0, used_dma = 0, found = 0;
3438
3439         /* step 1: calculate xfer_mask */
3440         ata_for_each_dev(dev, link, ENABLED) {
3441                 unsigned int pio_mask, dma_mask;
3442                 unsigned int mode_mask;
3443
3444                 mode_mask = ATA_DMA_MASK_ATA;
3445                 if (dev->class == ATA_DEV_ATAPI)
3446                         mode_mask = ATA_DMA_MASK_ATAPI;
3447                 else if (ata_id_is_cfa(dev->id))
3448                         mode_mask = ATA_DMA_MASK_CFA;
3449
3450                 ata_dev_xfermask(dev);
3451                 ata_force_xfermask(dev);
3452
3453                 pio_mask = ata_pack_xfermask(dev->pio_mask, 0, 0);
3454
3455                 if (libata_dma_mask & mode_mask)
3456                         dma_mask = ata_pack_xfermask(0, dev->mwdma_mask,
3457                                                      dev->udma_mask);
3458                 else
3459                         dma_mask = 0;
3460
3461                 dev->pio_mode = ata_xfer_mask2mode(pio_mask);
3462                 dev->dma_mode = ata_xfer_mask2mode(dma_mask);
3463
3464                 found = 1;
3465                 if (ata_dma_enabled(dev))
3466                         used_dma = 1;
3467         }
3468         if (!found)
3469                 goto out;
3470
3471         /* step 2: always set host PIO timings */
3472         ata_for_each_dev(dev, link, ENABLED) {
3473                 if (dev->pio_mode == 0xff) {
3474                         ata_dev_warn(dev, "no PIO support\n");
3475                         rc = -EINVAL;
3476                         goto out;
3477                 }
3478
3479                 dev->xfer_mode = dev->pio_mode;
3480                 dev->xfer_shift = ATA_SHIFT_PIO;
3481                 if (ap->ops->set_piomode)
3482                         ap->ops->set_piomode(ap, dev);
3483         }
3484
3485         /* step 3: set host DMA timings */
3486         ata_for_each_dev(dev, link, ENABLED) {
3487                 if (!ata_dma_enabled(dev))
3488                         continue;
3489
3490                 dev->xfer_mode = dev->dma_mode;
3491                 dev->xfer_shift = ata_xfer_mode2shift(dev->dma_mode);
3492                 if (ap->ops->set_dmamode)
3493                         ap->ops->set_dmamode(ap, dev);
3494         }
3495
3496         /* step 4: update devices' xfer mode */
3497         ata_for_each_dev(dev, link, ENABLED) {
3498                 rc = ata_dev_set_mode(dev);
3499                 if (rc)
3500                         goto out;
3501         }
3502
3503         /* Record simplex status. If we selected DMA then the other
3504          * host channels are not permitted to do so.
3505          */
3506         if (used_dma && (ap->host->flags & ATA_HOST_SIMPLEX))
3507                 ap->host->simplex_claimed = ap;
3508
3509  out:
3510         if (rc)
3511                 *r_failed_dev = dev;
3512         return rc;
3513 }
3514 EXPORT_SYMBOL_GPL(ata_do_set_mode);
3515
3516 /**
3517  *      ata_wait_ready - wait for link to become ready
3518  *      @link: link to be waited on
3519  *      @deadline: deadline jiffies for the operation
3520  *      @check_ready: callback to check link readiness
3521  *
3522  *      Wait for @link to become ready.  @check_ready should return
3523  *      positive number if @link is ready, 0 if it isn't, -ENODEV if
3524  *      link doesn't seem to be occupied, other errno for other error
3525  *      conditions.
3526  *
3527  *      Transient -ENODEV conditions are allowed for
3528  *      ATA_TMOUT_FF_WAIT.
3529  *
3530  *      LOCKING:
3531  *      EH context.
3532  *
3533  *      RETURNS:
3534  *      0 if @link is ready before @deadline; otherwise, -errno.
3535  */
3536 int ata_wait_ready(struct ata_link *link, unsigned long deadline,
3537                    int (*check_ready)(struct ata_link *link))
3538 {
3539         unsigned long start = jiffies;
3540         unsigned long nodev_deadline;
3541         int warned = 0;
3542
3543         /* choose which 0xff timeout to use, read comment in libata.h */
3544         if (link->ap->host->flags & ATA_HOST_PARALLEL_SCAN)
3545                 nodev_deadline = ata_deadline(start, ATA_TMOUT_FF_WAIT_LONG);
3546         else
3547                 nodev_deadline = ata_deadline(start, ATA_TMOUT_FF_WAIT);
3548
3549         /* Slave readiness can't be tested separately from master.  On
3550          * M/S emulation configuration, this function should be called
3551          * only on the master and it will handle both master and slave.
3552          */
3553         WARN_ON(link == link->ap->slave_link);
3554
3555         if (time_after(nodev_deadline, deadline))
3556                 nodev_deadline = deadline;
3557
3558         while (1) {
3559                 unsigned long now = jiffies;
3560                 int ready, tmp;
3561
3562                 ready = tmp = check_ready(link);
3563                 if (ready > 0)
3564                         return 0;
3565
3566                 /*
3567                  * -ENODEV could be transient.  Ignore -ENODEV if link
3568                  * is online.  Also, some SATA devices take a long
3569                  * time to clear 0xff after reset.  Wait for
3570                  * ATA_TMOUT_FF_WAIT[_LONG] on -ENODEV if link isn't
3571                  * offline.
3572                  *
3573                  * Note that some PATA controllers (pata_ali) explode
3574                  * if status register is read more than once when
3575                  * there's no device attached.
3576                  */
3577                 if (ready == -ENODEV) {
3578                         if (ata_link_online(link))
3579                                 ready = 0;
3580                         else if ((link->ap->flags & ATA_FLAG_SATA) &&
3581                                  !ata_link_offline(link) &&
3582                                  time_before(now, nodev_deadline))
3583                                 ready = 0;
3584                 }
3585
3586                 if (ready)
3587                         return ready;
3588                 if (time_after(now, deadline))
3589                         return -EBUSY;
3590
3591                 if (!warned && time_after(now, start + 5 * HZ) &&
3592                     (deadline - now > 3 * HZ)) {
3593                         ata_link_warn(link,
3594                                 "link is slow to respond, please be patient "
3595                                 "(ready=%d)\n", tmp);
3596                         warned = 1;
3597                 }
3598
3599                 ata_msleep(link->ap, 50);
3600         }
3601 }
3602
3603 /**
3604  *      ata_wait_after_reset - wait for link to become ready after reset
3605  *      @link: link to be waited on
3606  *      @deadline: deadline jiffies for the operation
3607  *      @check_ready: callback to check link readiness
3608  *
3609  *      Wait for @link to become ready after reset.
3610  *
3611  *      LOCKING:
3612  *      EH context.
3613  *
3614  *      RETURNS:
3615  *      0 if @link is ready before @deadline; otherwise, -errno.
3616  */
3617 int ata_wait_after_reset(struct ata_link *link, unsigned long deadline,
3618                                 int (*check_ready)(struct ata_link *link))
3619 {
3620         ata_msleep(link->ap, ATA_WAIT_AFTER_RESET);
3621
3622         return ata_wait_ready(link, deadline, check_ready);
3623 }
3624 EXPORT_SYMBOL_GPL(ata_wait_after_reset);
3625
3626 /**
3627  *      ata_std_prereset - prepare for reset
3628  *      @link: ATA link to be reset
3629  *      @deadline: deadline jiffies for the operation
3630  *
3631  *      @link is about to be reset.  Initialize it.  Failure from
3632  *      prereset makes libata abort whole reset sequence and give up
3633  *      that port, so prereset should be best-effort.  It does its
3634  *      best to prepare for reset sequence but if things go wrong, it
3635  *      should just whine, not fail.
3636  *
3637  *      LOCKING:
3638  *      Kernel thread context (may sleep)
3639  *
3640  *      RETURNS:
3641  *      Always 0.
3642  */
3643 int ata_std_prereset(struct ata_link *link, unsigned long deadline)
3644 {
3645         struct ata_port *ap = link->ap;
3646         struct ata_eh_context *ehc = &link->eh_context;
3647         const unsigned int *timing = sata_ehc_deb_timing(ehc);
3648         int rc;
3649
3650         /* if we're about to do hardreset, nothing more to do */
3651         if (ehc->i.action & ATA_EH_HARDRESET)
3652                 return 0;
3653
3654         /* if SATA, resume link */
3655         if (ap->flags & ATA_FLAG_SATA) {
3656                 rc = sata_link_resume(link, timing, deadline);
3657                 /* whine about phy resume failure but proceed */
3658                 if (rc && rc != -EOPNOTSUPP)
3659                         ata_link_warn(link,
3660                                       "failed to resume link for reset (errno=%d)\n",
3661                                       rc);
3662         }
3663
3664         /* no point in trying softreset on offline link */
3665         if (ata_phys_link_offline(link))
3666                 ehc->i.action &= ~ATA_EH_SOFTRESET;
3667
3668         return 0;
3669 }
3670 EXPORT_SYMBOL_GPL(ata_std_prereset);
3671
3672 /**
3673  *      ata_std_postreset - standard postreset callback
3674  *      @link: the target ata_link
3675  *      @classes: classes of attached devices
3676  *
3677  *      This function is invoked after a successful reset.  Note that
3678  *      the device might have been reset more than once using
3679  *      different reset methods before postreset is invoked.
3680  *
3681  *      LOCKING:
3682  *      Kernel thread context (may sleep)
3683  */
3684 void ata_std_postreset(struct ata_link *link, unsigned int *classes)
3685 {
3686         u32 serror;
3687
3688         /* reset complete, clear SError */
3689         if (!sata_scr_read(link, SCR_ERROR, &serror))
3690                 sata_scr_write(link, SCR_ERROR, serror);
3691
3692         /* print link status */
3693         sata_print_link_status(link);
3694 }
3695 EXPORT_SYMBOL_GPL(ata_std_postreset);
3696
3697 /**
3698  *      ata_dev_same_device - Determine whether new ID matches configured device
3699  *      @dev: device to compare against
3700  *      @new_class: class of the new device
3701  *      @new_id: IDENTIFY page of the new device
3702  *
3703  *      Compare @new_class and @new_id against @dev and determine
3704  *      whether @dev is the device indicated by @new_class and
3705  *      @new_id.
3706  *
3707  *      LOCKING:
3708  *      None.
3709  *
3710  *      RETURNS:
3711  *      1 if @dev matches @new_class and @new_id, 0 otherwise.
3712  */
3713 static int ata_dev_same_device(struct ata_device *dev, unsigned int new_class,
3714                                const u16 *new_id)
3715 {
3716         const u16 *old_id = dev->id;
3717         unsigned char model[2][ATA_ID_PROD_LEN + 1];
3718         unsigned char serial[2][ATA_ID_SERNO_LEN + 1];
3719
3720         if (dev->class != new_class) {
3721                 ata_dev_info(dev, "class mismatch %d != %d\n",
3722                              dev->class, new_class);
3723                 return 0;
3724         }
3725
3726         ata_id_c_string(old_id, model[0], ATA_ID_PROD, sizeof(model[0]));
3727         ata_id_c_string(new_id, model[1], ATA_ID_PROD, sizeof(model[1]));
3728         ata_id_c_string(old_id, serial[0], ATA_ID_SERNO, sizeof(serial[0]));
3729         ata_id_c_string(new_id, serial[1], ATA_ID_SERNO, sizeof(serial[1]));
3730
3731         if (strcmp(model[0], model[1])) {
3732                 ata_dev_info(dev, "model number mismatch '%s' != '%s'\n",
3733                              model[0], model[1]);
3734                 return 0;
3735         }
3736
3737         if (strcmp(serial[0], serial[1])) {
3738                 ata_dev_info(dev, "serial number mismatch '%s' != '%s'\n",
3739                              serial[0], serial[1]);
3740                 return 0;
3741         }
3742
3743         return 1;
3744 }
3745
3746 /**
3747  *      ata_dev_reread_id - Re-read IDENTIFY data
3748  *      @dev: target ATA device
3749  *      @readid_flags: read ID flags
3750  *
3751  *      Re-read IDENTIFY page and make sure @dev is still attached to
3752  *      the port.
3753  *
3754  *      LOCKING:
3755  *      Kernel thread context (may sleep)
3756  *
3757  *      RETURNS:
3758  *      0 on success, negative errno otherwise
3759  */
3760 int ata_dev_reread_id(struct ata_device *dev, unsigned int readid_flags)
3761 {
3762         unsigned int class = dev->class;
3763         u16 *id = (void *)dev->sector_buf;
3764         int rc;
3765
3766         /* read ID data */
3767         rc = ata_dev_read_id(dev, &class, readid_flags, id);
3768         if (rc)
3769                 return rc;
3770
3771         /* is the device still there? */
3772         if (!ata_dev_same_device(dev, class, id))
3773                 return -ENODEV;
3774
3775         memcpy(dev->id, id, sizeof(id[0]) * ATA_ID_WORDS);
3776         return 0;
3777 }
3778
3779 /**
3780  *      ata_dev_revalidate - Revalidate ATA device
3781  *      @dev: device to revalidate
3782  *      @new_class: new class code
3783  *      @readid_flags: read ID flags
3784  *
3785  *      Re-read IDENTIFY page, make sure @dev is still attached to the
3786  *      port and reconfigure it according to the new IDENTIFY page.
3787  *
3788  *      LOCKING:
3789  *      Kernel thread context (may sleep)
3790  *
3791  *      RETURNS:
3792  *      0 on success, negative errno otherwise
3793  */
3794 int ata_dev_revalidate(struct ata_device *dev, unsigned int new_class,
3795                        unsigned int readid_flags)
3796 {
3797         u64 n_sectors = dev->n_sectors;
3798         u64 n_native_sectors = dev->n_native_sectors;
3799         int rc;
3800
3801         if (!ata_dev_enabled(dev))
3802                 return -ENODEV;
3803
3804         /* fail early if !ATA && !ATAPI to avoid issuing [P]IDENTIFY to PMP */
3805         if (ata_class_enabled(new_class) && new_class == ATA_DEV_PMP) {
3806                 ata_dev_info(dev, "class mismatch %u != %u\n",
3807                              dev->class, new_class);
3808                 rc = -ENODEV;
3809                 goto fail;
3810         }
3811
3812         /* re-read ID */
3813         rc = ata_dev_reread_id(dev, readid_flags);
3814         if (rc)
3815                 goto fail;
3816
3817         /* configure device according to the new ID */
3818         rc = ata_dev_configure(dev);
3819         if (rc)
3820                 goto fail;
3821
3822         /* verify n_sectors hasn't changed */
3823         if (dev->class != ATA_DEV_ATA || !n_sectors ||
3824             dev->n_sectors == n_sectors)
3825                 return 0;
3826
3827         /* n_sectors has changed */
3828         ata_dev_warn(dev, "n_sectors mismatch %llu != %llu\n",
3829                      (unsigned long long)n_sectors,
3830                      (unsigned long long)dev->n_sectors);
3831
3832         /*
3833          * Something could have caused HPA to be unlocked
3834          * involuntarily.  If n_native_sectors hasn't changed and the
3835          * new size matches it, keep the device.
3836          */
3837         if (dev->n_native_sectors == n_native_sectors &&
3838             dev->n_sectors > n_sectors && dev->n_sectors == n_native_sectors) {
3839                 ata_dev_warn(dev,
3840                              "new n_sectors matches native, probably "
3841                              "late HPA unlock, n_sectors updated\n");
3842                 /* use the larger n_sectors */
3843                 return 0;
3844         }
3845
3846         /*
3847          * Some BIOSes boot w/o HPA but resume w/ HPA locked.  Try
3848          * unlocking HPA in those cases.
3849          *
3850          * https://bugzilla.kernel.org/show_bug.cgi?id=15396
3851          */
3852         if (dev->n_native_sectors == n_native_sectors &&
3853             dev->n_sectors < n_sectors && n_sectors == n_native_sectors &&
3854             !(dev->quirks & ATA_QUIRK_BROKEN_HPA)) {
3855                 ata_dev_warn(dev,
3856                              "old n_sectors matches native, probably "
3857                              "late HPA lock, will try to unlock HPA\n");
3858                 /* try unlocking HPA */
3859                 dev->flags |= ATA_DFLAG_UNLOCK_HPA;
3860                 rc = -EIO;
3861         } else
3862                 rc = -ENODEV;
3863
3864         /* restore original n_[native_]sectors and fail */
3865         dev->n_native_sectors = n_native_sectors;
3866         dev->n_sectors = n_sectors;
3867  fail:
3868         ata_dev_err(dev, "revalidation failed (errno=%d)\n", rc);
3869         return rc;
3870 }
3871
3872 static const char * const ata_quirk_names[] = {
3873         [__ATA_QUIRK_DIAGNOSTIC]        = "diagnostic",
3874         [__ATA_QUIRK_NODMA]             = "nodma",
3875         [__ATA_QUIRK_NONCQ]             = "noncq",
3876         [__ATA_QUIRK_MAX_SEC_128]       = "maxsec128",
3877         [__ATA_QUIRK_BROKEN_HPA]        = "brokenhpa",
3878         [__ATA_QUIRK_DISABLE]           = "disable",
3879         [__ATA_QUIRK_HPA_SIZE]          = "hpasize",
3880         [__ATA_QUIRK_IVB]               = "ivb",
3881         [__ATA_QUIRK_STUCK_ERR]         = "stuckerr",
3882         [__ATA_QUIRK_BRIDGE_OK]         = "bridgeok",
3883         [__ATA_QUIRK_ATAPI_MOD16_DMA]   = "atapimod16dma",
3884         [__ATA_QUIRK_FIRMWARE_WARN]     = "firmwarewarn",
3885         [__ATA_QUIRK_1_5_GBPS]          = "1.5gbps",
3886         [__ATA_QUIRK_NOSETXFER]         = "nosetxfer",
3887         [__ATA_QUIRK_BROKEN_FPDMA_AA]   = "brokenfpdmaaa",
3888         [__ATA_QUIRK_DUMP_ID]           = "dumpid",
3889         [__ATA_QUIRK_MAX_SEC_LBA48]     = "maxseclba48",
3890         [__ATA_QUIRK_ATAPI_DMADIR]      = "atapidmadir",
3891         [__ATA_QUIRK_NO_NCQ_TRIM]       = "noncqtrim",
3892         [__ATA_QUIRK_NOLPM]             = "nolpm",
3893         [__ATA_QUIRK_WD_BROKEN_LPM]     = "wdbrokenlpm",
3894         [__ATA_QUIRK_ZERO_AFTER_TRIM]   = "zeroaftertrim",
3895         [__ATA_QUIRK_NO_DMA_LOG]        = "nodmalog",
3896         [__ATA_QUIRK_NOTRIM]            = "notrim",
3897         [__ATA_QUIRK_MAX_SEC_1024]      = "maxsec1024",
3898         [__ATA_QUIRK_MAX_TRIM_128M]     = "maxtrim128m",
3899         [__ATA_QUIRK_NO_NCQ_ON_ATI]     = "noncqonati",
3900         [__ATA_QUIRK_NO_ID_DEV_LOG]     = "noiddevlog",
3901         [__ATA_QUIRK_NO_LOG_DIR]        = "nologdir",
3902         [__ATA_QUIRK_NO_FUA]            = "nofua",
3903 };
3904
3905 static void ata_dev_print_quirks(const struct ata_device *dev,
3906                                  const char *model, const char *rev,
3907                                  unsigned int quirks)
3908 {
3909         struct ata_eh_context *ehc = &dev->link->eh_context;
3910         int n = 0, i;
3911         size_t sz;
3912         char *str;
3913
3914         if (!ata_dev_print_info(dev) || ehc->i.flags & ATA_EHI_DID_PRINT_QUIRKS)
3915                 return;
3916
3917         ehc->i.flags |= ATA_EHI_DID_PRINT_QUIRKS;
3918
3919         if (!quirks)
3920                 return;
3921
3922         sz = 64 + ARRAY_SIZE(ata_quirk_names) * 16;
3923         str = kmalloc(sz, GFP_KERNEL);
3924         if (!str)
3925                 return;
3926
3927         n = snprintf(str, sz, "Model '%s', rev '%s', applying quirks:",
3928                      model, rev);
3929
3930         for (i = 0; i < ARRAY_SIZE(ata_quirk_names); i++) {
3931                 if (quirks & (1U << i))
3932                         n += snprintf(str + n, sz - n,
3933                                       " %s", ata_quirk_names[i]);
3934         }
3935
3936         ata_dev_warn(dev, "%s\n", str);
3937
3938         kfree(str);
3939 }
3940
3941 struct ata_dev_quirks_entry {
3942         const char *model_num;
3943         const char *model_rev;
3944         unsigned int quirks;
3945 };
3946
3947 static const struct ata_dev_quirks_entry __ata_dev_quirks[] = {
3948         /* Devices with DMA related problems under Linux */
3949         { "WDC AC11000H",       NULL,           ATA_QUIRK_NODMA },
3950         { "WDC AC22100H",       NULL,           ATA_QUIRK_NODMA },
3951         { "WDC AC32500H",       NULL,           ATA_QUIRK_NODMA },
3952         { "WDC AC33100H",       NULL,           ATA_QUIRK_NODMA },
3953         { "WDC AC31600H",       NULL,           ATA_QUIRK_NODMA },
3954         { "WDC AC32100H",       "24.09P07",     ATA_QUIRK_NODMA },
3955         { "WDC AC23200L",       "21.10N21",     ATA_QUIRK_NODMA },
3956         { "Compaq CRD-8241B",   NULL,           ATA_QUIRK_NODMA },
3957         { "CRD-8400B",          NULL,           ATA_QUIRK_NODMA },
3958         { "CRD-848[02]B",       NULL,           ATA_QUIRK_NODMA },
3959         { "CRD-84",             NULL,           ATA_QUIRK_NODMA },
3960         { "SanDisk SDP3B",      NULL,           ATA_QUIRK_NODMA },
3961         { "SanDisk SDP3B-64",   NULL,           ATA_QUIRK_NODMA },
3962         { "SANYO CD-ROM CRD",   NULL,           ATA_QUIRK_NODMA },
3963         { "HITACHI CDR-8",      NULL,           ATA_QUIRK_NODMA },
3964         { "HITACHI CDR-8[34]35", NULL,          ATA_QUIRK_NODMA },
3965         { "Toshiba CD-ROM XM-6202B", NULL,      ATA_QUIRK_NODMA },
3966         { "TOSHIBA CD-ROM XM-1702BC", NULL,     ATA_QUIRK_NODMA },
3967         { "CD-532E-A",          NULL,           ATA_QUIRK_NODMA },
3968         { "E-IDE CD-ROM CR-840", NULL,          ATA_QUIRK_NODMA },
3969         { "CD-ROM Drive/F5A",   NULL,           ATA_QUIRK_NODMA },
3970         { "WPI CDD-820",        NULL,           ATA_QUIRK_NODMA },
3971         { "SAMSUNG CD-ROM SC-148C", NULL,       ATA_QUIRK_NODMA },
3972         { "SAMSUNG CD-ROM SC",  NULL,           ATA_QUIRK_NODMA },
3973         { "ATAPI CD-ROM DRIVE 40X MAXIMUM", NULL, ATA_QUIRK_NODMA },
3974         { "_NEC DV5800A",       NULL,           ATA_QUIRK_NODMA },
3975         { "SAMSUNG CD-ROM SN-124", "N001",      ATA_QUIRK_NODMA },
3976         { "Seagate STT20000A", NULL,            ATA_QUIRK_NODMA },
3977         { " 2GB ATA Flash Disk", "ADMA428M",    ATA_QUIRK_NODMA },
3978         { "VRFDFC22048UCHC-TE*", NULL,          ATA_QUIRK_NODMA },
3979         /* Odd clown on sil3726/4726 PMPs */
3980         { "Config  Disk",       NULL,           ATA_QUIRK_DISABLE },
3981         /* Similar story with ASMedia 1092 */
3982         { "ASMT109x- Config",   NULL,           ATA_QUIRK_DISABLE },
3983
3984         /* Weird ATAPI devices */
3985         { "TORiSAN DVD-ROM DRD-N216", NULL,     ATA_QUIRK_MAX_SEC_128 },
3986         { "QUANTUM DAT    DAT72-000", NULL,     ATA_QUIRK_ATAPI_MOD16_DMA },
3987         { "Slimtype DVD A  DS8A8SH", NULL,      ATA_QUIRK_MAX_SEC_LBA48 },
3988         { "Slimtype DVD A  DS8A9SH", NULL,      ATA_QUIRK_MAX_SEC_LBA48 },
3989
3990         /*
3991          * Causes silent data corruption with higher max sects.
3992          * http://lkml.kernel.org/g/[email protected]
3993          */
3994         { "ST380013AS",         "3.20",         ATA_QUIRK_MAX_SEC_1024 },
3995
3996         /*
3997          * These devices time out with higher max sects.
3998          * https://bugzilla.kernel.org/show_bug.cgi?id=121671
3999          */
4000         { "LITEON CX1-JB*-HP",  NULL,           ATA_QUIRK_MAX_SEC_1024 },
4001         { "LITEON EP1-*",       NULL,           ATA_QUIRK_MAX_SEC_1024 },
4002
4003         /* Devices we expect to fail diagnostics */
4004
4005         /* Devices where NCQ should be avoided */
4006         /* NCQ is slow */
4007         { "WDC WD740ADFD-00",   NULL,           ATA_QUIRK_NONCQ },
4008         { "WDC WD740ADFD-00NLR1", NULL,         ATA_QUIRK_NONCQ },
4009         /* http://thread.gmane.org/gmane.linux.ide/14907 */
4010         { "FUJITSU MHT2060BH",  NULL,           ATA_QUIRK_NONCQ },
4011         /* NCQ is broken */
4012         { "Maxtor *",           "BANC*",        ATA_QUIRK_NONCQ },
4013         { "Maxtor 7V300F0",     "VA111630",     ATA_QUIRK_NONCQ },
4014         { "ST380817AS",         "3.42",         ATA_QUIRK_NONCQ },
4015         { "ST3160023AS",        "3.42",         ATA_QUIRK_NONCQ },
4016         { "OCZ CORE_SSD",       "02.10104",     ATA_QUIRK_NONCQ },
4017
4018         /* Seagate NCQ + FLUSH CACHE firmware bug */
4019         { "ST31500341AS",       "SD1[5-9]",     ATA_QUIRK_NONCQ |
4020                                                 ATA_QUIRK_FIRMWARE_WARN },
4021
4022         { "ST31000333AS",       "SD1[5-9]",     ATA_QUIRK_NONCQ |
4023                                                 ATA_QUIRK_FIRMWARE_WARN },
4024
4025         { "ST3640[36]23AS",     "SD1[5-9]",     ATA_QUIRK_NONCQ |
4026                                                 ATA_QUIRK_FIRMWARE_WARN },
4027
4028         { "ST3320[68]13AS",     "SD1[5-9]",     ATA_QUIRK_NONCQ |
4029                                                 ATA_QUIRK_FIRMWARE_WARN },
4030
4031         /* drives which fail FPDMA_AA activation (some may freeze afterwards)
4032            the ST disks also have LPM issues */
4033         { "ST1000LM024 HN-M101MBB", NULL,       ATA_QUIRK_BROKEN_FPDMA_AA |
4034                                                 ATA_QUIRK_NOLPM },
4035         { "VB0250EAVER",        "HPG7",         ATA_QUIRK_BROKEN_FPDMA_AA },
4036
4037         /* Blacklist entries taken from Silicon Image 3124/3132
4038            Windows driver .inf file - also several Linux problem reports */
4039         { "HTS541060G9SA00",    "MB3OC60D",     ATA_QUIRK_NONCQ },
4040         { "HTS541080G9SA00",    "MB4OC60D",     ATA_QUIRK_NONCQ },
4041         { "HTS541010G9SA00",    "MBZOC60D",     ATA_QUIRK_NONCQ },
4042
4043         /* https://bugzilla.kernel.org/show_bug.cgi?id=15573 */
4044         { "C300-CTFDDAC128MAG", "0001",         ATA_QUIRK_NONCQ },
4045
4046         /* Sandisk SD7/8/9s lock up hard on large trims */
4047         { "SanDisk SD[789]*",   NULL,           ATA_QUIRK_MAX_TRIM_128M },
4048
4049         /* devices which puke on READ_NATIVE_MAX */
4050         { "HDS724040KLSA80",    "KFAOA20N",     ATA_QUIRK_BROKEN_HPA },
4051         { "WDC WD3200JD-00KLB0", "WD-WCAMR1130137", ATA_QUIRK_BROKEN_HPA },
4052         { "WDC WD2500JD-00HBB0", "WD-WMAL71490727", ATA_QUIRK_BROKEN_HPA },
4053         { "MAXTOR 6L080L4",     "A93.0500",     ATA_QUIRK_BROKEN_HPA },
4054
4055         /* this one allows HPA unlocking but fails IOs on the area */
4056         { "OCZ-VERTEX",             "1.30",     ATA_QUIRK_BROKEN_HPA },
4057
4058         /* Devices which report 1 sector over size HPA */
4059         { "ST340823A",          NULL,           ATA_QUIRK_HPA_SIZE },
4060         { "ST320413A",          NULL,           ATA_QUIRK_HPA_SIZE },
4061         { "ST310211A",          NULL,           ATA_QUIRK_HPA_SIZE },
4062
4063         /* Devices which get the IVB wrong */
4064         { "QUANTUM FIREBALLlct10 05", "A03.0900", ATA_QUIRK_IVB },
4065         /* Maybe we should just add all TSSTcorp devices... */
4066         { "TSSTcorp CDDVDW SH-S202[HJN]", "SB0[01]",  ATA_QUIRK_IVB },
4067
4068         /* Devices that do not need bridging limits applied */
4069         { "MTRON MSP-SATA*",            NULL,   ATA_QUIRK_BRIDGE_OK },
4070         { "BUFFALO HD-QSU2/R5",         NULL,   ATA_QUIRK_BRIDGE_OK },
4071
4072         /* Devices which aren't very happy with higher link speeds */
4073         { "WD My Book",                 NULL,   ATA_QUIRK_1_5_GBPS },
4074         { "Seagate FreeAgent GoFlex",   NULL,   ATA_QUIRK_1_5_GBPS },
4075
4076         /*
4077          * Devices which choke on SETXFER.  Applies only if both the
4078          * device and controller are SATA.
4079          */
4080         { "PIONEER DVD-RW  DVRTD08",    NULL,   ATA_QUIRK_NOSETXFER },
4081         { "PIONEER DVD-RW  DVRTD08A",   NULL,   ATA_QUIRK_NOSETXFER },
4082         { "PIONEER DVD-RW  DVR-215",    NULL,   ATA_QUIRK_NOSETXFER },
4083         { "PIONEER DVD-RW  DVR-212D",   NULL,   ATA_QUIRK_NOSETXFER },
4084         { "PIONEER DVD-RW  DVR-216D",   NULL,   ATA_QUIRK_NOSETXFER },
4085
4086         /* These specific Pioneer models have LPM issues */
4087         { "PIONEER BD-RW   BDR-207M",   NULL,   ATA_QUIRK_NOLPM },
4088         { "PIONEER BD-RW   BDR-205",    NULL,   ATA_QUIRK_NOLPM },
4089
4090         /* Crucial devices with broken LPM support */
4091         { "CT*0BX*00SSD1",              NULL,   ATA_QUIRK_NOLPM },
4092
4093         /* 512GB MX100 with MU01 firmware has both queued TRIM and LPM issues */
4094         { "Crucial_CT512MX100*",        "MU01", ATA_QUIRK_NO_NCQ_TRIM |
4095                                                 ATA_QUIRK_ZERO_AFTER_TRIM |
4096                                                 ATA_QUIRK_NOLPM },
4097         /* 512GB MX100 with newer firmware has only LPM issues */
4098         { "Crucial_CT512MX100*",        NULL,   ATA_QUIRK_ZERO_AFTER_TRIM |
4099                                                 ATA_QUIRK_NOLPM },
4100
4101         /* 480GB+ M500 SSDs have both queued TRIM and LPM issues */
4102         { "Crucial_CT480M500*",         NULL,   ATA_QUIRK_NO_NCQ_TRIM |
4103                                                 ATA_QUIRK_ZERO_AFTER_TRIM |
4104                                                 ATA_QUIRK_NOLPM },
4105         { "Crucial_CT960M500*",         NULL,   ATA_QUIRK_NO_NCQ_TRIM |
4106                                                 ATA_QUIRK_ZERO_AFTER_TRIM |
4107                                                 ATA_QUIRK_NOLPM },
4108
4109         /* AMD Radeon devices with broken LPM support */
4110         { "R3SL240G",                   NULL,   ATA_QUIRK_NOLPM },
4111
4112         /* Apacer models with LPM issues */
4113         { "Apacer AS340*",              NULL,   ATA_QUIRK_NOLPM },
4114
4115         /* These specific Samsung models/firmware-revs do not handle LPM well */
4116         { "SAMSUNG MZMPC128HBFU-000MV", "CXM14M1Q", ATA_QUIRK_NOLPM },
4117         { "SAMSUNG SSD PM830 mSATA *",  "CXM13D1Q", ATA_QUIRK_NOLPM },
4118         { "SAMSUNG MZ7TD256HAFV-000L9", NULL,       ATA_QUIRK_NOLPM },
4119         { "SAMSUNG MZ7TE512HMHP-000L1", "EXT06L0Q", ATA_QUIRK_NOLPM },
4120
4121         /* devices that don't properly handle queued TRIM commands */
4122         { "Micron_M500IT_*",            "MU01", ATA_QUIRK_NO_NCQ_TRIM |
4123                                                 ATA_QUIRK_ZERO_AFTER_TRIM },
4124         { "Micron_M500_*",              NULL,   ATA_QUIRK_NO_NCQ_TRIM |
4125                                                 ATA_QUIRK_ZERO_AFTER_TRIM },
4126         { "Micron_M5[15]0_*",           "MU01", ATA_QUIRK_NO_NCQ_TRIM |
4127                                                 ATA_QUIRK_ZERO_AFTER_TRIM },
4128         { "Micron_1100_*",              NULL,   ATA_QUIRK_NO_NCQ_TRIM |
4129                                                 ATA_QUIRK_ZERO_AFTER_TRIM, },
4130         { "Crucial_CT*M500*",           NULL,   ATA_QUIRK_NO_NCQ_TRIM |
4131                                                 ATA_QUIRK_ZERO_AFTER_TRIM },
4132         { "Crucial_CT*M550*",           "MU01", ATA_QUIRK_NO_NCQ_TRIM |
4133                                                 ATA_QUIRK_ZERO_AFTER_TRIM },
4134         { "Crucial_CT*MX100*",          "MU01", ATA_QUIRK_NO_NCQ_TRIM |
4135                                                 ATA_QUIRK_ZERO_AFTER_TRIM },
4136         { "Samsung SSD 840 EVO*",       NULL,   ATA_QUIRK_NO_NCQ_TRIM |
4137                                                 ATA_QUIRK_NO_DMA_LOG |
4138                                                 ATA_QUIRK_ZERO_AFTER_TRIM },
4139         { "Samsung SSD 840*",           NULL,   ATA_QUIRK_NO_NCQ_TRIM |
4140                                                 ATA_QUIRK_ZERO_AFTER_TRIM },
4141         { "Samsung SSD 850*",           NULL,   ATA_QUIRK_NO_NCQ_TRIM |
4142                                                 ATA_QUIRK_ZERO_AFTER_TRIM },
4143         { "Samsung SSD 860*",           NULL,   ATA_QUIRK_NO_NCQ_TRIM |
4144                                                 ATA_QUIRK_ZERO_AFTER_TRIM |
4145                                                 ATA_QUIRK_NO_NCQ_ON_ATI },
4146         { "Samsung SSD 870*",           NULL,   ATA_QUIRK_NO_NCQ_TRIM |
4147                                                 ATA_QUIRK_ZERO_AFTER_TRIM |
4148                                                 ATA_QUIRK_NO_NCQ_ON_ATI },
4149         { "SAMSUNG*MZ7LH*",             NULL,   ATA_QUIRK_NO_NCQ_TRIM |
4150                                                 ATA_QUIRK_ZERO_AFTER_TRIM |
4151                                                 ATA_QUIRK_NO_NCQ_ON_ATI, },
4152         { "FCCT*M500*",                 NULL,   ATA_QUIRK_NO_NCQ_TRIM |
4153                                                 ATA_QUIRK_ZERO_AFTER_TRIM },
4154
4155         /* devices that don't properly handle TRIM commands */
4156         { "SuperSSpeed S238*",          NULL,   ATA_QUIRK_NOTRIM },
4157         { "M88V29*",                    NULL,   ATA_QUIRK_NOTRIM },
4158
4159         /*
4160          * As defined, the DRAT (Deterministic Read After Trim) and RZAT
4161          * (Return Zero After Trim) flags in the ATA Command Set are
4162          * unreliable in the sense that they only define what happens if
4163          * the device successfully executed the DSM TRIM command. TRIM
4164          * is only advisory, however, and the device is free to silently
4165          * ignore all or parts of the request.
4166          *
4167          * Whitelist drives that are known to reliably return zeroes
4168          * after TRIM.
4169          */
4170
4171         /*
4172          * The intel 510 drive has buggy DRAT/RZAT. Explicitly exclude
4173          * that model before whitelisting all other intel SSDs.
4174          */
4175         { "INTEL*SSDSC2MH*",            NULL,   0 },
4176
4177         { "Micron*",                    NULL,   ATA_QUIRK_ZERO_AFTER_TRIM },
4178         { "Crucial*",                   NULL,   ATA_QUIRK_ZERO_AFTER_TRIM },
4179         { "INTEL*SSD*",                 NULL,   ATA_QUIRK_ZERO_AFTER_TRIM },
4180         { "SSD*INTEL*",                 NULL,   ATA_QUIRK_ZERO_AFTER_TRIM },
4181         { "Samsung*SSD*",               NULL,   ATA_QUIRK_ZERO_AFTER_TRIM },
4182         { "SAMSUNG*SSD*",               NULL,   ATA_QUIRK_ZERO_AFTER_TRIM },
4183         { "SAMSUNG*MZ7KM*",             NULL,   ATA_QUIRK_ZERO_AFTER_TRIM },
4184         { "ST[1248][0248]0[FH]*",       NULL,   ATA_QUIRK_ZERO_AFTER_TRIM },
4185
4186         /*
4187          * Some WD SATA-I drives spin up and down erratically when the link
4188          * is put into the slumber mode.  We don't have full list of the
4189          * affected devices.  Disable LPM if the device matches one of the
4190          * known prefixes and is SATA-1.  As a side effect LPM partial is
4191          * lost too.
4192          *
4193          * https://bugzilla.kernel.org/show_bug.cgi?id=57211
4194          */
4195         { "WDC WD800JD-*",              NULL,   ATA_QUIRK_WD_BROKEN_LPM },
4196         { "WDC WD1200JD-*",             NULL,   ATA_QUIRK_WD_BROKEN_LPM },
4197         { "WDC WD1600JD-*",             NULL,   ATA_QUIRK_WD_BROKEN_LPM },
4198         { "WDC WD2000JD-*",             NULL,   ATA_QUIRK_WD_BROKEN_LPM },
4199         { "WDC WD2500JD-*",             NULL,   ATA_QUIRK_WD_BROKEN_LPM },
4200         { "WDC WD3000JD-*",             NULL,   ATA_QUIRK_WD_BROKEN_LPM },
4201         { "WDC WD3200JD-*",             NULL,   ATA_QUIRK_WD_BROKEN_LPM },
4202
4203         /*
4204          * This sata dom device goes on a walkabout when the ATA_LOG_DIRECTORY
4205          * log page is accessed. Ensure we never ask for this log page with
4206          * these devices.
4207          */
4208         { "SATADOM-ML 3ME",             NULL,   ATA_QUIRK_NO_LOG_DIR },
4209
4210         /* Buggy FUA */
4211         { "Maxtor",             "BANC1G10",     ATA_QUIRK_NO_FUA },
4212         { "WDC*WD2500J*",       NULL,           ATA_QUIRK_NO_FUA },
4213         { "OCZ-VERTEX*",        NULL,           ATA_QUIRK_NO_FUA },
4214         { "INTEL*SSDSC2CT*",    NULL,           ATA_QUIRK_NO_FUA },
4215
4216         /* End Marker */
4217         { }
4218 };
4219
4220 static unsigned int ata_dev_quirks(const struct ata_device *dev)
4221 {
4222         unsigned char model_num[ATA_ID_PROD_LEN + 1];
4223         unsigned char model_rev[ATA_ID_FW_REV_LEN + 1];
4224         const struct ata_dev_quirks_entry *ad = __ata_dev_quirks;
4225
4226         /* dev->quirks is an unsigned int. */
4227         BUILD_BUG_ON(__ATA_QUIRK_MAX > 32);
4228
4229         ata_id_c_string(dev->id, model_num, ATA_ID_PROD, sizeof(model_num));
4230         ata_id_c_string(dev->id, model_rev, ATA_ID_FW_REV, sizeof(model_rev));
4231
4232         while (ad->model_num) {
4233                 if (glob_match(ad->model_num, model_num) &&
4234                     (!ad->model_rev || glob_match(ad->model_rev, model_rev))) {
4235                         ata_dev_print_quirks(dev, model_num, model_rev,
4236                                              ad->quirks);
4237                         return ad->quirks;
4238                 }
4239                 ad++;
4240         }
4241         return 0;
4242 }
4243
4244 static bool ata_dev_nodma(const struct ata_device *dev)
4245 {
4246         /*
4247          * We do not support polling DMA. Deny DMA for those ATAPI devices
4248          * with CDB-intr (and use PIO) if the LLDD handles only interrupts in
4249          * the HSM_ST_LAST state.
4250          */
4251         if ((dev->link->ap->flags & ATA_FLAG_PIO_POLLING) &&
4252             (dev->flags & ATA_DFLAG_CDB_INTR))
4253                 return true;
4254         return dev->quirks & ATA_QUIRK_NODMA;
4255 }
4256
4257 /**
4258  *      ata_is_40wire           -       check drive side detection
4259  *      @dev: device
4260  *
4261  *      Perform drive side detection decoding, allowing for device vendors
4262  *      who can't follow the documentation.
4263  */
4264
4265 static int ata_is_40wire(struct ata_device *dev)
4266 {
4267         if (dev->quirks & ATA_QUIRK_IVB)
4268                 return ata_drive_40wire_relaxed(dev->id);
4269         return ata_drive_40wire(dev->id);
4270 }
4271
4272 /**
4273  *      cable_is_40wire         -       40/80/SATA decider
4274  *      @ap: port to consider
4275  *
4276  *      This function encapsulates the policy for speed management
4277  *      in one place. At the moment we don't cache the result but
4278  *      there is a good case for setting ap->cbl to the result when
4279  *      we are called with unknown cables (and figuring out if it
4280  *      impacts hotplug at all).
4281  *
4282  *      Return 1 if the cable appears to be 40 wire.
4283  */
4284
4285 static int cable_is_40wire(struct ata_port *ap)
4286 {
4287         struct ata_link *link;
4288         struct ata_device *dev;
4289
4290         /* If the controller thinks we are 40 wire, we are. */
4291         if (ap->cbl == ATA_CBL_PATA40)
4292                 return 1;
4293
4294         /* If the controller thinks we are 80 wire, we are. */
4295         if (ap->cbl == ATA_CBL_PATA80 || ap->cbl == ATA_CBL_SATA)
4296                 return 0;
4297
4298         /* If the system is known to be 40 wire short cable (eg
4299          * laptop), then we allow 80 wire modes even if the drive
4300          * isn't sure.
4301          */
4302         if (ap->cbl == ATA_CBL_PATA40_SHORT)
4303                 return 0;
4304
4305         /* If the controller doesn't know, we scan.
4306          *
4307          * Note: We look for all 40 wire detects at this point.  Any
4308          *       80 wire detect is taken to be 80 wire cable because
4309          * - in many setups only the one drive (slave if present) will
4310          *   give a valid detect
4311          * - if you have a non detect capable drive you don't want it
4312          *   to colour the choice
4313          */
4314         ata_for_each_link(link, ap, EDGE) {
4315                 ata_for_each_dev(dev, link, ENABLED) {
4316                         if (!ata_is_40wire(dev))
4317                                 return 0;
4318                 }
4319         }
4320         return 1;
4321 }
4322
4323 /**
4324  *      ata_dev_xfermask - Compute supported xfermask of the given device
4325  *      @dev: Device to compute xfermask for
4326  *
4327  *      Compute supported xfermask of @dev and store it in
4328  *      dev->*_mask.  This function is responsible for applying all
4329  *      known limits including host controller limits, device quirks, etc...
4330  *
4331  *      LOCKING:
4332  *      None.
4333  */
4334 static void ata_dev_xfermask(struct ata_device *dev)
4335 {
4336         struct ata_link *link = dev->link;
4337         struct ata_port *ap = link->ap;
4338         struct ata_host *host = ap->host;
4339         unsigned int xfer_mask;
4340
4341         /* controller modes available */
4342         xfer_mask = ata_pack_xfermask(ap->pio_mask,
4343                                       ap->mwdma_mask, ap->udma_mask);
4344
4345         /* drive modes available */
4346         xfer_mask &= ata_pack_xfermask(dev->pio_mask,
4347                                        dev->mwdma_mask, dev->udma_mask);
4348         xfer_mask &= ata_id_xfermask(dev->id);
4349
4350         /*
4351          *      CFA Advanced TrueIDE timings are not allowed on a shared
4352          *      cable
4353          */
4354         if (ata_dev_pair(dev)) {
4355                 /* No PIO5 or PIO6 */
4356                 xfer_mask &= ~(0x03 << (ATA_SHIFT_PIO + 5));
4357                 /* No MWDMA3 or MWDMA 4 */
4358                 xfer_mask &= ~(0x03 << (ATA_SHIFT_MWDMA + 3));
4359         }
4360
4361         if (ata_dev_nodma(dev)) {
4362                 xfer_mask &= ~(ATA_MASK_MWDMA | ATA_MASK_UDMA);
4363                 ata_dev_warn(dev,
4364                              "device does not support DMA, disabling DMA\n");
4365         }
4366
4367         if ((host->flags & ATA_HOST_SIMPLEX) &&
4368             host->simplex_claimed && host->simplex_claimed != ap) {
4369                 xfer_mask &= ~(ATA_MASK_MWDMA | ATA_MASK_UDMA);
4370                 ata_dev_warn(dev,
4371                              "simplex DMA is claimed by other device, disabling DMA\n");
4372         }
4373
4374         if (ap->flags & ATA_FLAG_NO_IORDY)
4375                 xfer_mask &= ata_pio_mask_no_iordy(dev);
4376
4377         if (ap->ops->mode_filter)
4378                 xfer_mask = ap->ops->mode_filter(dev, xfer_mask);
4379
4380         /* Apply cable rule here.  Don't apply it early because when
4381          * we handle hot plug the cable type can itself change.
4382          * Check this last so that we know if the transfer rate was
4383          * solely limited by the cable.
4384          * Unknown or 80 wire cables reported host side are checked
4385          * drive side as well. Cases where we know a 40wire cable
4386          * is used safely for 80 are not checked here.
4387          */
4388         if (xfer_mask & (0xF8 << ATA_SHIFT_UDMA))
4389                 /* UDMA/44 or higher would be available */
4390                 if (cable_is_40wire(ap)) {
4391                         ata_dev_warn(dev,
4392                                      "limited to UDMA/33 due to 40-wire cable\n");
4393                         xfer_mask &= ~(0xF8 << ATA_SHIFT_UDMA);
4394                 }
4395
4396         ata_unpack_xfermask(xfer_mask, &dev->pio_mask,
4397                             &dev->mwdma_mask, &dev->udma_mask);
4398 }
4399
4400 /**
4401  *      ata_dev_set_xfermode - Issue SET FEATURES - XFER MODE command
4402  *      @dev: Device to which command will be sent
4403  *
4404  *      Issue SET FEATURES - XFER MODE command to device @dev
4405  *      on port @ap.
4406  *
4407  *      LOCKING:
4408  *      PCI/etc. bus probe sem.
4409  *
4410  *      RETURNS:
4411  *      0 on success, AC_ERR_* mask otherwise.
4412  */
4413
4414 static unsigned int ata_dev_set_xfermode(struct ata_device *dev)
4415 {
4416         struct ata_taskfile tf;
4417
4418         /* set up set-features taskfile */
4419         ata_dev_dbg(dev, "set features - xfer mode\n");
4420
4421         /* Some controllers and ATAPI devices show flaky interrupt
4422          * behavior after setting xfer mode.  Use polling instead.
4423          */
4424         ata_tf_init(dev, &tf);
4425         tf.command = ATA_CMD_SET_FEATURES;
4426         tf.feature = SETFEATURES_XFER;
4427         tf.flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE | ATA_TFLAG_POLLING;
4428         tf.protocol = ATA_PROT_NODATA;
4429         /* If we are using IORDY we must send the mode setting command */
4430         if (ata_pio_need_iordy(dev))
4431                 tf.nsect = dev->xfer_mode;
4432         /* If the device has IORDY and the controller does not - turn it off */
4433         else if (ata_id_has_iordy(dev->id))
4434                 tf.nsect = 0x01;
4435         else /* In the ancient relic department - skip all of this */
4436                 return 0;
4437
4438         /*
4439          * On some disks, this command causes spin-up, so we need longer
4440          * timeout.
4441          */
4442         return ata_exec_internal(dev, &tf, NULL, DMA_NONE, NULL, 0, 15000);
4443 }
4444
4445 /**
4446  *      ata_dev_set_feature - Issue SET FEATURES
4447  *      @dev: Device to which command will be sent
4448  *      @subcmd: The SET FEATURES subcommand to be sent
4449  *      @action: The sector count represents a subcommand specific action
4450  *
4451  *      Issue SET FEATURES command to device @dev on port @ap with sector count
4452  *
4453  *      LOCKING:
4454  *      PCI/etc. bus probe sem.
4455  *
4456  *      RETURNS:
4457  *      0 on success, AC_ERR_* mask otherwise.
4458  */
4459 unsigned int ata_dev_set_feature(struct ata_device *dev, u8 subcmd, u8 action)
4460 {
4461         struct ata_taskfile tf;
4462         unsigned int timeout = 0;
4463
4464         /* set up set-features taskfile */
4465         ata_dev_dbg(dev, "set features\n");
4466
4467         ata_tf_init(dev, &tf);
4468         tf.command = ATA_CMD_SET_FEATURES;
4469         tf.feature = subcmd;
4470         tf.flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE;
4471         tf.protocol = ATA_PROT_NODATA;
4472         tf.nsect = action;
4473
4474         if (subcmd == SETFEATURES_SPINUP)
4475                 timeout = ata_probe_timeout ?
4476                           ata_probe_timeout * 1000 : SETFEATURES_SPINUP_TIMEOUT;
4477
4478         return ata_exec_internal(dev, &tf, NULL, DMA_NONE, NULL, 0, timeout);
4479 }
4480 EXPORT_SYMBOL_GPL(ata_dev_set_feature);
4481
4482 /**
4483  *      ata_dev_init_params - Issue INIT DEV PARAMS command
4484  *      @dev: Device to which command will be sent
4485  *      @heads: Number of heads (taskfile parameter)
4486  *      @sectors: Number of sectors (taskfile parameter)
4487  *
4488  *      LOCKING:
4489  *      Kernel thread context (may sleep)
4490  *
4491  *      RETURNS:
4492  *      0 on success, AC_ERR_* mask otherwise.
4493  */
4494 static unsigned int ata_dev_init_params(struct ata_device *dev,
4495                                         u16 heads, u16 sectors)
4496 {
4497         struct ata_taskfile tf;
4498         unsigned int err_mask;
4499
4500         /* Number of sectors per track 1-255. Number of heads 1-16 */
4501         if (sectors < 1 || sectors > 255 || heads < 1 || heads > 16)
4502                 return AC_ERR_INVALID;
4503
4504         /* set up init dev params taskfile */
4505         ata_dev_dbg(dev, "init dev params \n");
4506
4507         ata_tf_init(dev, &tf);
4508         tf.command = ATA_CMD_INIT_DEV_PARAMS;
4509         tf.flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE;
4510         tf.protocol = ATA_PROT_NODATA;
4511         tf.nsect = sectors;
4512         tf.device |= (heads - 1) & 0x0f; /* max head = num. of heads - 1 */
4513
4514         err_mask = ata_exec_internal(dev, &tf, NULL, DMA_NONE, NULL, 0, 0);
4515         /* A clean abort indicates an original or just out of spec drive
4516            and we should continue as we issue the setup based on the
4517            drive reported working geometry */
4518         if (err_mask == AC_ERR_DEV && (tf.error & ATA_ABORTED))
4519                 err_mask = 0;
4520
4521         return err_mask;
4522 }
4523
4524 /**
4525  *      atapi_check_dma - Check whether ATAPI DMA can be supported
4526  *      @qc: Metadata associated with taskfile to check
4527  *
4528  *      Allow low-level driver to filter ATA PACKET commands, returning
4529  *      a status indicating whether or not it is OK to use DMA for the
4530  *      supplied PACKET command.
4531  *
4532  *      LOCKING:
4533  *      spin_lock_irqsave(host lock)
4534  *
4535  *      RETURNS: 0 when ATAPI DMA can be used
4536  *               nonzero otherwise
4537  */
4538 int atapi_check_dma(struct ata_queued_cmd *qc)
4539 {
4540         struct ata_port *ap = qc->ap;
4541
4542         /* Don't allow DMA if it isn't multiple of 16 bytes.  Quite a
4543          * few ATAPI devices choke on such DMA requests.
4544          */
4545         if (!(qc->dev->quirks & ATA_QUIRK_ATAPI_MOD16_DMA) &&
4546             unlikely(qc->nbytes & 15))
4547                 return 1;
4548
4549         if (ap->ops->check_atapi_dma)
4550                 return ap->ops->check_atapi_dma(qc);
4551
4552         return 0;
4553 }
4554
4555 /**
4556  *      ata_std_qc_defer - Check whether a qc needs to be deferred
4557  *      @qc: ATA command in question
4558  *
4559  *      Non-NCQ commands cannot run with any other command, NCQ or
4560  *      not.  As upper layer only knows the queue depth, we are
4561  *      responsible for maintaining exclusion.  This function checks
4562  *      whether a new command @qc can be issued.
4563  *
4564  *      LOCKING:
4565  *      spin_lock_irqsave(host lock)
4566  *
4567  *      RETURNS:
4568  *      ATA_DEFER_* if deferring is needed, 0 otherwise.
4569  */
4570 int ata_std_qc_defer(struct ata_queued_cmd *qc)
4571 {
4572         struct ata_link *link = qc->dev->link;
4573
4574         if (ata_is_ncq(qc->tf.protocol)) {
4575                 if (!ata_tag_valid(link->active_tag))
4576                         return 0;
4577         } else {
4578                 if (!ata_tag_valid(link->active_tag) && !link->sactive)
4579                         return 0;
4580         }
4581
4582         return ATA_DEFER_LINK;
4583 }
4584 EXPORT_SYMBOL_GPL(ata_std_qc_defer);
4585
4586 /**
4587  *      ata_sg_init - Associate command with scatter-gather table.
4588  *      @qc: Command to be associated
4589  *      @sg: Scatter-gather table.
4590  *      @n_elem: Number of elements in s/g table.
4591  *
4592  *      Initialize the data-related elements of queued_cmd @qc
4593  *      to point to a scatter-gather table @sg, containing @n_elem
4594  *      elements.
4595  *
4596  *      LOCKING:
4597  *      spin_lock_irqsave(host lock)
4598  */
4599 void ata_sg_init(struct ata_queued_cmd *qc, struct scatterlist *sg,
4600                  unsigned int n_elem)
4601 {
4602         qc->sg = sg;
4603         qc->n_elem = n_elem;
4604         qc->cursg = qc->sg;
4605 }
4606
4607 #ifdef CONFIG_HAS_DMA
4608
4609 /**
4610  *      ata_sg_clean - Unmap DMA memory associated with command
4611  *      @qc: Command containing DMA memory to be released
4612  *
4613  *      Unmap all mapped DMA memory associated with this command.
4614  *
4615  *      LOCKING:
4616  *      spin_lock_irqsave(host lock)
4617  */
4618 static void ata_sg_clean(struct ata_queued_cmd *qc)
4619 {
4620         struct ata_port *ap = qc->ap;
4621         struct scatterlist *sg = qc->sg;
4622         int dir = qc->dma_dir;
4623
4624         WARN_ON_ONCE(sg == NULL);
4625
4626         if (qc->n_elem)
4627                 dma_unmap_sg(ap->dev, sg, qc->orig_n_elem, dir);
4628
4629         qc->flags &= ~ATA_QCFLAG_DMAMAP;
4630         qc->sg = NULL;
4631 }
4632
4633 /**
4634  *      ata_sg_setup - DMA-map the scatter-gather table associated with a command.
4635  *      @qc: Command with scatter-gather table to be mapped.
4636  *
4637  *      DMA-map the scatter-gather table associated with queued_cmd @qc.
4638  *
4639  *      LOCKING:
4640  *      spin_lock_irqsave(host lock)
4641  *
4642  *      RETURNS:
4643  *      Zero on success, negative on error.
4644  *
4645  */
4646 static int ata_sg_setup(struct ata_queued_cmd *qc)
4647 {
4648         struct ata_port *ap = qc->ap;
4649         unsigned int n_elem;
4650
4651         n_elem = dma_map_sg(ap->dev, qc->sg, qc->n_elem, qc->dma_dir);
4652         if (n_elem < 1)
4653                 return -1;
4654
4655         qc->orig_n_elem = qc->n_elem;
4656         qc->n_elem = n_elem;
4657         qc->flags |= ATA_QCFLAG_DMAMAP;
4658
4659         return 0;
4660 }
4661
4662 #else /* !CONFIG_HAS_DMA */
4663
4664 static inline void ata_sg_clean(struct ata_queued_cmd *qc) {}
4665 static inline int ata_sg_setup(struct ata_queued_cmd *qc) { return -1; }
4666
4667 #endif /* !CONFIG_HAS_DMA */
4668
4669 /**
4670  *      swap_buf_le16 - swap halves of 16-bit words in place
4671  *      @buf:  Buffer to swap
4672  *      @buf_words:  Number of 16-bit words in buffer.
4673  *
4674  *      Swap halves of 16-bit words if needed to convert from
4675  *      little-endian byte order to native cpu byte order, or
4676  *      vice-versa.
4677  *
4678  *      LOCKING:
4679  *      Inherited from caller.
4680  */
4681 void swap_buf_le16(u16 *buf, unsigned int buf_words)
4682 {
4683 #ifdef __BIG_ENDIAN
4684         unsigned int i;
4685
4686         for (i = 0; i < buf_words; i++)
4687                 buf[i] = le16_to_cpu(buf[i]);
4688 #endif /* __BIG_ENDIAN */
4689 }
4690
4691 /**
4692  *      ata_qc_free - free unused ata_queued_cmd
4693  *      @qc: Command to complete
4694  *
4695  *      Designed to free unused ata_queued_cmd object
4696  *      in case something prevents using it.
4697  *
4698  *      LOCKING:
4699  *      spin_lock_irqsave(host lock)
4700  */
4701 void ata_qc_free(struct ata_queued_cmd *qc)
4702 {
4703         qc->flags = 0;
4704         if (ata_tag_valid(qc->tag))
4705                 qc->tag = ATA_TAG_POISON;
4706 }
4707
4708 void __ata_qc_complete(struct ata_queued_cmd *qc)
4709 {
4710         struct ata_port *ap;
4711         struct ata_link *link;
4712
4713         if (WARN_ON_ONCE(!(qc->flags & ATA_QCFLAG_ACTIVE)))
4714                 return;
4715
4716         ap = qc->ap;
4717         link = qc->dev->link;
4718
4719         if (likely(qc->flags & ATA_QCFLAG_DMAMAP))
4720                 ata_sg_clean(qc);
4721
4722         /* command should be marked inactive atomically with qc completion */
4723         if (ata_is_ncq(qc->tf.protocol)) {
4724                 link->sactive &= ~(1 << qc->hw_tag);
4725                 if (!link->sactive)
4726                         ap->nr_active_links--;
4727         } else {
4728                 link->active_tag = ATA_TAG_POISON;
4729                 ap->nr_active_links--;
4730         }
4731
4732         /* clear exclusive status */
4733         if (unlikely(qc->flags & ATA_QCFLAG_CLEAR_EXCL &&
4734                      ap->excl_link == link))
4735                 ap->excl_link = NULL;
4736
4737         /*
4738          * Mark qc as inactive to prevent the port interrupt handler from
4739          * completing the command twice later, before the error handler is
4740          * called.
4741          */
4742         qc->flags &= ~ATA_QCFLAG_ACTIVE;
4743         ap->qc_active &= ~(1ULL << qc->tag);
4744
4745         /* call completion callback */
4746         qc->complete_fn(qc);
4747 }
4748
4749 static void fill_result_tf(struct ata_queued_cmd *qc)
4750 {
4751         struct ata_port *ap = qc->ap;
4752
4753         /*
4754          * rtf may already be filled (e.g. for successful NCQ commands).
4755          * If that is the case, we have nothing to do.
4756          */
4757         if (qc->flags & ATA_QCFLAG_RTF_FILLED)
4758                 return;
4759
4760         qc->result_tf.flags = qc->tf.flags;
4761         ap->ops->qc_fill_rtf(qc);
4762         qc->flags |= ATA_QCFLAG_RTF_FILLED;
4763 }
4764
4765 static void ata_verify_xfer(struct ata_queued_cmd *qc)
4766 {
4767         struct ata_device *dev = qc->dev;
4768
4769         if (!ata_is_data(qc->tf.protocol))
4770                 return;
4771
4772         if ((dev->mwdma_mask || dev->udma_mask) && ata_is_pio(qc->tf.protocol))
4773                 return;
4774
4775         dev->flags &= ~ATA_DFLAG_DUBIOUS_XFER;
4776 }
4777
4778 /**
4779  *      ata_qc_complete - Complete an active ATA command
4780  *      @qc: Command to complete
4781  *
4782  *      Indicate to the mid and upper layers that an ATA command has
4783  *      completed, with either an ok or not-ok status.
4784  *
4785  *      Refrain from calling this function multiple times when
4786  *      successfully completing multiple NCQ commands.
4787  *      ata_qc_complete_multiple() should be used instead, which will
4788  *      properly update IRQ expect state.
4789  *
4790  *      LOCKING:
4791  *      spin_lock_irqsave(host lock)
4792  */
4793 void ata_qc_complete(struct ata_queued_cmd *qc)
4794 {
4795         struct ata_port *ap = qc->ap;
4796         struct ata_device *dev = qc->dev;
4797         struct ata_eh_info *ehi = &dev->link->eh_info;
4798
4799         /* Trigger the LED (if available) */
4800         ledtrig_disk_activity(!!(qc->tf.flags & ATA_TFLAG_WRITE));
4801
4802         /*
4803          * In order to synchronize EH with the regular execution path, a qc that
4804          * is owned by EH is marked with ATA_QCFLAG_EH.
4805          *
4806          * The normal execution path is responsible for not accessing a qc owned
4807          * by EH.  libata core enforces the rule by returning NULL from
4808          * ata_qc_from_tag() for qcs owned by EH.
4809          */
4810         if (unlikely(qc->err_mask))
4811                 qc->flags |= ATA_QCFLAG_EH;
4812
4813         /*
4814          * Finish internal commands without any further processing and always
4815          * with the result TF filled.
4816          */
4817         if (unlikely(ata_tag_internal(qc->tag))) {
4818                 fill_result_tf(qc);
4819                 trace_ata_qc_complete_internal(qc);
4820                 __ata_qc_complete(qc);
4821                 return;
4822         }
4823
4824         /* Non-internal qc has failed.  Fill the result TF and summon EH. */
4825         if (unlikely(qc->flags & ATA_QCFLAG_EH)) {
4826                 fill_result_tf(qc);
4827                 trace_ata_qc_complete_failed(qc);
4828                 ata_qc_schedule_eh(qc);
4829                 return;
4830         }
4831
4832         WARN_ON_ONCE(ata_port_is_frozen(ap));
4833
4834         /* read result TF if requested */
4835         if (qc->flags & ATA_QCFLAG_RESULT_TF)
4836                 fill_result_tf(qc);
4837
4838         trace_ata_qc_complete_done(qc);
4839
4840         /*
4841          * For CDL commands that completed without an error, check if we have
4842          * sense data (ATA_SENSE is set). If we do, then the command may have
4843          * been aborted by the device due to a limit timeout using the policy
4844          * 0xD. For these commands, invoke EH to get the command sense data.
4845          */
4846         if (qc->flags & ATA_QCFLAG_HAS_CDL &&
4847             qc->result_tf.status & ATA_SENSE) {
4848                 /*
4849                  * Tell SCSI EH to not overwrite scmd->result even if this
4850                  * command is finished with result SAM_STAT_GOOD.
4851                  */
4852                 qc->scsicmd->flags |= SCMD_FORCE_EH_SUCCESS;
4853                 qc->flags |= ATA_QCFLAG_EH_SUCCESS_CMD;
4854                 ehi->dev_action[dev->devno] |= ATA_EH_GET_SUCCESS_SENSE;
4855
4856                 /*
4857                  * set pending so that ata_qc_schedule_eh() does not trigger
4858                  * fast drain, and freeze the port.
4859                  */
4860                 ap->pflags |= ATA_PFLAG_EH_PENDING;
4861                 ata_qc_schedule_eh(qc);
4862                 return;
4863         }
4864
4865         /* Some commands need post-processing after successful completion. */
4866         switch (qc->tf.command) {
4867         case ATA_CMD_SET_FEATURES:
4868                 if (qc->tf.feature != SETFEATURES_WC_ON &&
4869                     qc->tf.feature != SETFEATURES_WC_OFF &&
4870                     qc->tf.feature != SETFEATURES_RA_ON &&
4871                     qc->tf.feature != SETFEATURES_RA_OFF)
4872                         break;
4873                 fallthrough;
4874         case ATA_CMD_INIT_DEV_PARAMS: /* CHS translation changed */
4875         case ATA_CMD_SET_MULTI: /* multi_count changed */
4876                 /* revalidate device */
4877                 ehi->dev_action[dev->devno] |= ATA_EH_REVALIDATE;
4878                 ata_port_schedule_eh(ap);
4879                 break;
4880
4881         case ATA_CMD_SLEEP:
4882                 dev->flags |= ATA_DFLAG_SLEEPING;
4883                 break;
4884         }
4885
4886         if (unlikely(dev->flags & ATA_DFLAG_DUBIOUS_XFER))
4887                 ata_verify_xfer(qc);
4888
4889         __ata_qc_complete(qc);
4890 }
4891 EXPORT_SYMBOL_GPL(ata_qc_complete);
4892
4893 /**
4894  *      ata_qc_get_active - get bitmask of active qcs
4895  *      @ap: port in question
4896  *
4897  *      LOCKING:
4898  *      spin_lock_irqsave(host lock)
4899  *
4900  *      RETURNS:
4901  *      Bitmask of active qcs
4902  */
4903 u64 ata_qc_get_active(struct ata_port *ap)
4904 {
4905         u64 qc_active = ap->qc_active;
4906
4907         /* ATA_TAG_INTERNAL is sent to hw as tag 0 */
4908         if (qc_active & (1ULL << ATA_TAG_INTERNAL)) {
4909                 qc_active |= (1 << 0);
4910                 qc_active &= ~(1ULL << ATA_TAG_INTERNAL);
4911         }
4912
4913         return qc_active;
4914 }
4915 EXPORT_SYMBOL_GPL(ata_qc_get_active);
4916
4917 /**
4918  *      ata_qc_issue - issue taskfile to device
4919  *      @qc: command to issue to device
4920  *
4921  *      Prepare an ATA command to submission to device.
4922  *      This includes mapping the data into a DMA-able
4923  *      area, filling in the S/G table, and finally
4924  *      writing the taskfile to hardware, starting the command.
4925  *
4926  *      LOCKING:
4927  *      spin_lock_irqsave(host lock)
4928  */
4929 void ata_qc_issue(struct ata_queued_cmd *qc)
4930 {
4931         struct ata_port *ap = qc->ap;
4932         struct ata_link *link = qc->dev->link;
4933         u8 prot = qc->tf.protocol;
4934
4935         /* Make sure only one non-NCQ command is outstanding. */
4936         WARN_ON_ONCE(ata_tag_valid(link->active_tag));
4937
4938         if (ata_is_ncq(prot)) {
4939                 WARN_ON_ONCE(link->sactive & (1 << qc->hw_tag));
4940
4941                 if (!link->sactive)
4942                         ap->nr_active_links++;
4943                 link->sactive |= 1 << qc->hw_tag;
4944         } else {
4945                 WARN_ON_ONCE(link->sactive);
4946
4947                 ap->nr_active_links++;
4948                 link->active_tag = qc->tag;
4949         }
4950
4951         qc->flags |= ATA_QCFLAG_ACTIVE;
4952         ap->qc_active |= 1ULL << qc->tag;
4953
4954         /*
4955          * We guarantee to LLDs that they will have at least one
4956          * non-zero sg if the command is a data command.
4957          */
4958         if (ata_is_data(prot) && (!qc->sg || !qc->n_elem || !qc->nbytes))
4959                 goto sys_err;
4960
4961         if (ata_is_dma(prot) || (ata_is_pio(prot) &&
4962                                  (ap->flags & ATA_FLAG_PIO_DMA)))
4963                 if (ata_sg_setup(qc))
4964                         goto sys_err;
4965
4966         /* if device is sleeping, schedule reset and abort the link */
4967         if (unlikely(qc->dev->flags & ATA_DFLAG_SLEEPING)) {
4968                 link->eh_info.action |= ATA_EH_RESET;
4969                 ata_ehi_push_desc(&link->eh_info, "waking up from sleep");
4970                 ata_link_abort(link);
4971                 return;
4972         }
4973
4974         if (ap->ops->qc_prep) {
4975                 trace_ata_qc_prep(qc);
4976                 qc->err_mask |= ap->ops->qc_prep(qc);
4977                 if (unlikely(qc->err_mask))
4978                         goto err;
4979         }
4980
4981         trace_ata_qc_issue(qc);
4982         qc->err_mask |= ap->ops->qc_issue(qc);
4983         if (unlikely(qc->err_mask))
4984                 goto err;
4985         return;
4986
4987 sys_err:
4988         qc->err_mask |= AC_ERR_SYSTEM;
4989 err:
4990         ata_qc_complete(qc);
4991 }
4992
4993 /**
4994  *      ata_phys_link_online - test whether the given link is online
4995  *      @link: ATA link to test
4996  *
4997  *      Test whether @link is online.  Note that this function returns
4998  *      0 if online status of @link cannot be obtained, so
4999  *      ata_link_online(link) != !ata_link_offline(link).
5000  *
5001  *      LOCKING:
5002  *      None.
5003  *
5004  *      RETURNS:
5005  *      True if the port online status is available and online.
5006  */
5007 bool ata_phys_link_online(struct ata_link *link)
5008 {
5009         u32 sstatus;
5010
5011         if (sata_scr_read(link, SCR_STATUS, &sstatus) == 0 &&
5012             ata_sstatus_online(sstatus))
5013                 return true;
5014         return false;
5015 }
5016
5017 /**
5018  *      ata_phys_link_offline - test whether the given link is offline
5019  *      @link: ATA link to test
5020  *
5021  *      Test whether @link is offline.  Note that this function
5022  *      returns 0 if offline status of @link cannot be obtained, so
5023  *      ata_link_online(link) != !ata_link_offline(link).
5024  *
5025  *      LOCKING:
5026  *      None.
5027  *
5028  *      RETURNS:
5029  *      True if the port offline status is available and offline.
5030  */
5031 bool ata_phys_link_offline(struct ata_link *link)
5032 {
5033         u32 sstatus;
5034
5035         if (sata_scr_read(link, SCR_STATUS, &sstatus) == 0 &&
5036             !ata_sstatus_online(sstatus))
5037                 return true;
5038         return false;
5039 }
5040
5041 /**
5042  *      ata_link_online - test whether the given link is online
5043  *      @link: ATA link to test
5044  *
5045  *      Test whether @link is online.  This is identical to
5046  *      ata_phys_link_online() when there's no slave link.  When
5047  *      there's a slave link, this function should only be called on
5048  *      the master link and will return true if any of M/S links is
5049  *      online.
5050  *
5051  *      LOCKING:
5052  *      None.
5053  *
5054  *      RETURNS:
5055  *      True if the port online status is available and online.
5056  */
5057 bool ata_link_online(struct ata_link *link)
5058 {
5059         struct ata_link *slave = link->ap->slave_link;
5060
5061         WARN_ON(link == slave); /* shouldn't be called on slave link */
5062
5063         return ata_phys_link_online(link) ||
5064                 (slave && ata_phys_link_online(slave));
5065 }
5066 EXPORT_SYMBOL_GPL(ata_link_online);
5067
5068 /**
5069  *      ata_link_offline - test whether the given link is offline
5070  *      @link: ATA link to test
5071  *
5072  *      Test whether @link is offline.  This is identical to
5073  *      ata_phys_link_offline() when there's no slave link.  When
5074  *      there's a slave link, this function should only be called on
5075  *      the master link and will return true if both M/S links are
5076  *      offline.
5077  *
5078  *      LOCKING:
5079  *      None.
5080  *
5081  *      RETURNS:
5082  *      True if the port offline status is available and offline.
5083  */
5084 bool ata_link_offline(struct ata_link *link)
5085 {
5086         struct ata_link *slave = link->ap->slave_link;
5087
5088         WARN_ON(link == slave); /* shouldn't be called on slave link */
5089
5090         return ata_phys_link_offline(link) &&
5091                 (!slave || ata_phys_link_offline(slave));
5092 }
5093 EXPORT_SYMBOL_GPL(ata_link_offline);
5094
5095 #ifdef CONFIG_PM
5096 static void ata_port_request_pm(struct ata_port *ap, pm_message_t mesg,
5097                                 unsigned int action, unsigned int ehi_flags,
5098                                 bool async)
5099 {
5100         struct ata_link *link;
5101         unsigned long flags;
5102
5103         spin_lock_irqsave(ap->lock, flags);
5104
5105         /*
5106          * A previous PM operation might still be in progress. Wait for
5107          * ATA_PFLAG_PM_PENDING to clear.
5108          */
5109         if (ap->pflags & ATA_PFLAG_PM_PENDING) {
5110                 spin_unlock_irqrestore(ap->lock, flags);
5111                 ata_port_wait_eh(ap);
5112                 spin_lock_irqsave(ap->lock, flags);
5113         }
5114
5115         /* Request PM operation to EH */
5116         ap->pm_mesg = mesg;
5117         ap->pflags |= ATA_PFLAG_PM_PENDING;
5118         ata_for_each_link(link, ap, HOST_FIRST) {
5119                 link->eh_info.action |= action;
5120                 link->eh_info.flags |= ehi_flags;
5121         }
5122
5123         ata_port_schedule_eh(ap);
5124
5125         spin_unlock_irqrestore(ap->lock, flags);
5126
5127         if (!async)
5128                 ata_port_wait_eh(ap);
5129 }
5130
5131 static void ata_port_suspend(struct ata_port *ap, pm_message_t mesg,
5132                              bool async)
5133 {
5134         /*
5135          * We are about to suspend the port, so we do not care about
5136          * scsi_rescan_device() calls scheduled by previous resume operations.
5137          * The next resume will schedule the rescan again. So cancel any rescan
5138          * that is not done yet.
5139          */
5140         cancel_delayed_work_sync(&ap->scsi_rescan_task);
5141
5142         /*
5143          * On some hardware, device fails to respond after spun down for
5144          * suspend. As the device will not be used until being resumed, we
5145          * do not need to touch the device. Ask EH to skip the usual stuff
5146          * and proceed directly to suspend.
5147          *
5148          * http://thread.gmane.org/gmane.linux.ide/46764
5149          */
5150         ata_port_request_pm(ap, mesg, 0,
5151                             ATA_EHI_QUIET | ATA_EHI_NO_AUTOPSY |
5152                             ATA_EHI_NO_RECOVERY,
5153                             async);
5154 }
5155
5156 static int ata_port_pm_suspend(struct device *dev)
5157 {
5158         struct ata_port *ap = to_ata_port(dev);
5159
5160         if (pm_runtime_suspended(dev))
5161                 return 0;
5162
5163         ata_port_suspend(ap, PMSG_SUSPEND, false);
5164         return 0;
5165 }
5166
5167 static int ata_port_pm_freeze(struct device *dev)
5168 {
5169         struct ata_port *ap = to_ata_port(dev);
5170
5171         if (pm_runtime_suspended(dev))
5172                 return 0;
5173
5174         ata_port_suspend(ap, PMSG_FREEZE, false);
5175         return 0;
5176 }
5177
5178 static int ata_port_pm_poweroff(struct device *dev)
5179 {
5180         if (!pm_runtime_suspended(dev))
5181                 ata_port_suspend(to_ata_port(dev), PMSG_HIBERNATE, false);
5182         return 0;
5183 }
5184
5185 static void ata_port_resume(struct ata_port *ap, pm_message_t mesg,
5186                             bool async)
5187 {
5188         ata_port_request_pm(ap, mesg, ATA_EH_RESET,
5189                             ATA_EHI_NO_AUTOPSY | ATA_EHI_QUIET,
5190                             async);
5191 }
5192
5193 static int ata_port_pm_resume(struct device *dev)
5194 {
5195         if (!pm_runtime_suspended(dev))
5196                 ata_port_resume(to_ata_port(dev), PMSG_RESUME, true);
5197         return 0;
5198 }
5199
5200 /*
5201  * For ODDs, the upper layer will poll for media change every few seconds,
5202  * which will make it enter and leave suspend state every few seconds. And
5203  * as each suspend will cause a hard/soft reset, the gain of runtime suspend
5204  * is very little and the ODD may malfunction after constantly being reset.
5205  * So the idle callback here will not proceed to suspend if a non-ZPODD capable
5206  * ODD is attached to the port.
5207  */
5208 static int ata_port_runtime_idle(struct device *dev)
5209 {
5210         struct ata_port *ap = to_ata_port(dev);
5211         struct ata_link *link;
5212         struct ata_device *adev;
5213
5214         ata_for_each_link(link, ap, HOST_FIRST) {
5215                 ata_for_each_dev(adev, link, ENABLED)
5216                         if (adev->class == ATA_DEV_ATAPI &&
5217                             !zpodd_dev_enabled(adev))
5218                                 return -EBUSY;
5219         }
5220
5221         return 0;
5222 }
5223
5224 static int ata_port_runtime_suspend(struct device *dev)
5225 {
5226         ata_port_suspend(to_ata_port(dev), PMSG_AUTO_SUSPEND, false);
5227         return 0;
5228 }
5229
5230 static int ata_port_runtime_resume(struct device *dev)
5231 {
5232         ata_port_resume(to_ata_port(dev), PMSG_AUTO_RESUME, false);
5233         return 0;
5234 }
5235
5236 static const struct dev_pm_ops ata_port_pm_ops = {
5237         .suspend = ata_port_pm_suspend,
5238         .resume = ata_port_pm_resume,
5239         .freeze = ata_port_pm_freeze,
5240         .thaw = ata_port_pm_resume,
5241         .poweroff = ata_port_pm_poweroff,
5242         .restore = ata_port_pm_resume,
5243
5244         .runtime_suspend = ata_port_runtime_suspend,
5245         .runtime_resume = ata_port_runtime_resume,
5246         .runtime_idle = ata_port_runtime_idle,
5247 };
5248
5249 /* sas ports don't participate in pm runtime management of ata_ports,
5250  * and need to resume ata devices at the domain level, not the per-port
5251  * level. sas suspend/resume is async to allow parallel port recovery
5252  * since sas has multiple ata_port instances per Scsi_Host.
5253  */
5254 void ata_sas_port_suspend(struct ata_port *ap)
5255 {
5256         ata_port_suspend(ap, PMSG_SUSPEND, true);
5257 }
5258 EXPORT_SYMBOL_GPL(ata_sas_port_suspend);
5259
5260 void ata_sas_port_resume(struct ata_port *ap)
5261 {
5262         ata_port_resume(ap, PMSG_RESUME, true);
5263 }
5264 EXPORT_SYMBOL_GPL(ata_sas_port_resume);
5265
5266 /**
5267  *      ata_host_suspend - suspend host
5268  *      @host: host to suspend
5269  *      @mesg: PM message
5270  *
5271  *      Suspend @host.  Actual operation is performed by port suspend.
5272  */
5273 void ata_host_suspend(struct ata_host *host, pm_message_t mesg)
5274 {
5275         host->dev->power.power_state = mesg;
5276 }
5277 EXPORT_SYMBOL_GPL(ata_host_suspend);
5278
5279 /**
5280  *      ata_host_resume - resume host
5281  *      @host: host to resume
5282  *
5283  *      Resume @host.  Actual operation is performed by port resume.
5284  */
5285 void ata_host_resume(struct ata_host *host)
5286 {
5287         host->dev->power.power_state = PMSG_ON;
5288 }
5289 EXPORT_SYMBOL_GPL(ata_host_resume);
5290 #endif
5291
5292 const struct device_type ata_port_type = {
5293         .name = ATA_PORT_TYPE_NAME,
5294 #ifdef CONFIG_PM
5295         .pm = &ata_port_pm_ops,
5296 #endif
5297 };
5298
5299 /**
5300  *      ata_dev_init - Initialize an ata_device structure
5301  *      @dev: Device structure to initialize
5302  *
5303  *      Initialize @dev in preparation for probing.
5304  *
5305  *      LOCKING:
5306  *      Inherited from caller.
5307  */
5308 void ata_dev_init(struct ata_device *dev)
5309 {
5310         struct ata_link *link = ata_dev_phys_link(dev);
5311         struct ata_port *ap = link->ap;
5312         unsigned long flags;
5313
5314         /* SATA spd limit is bound to the attached device, reset together */
5315         link->sata_spd_limit = link->hw_sata_spd_limit;
5316         link->sata_spd = 0;
5317
5318         /* High bits of dev->flags are used to record warm plug
5319          * requests which occur asynchronously.  Synchronize using
5320          * host lock.
5321          */
5322         spin_lock_irqsave(ap->lock, flags);
5323         dev->flags &= ~ATA_DFLAG_INIT_MASK;
5324         dev->quirks = 0;
5325         spin_unlock_irqrestore(ap->lock, flags);
5326
5327         memset((void *)dev + ATA_DEVICE_CLEAR_BEGIN, 0,
5328                ATA_DEVICE_CLEAR_END - ATA_DEVICE_CLEAR_BEGIN);
5329         dev->pio_mask = UINT_MAX;
5330         dev->mwdma_mask = UINT_MAX;
5331         dev->udma_mask = UINT_MAX;
5332 }
5333
5334 /**
5335  *      ata_link_init - Initialize an ata_link structure
5336  *      @ap: ATA port link is attached to
5337  *      @link: Link structure to initialize
5338  *      @pmp: Port multiplier port number
5339  *
5340  *      Initialize @link.
5341  *
5342  *      LOCKING:
5343  *      Kernel thread context (may sleep)
5344  */
5345 void ata_link_init(struct ata_port *ap, struct ata_link *link, int pmp)
5346 {
5347         int i;
5348
5349         /* clear everything except for devices */
5350         memset((void *)link + ATA_LINK_CLEAR_BEGIN, 0,
5351                ATA_LINK_CLEAR_END - ATA_LINK_CLEAR_BEGIN);
5352
5353         link->ap = ap;
5354         link->pmp = pmp;
5355         link->active_tag = ATA_TAG_POISON;
5356         link->hw_sata_spd_limit = UINT_MAX;
5357
5358         /* can't use iterator, ap isn't initialized yet */
5359         for (i = 0; i < ATA_MAX_DEVICES; i++) {
5360                 struct ata_device *dev = &link->device[i];
5361
5362                 dev->link = link;
5363                 dev->devno = dev - link->device;
5364 #ifdef CONFIG_ATA_ACPI
5365                 dev->gtf_filter = ata_acpi_gtf_filter;
5366 #endif
5367                 ata_dev_init(dev);
5368         }
5369 }
5370
5371 /**
5372  *      sata_link_init_spd - Initialize link->sata_spd_limit
5373  *      @link: Link to configure sata_spd_limit for
5374  *
5375  *      Initialize ``link->[hw_]sata_spd_limit`` to the currently
5376  *      configured value.
5377  *
5378  *      LOCKING:
5379  *      Kernel thread context (may sleep).
5380  *
5381  *      RETURNS:
5382  *      0 on success, -errno on failure.
5383  */
5384 int sata_link_init_spd(struct ata_link *link)
5385 {
5386         u8 spd;
5387         int rc;
5388
5389         rc = sata_scr_read(link, SCR_CONTROL, &link->saved_scontrol);
5390         if (rc)
5391                 return rc;
5392
5393         spd = (link->saved_scontrol >> 4) & 0xf;
5394         if (spd)
5395                 link->hw_sata_spd_limit &= (1 << spd) - 1;
5396
5397         ata_force_link_limits(link);
5398
5399         link->sata_spd_limit = link->hw_sata_spd_limit;
5400
5401         return 0;
5402 }
5403
5404 /**
5405  *      ata_port_alloc - allocate and initialize basic ATA port resources
5406  *      @host: ATA host this allocated port belongs to
5407  *
5408  *      Allocate and initialize basic ATA port resources.
5409  *
5410  *      RETURNS:
5411  *      Allocate ATA port on success, NULL on failure.
5412  *
5413  *      LOCKING:
5414  *      Inherited from calling layer (may sleep).
5415  */
5416 struct ata_port *ata_port_alloc(struct ata_host *host)
5417 {
5418         struct ata_port *ap;
5419         int id;
5420
5421         ap = kzalloc(sizeof(*ap), GFP_KERNEL);
5422         if (!ap)
5423                 return NULL;
5424
5425         ap->pflags |= ATA_PFLAG_INITIALIZING | ATA_PFLAG_FROZEN;
5426         ap->lock = &host->lock;
5427         id = ida_alloc_min(&ata_ida, 1, GFP_KERNEL);
5428         if (id < 0) {
5429                 kfree(ap);
5430                 return NULL;
5431         }
5432         ap->print_id = id;
5433         ap->host = host;
5434         ap->dev = host->dev;
5435
5436         mutex_init(&ap->scsi_scan_mutex);
5437         INIT_DELAYED_WORK(&ap->hotplug_task, ata_scsi_hotplug);
5438         INIT_DELAYED_WORK(&ap->scsi_rescan_task, ata_scsi_dev_rescan);
5439         INIT_LIST_HEAD(&ap->eh_done_q);
5440         init_waitqueue_head(&ap->eh_wait_q);
5441         init_completion(&ap->park_req_pending);
5442         timer_setup(&ap->fastdrain_timer, ata_eh_fastdrain_timerfn,
5443                     TIMER_DEFERRABLE);
5444
5445         ap->cbl = ATA_CBL_NONE;
5446
5447         ata_link_init(ap, &ap->link, 0);
5448
5449 #ifdef ATA_IRQ_TRAP
5450         ap->stats.unhandled_irq = 1;
5451         ap->stats.idle_irq = 1;
5452 #endif
5453         ata_sff_port_init(ap);
5454
5455         return ap;
5456 }
5457 EXPORT_SYMBOL_GPL(ata_port_alloc);
5458
5459 void ata_port_free(struct ata_port *ap)
5460 {
5461         if (!ap)
5462                 return;
5463
5464         kfree(ap->pmp_link);
5465         kfree(ap->slave_link);
5466         ida_free(&ata_ida, ap->print_id);
5467         kfree(ap);
5468 }
5469 EXPORT_SYMBOL_GPL(ata_port_free);
5470
5471 static void ata_devres_release(struct device *gendev, void *res)
5472 {
5473         struct ata_host *host = dev_get_drvdata(gendev);
5474         int i;
5475
5476         for (i = 0; i < host->n_ports; i++) {
5477                 struct ata_port *ap = host->ports[i];
5478
5479                 if (!ap)
5480                         continue;
5481
5482                 if (ap->scsi_host)
5483                         scsi_host_put(ap->scsi_host);
5484
5485         }
5486
5487         dev_set_drvdata(gendev, NULL);
5488         ata_host_put(host);
5489 }
5490
5491 static void ata_host_release(struct kref *kref)
5492 {
5493         struct ata_host *host = container_of(kref, struct ata_host, kref);
5494         int i;
5495
5496         for (i = 0; i < host->n_ports; i++) {
5497                 ata_port_free(host->ports[i]);
5498                 host->ports[i] = NULL;
5499         }
5500         kfree(host);
5501 }
5502
5503 void ata_host_get(struct ata_host *host)
5504 {
5505         kref_get(&host->kref);
5506 }
5507
5508 void ata_host_put(struct ata_host *host)
5509 {
5510         kref_put(&host->kref, ata_host_release);
5511 }
5512 EXPORT_SYMBOL_GPL(ata_host_put);
5513
5514 /**
5515  *      ata_host_alloc - allocate and init basic ATA host resources
5516  *      @dev: generic device this host is associated with
5517  *      @n_ports: the number of ATA ports associated with this host
5518  *
5519  *      Allocate and initialize basic ATA host resources.  LLD calls
5520  *      this function to allocate a host, initializes it fully and
5521  *      attaches it using ata_host_register().
5522  *
5523  *      RETURNS:
5524  *      Allocate ATA host on success, NULL on failure.
5525  *
5526  *      LOCKING:
5527  *      Inherited from calling layer (may sleep).
5528  */
5529 struct ata_host *ata_host_alloc(struct device *dev, int n_ports)
5530 {
5531         struct ata_host *host;
5532         size_t sz;
5533         int i;
5534         void *dr;
5535
5536         /* alloc a container for our list of ATA ports (buses) */
5537         sz = sizeof(struct ata_host) + n_ports * sizeof(void *);
5538         host = kzalloc(sz, GFP_KERNEL);
5539         if (!host)
5540                 return NULL;
5541
5542         if (!devres_open_group(dev, NULL, GFP_KERNEL)) {
5543                 kfree(host);
5544                 return NULL;
5545         }
5546
5547         dr = devres_alloc(ata_devres_release, 0, GFP_KERNEL);
5548         if (!dr) {
5549                 kfree(host);
5550                 goto err_out;
5551         }
5552
5553         devres_add(dev, dr);
5554         dev_set_drvdata(dev, host);
5555
5556         spin_lock_init(&host->lock);
5557         mutex_init(&host->eh_mutex);
5558         host->dev = dev;
5559         host->n_ports = n_ports;
5560         kref_init(&host->kref);
5561
5562         /* allocate ports bound to this host */
5563         for (i = 0; i < n_ports; i++) {
5564                 struct ata_port *ap;
5565
5566                 ap = ata_port_alloc(host);
5567                 if (!ap)
5568                         goto err_out;
5569
5570                 ap->port_no = i;
5571                 host->ports[i] = ap;
5572         }
5573
5574         devres_remove_group(dev, NULL);
5575         return host;
5576
5577  err_out:
5578         devres_release_group(dev, NULL);
5579         return NULL;
5580 }
5581 EXPORT_SYMBOL_GPL(ata_host_alloc);
5582
5583 /**
5584  *      ata_host_alloc_pinfo - alloc host and init with port_info array
5585  *      @dev: generic device this host is associated with
5586  *      @ppi: array of ATA port_info to initialize host with
5587  *      @n_ports: number of ATA ports attached to this host
5588  *
5589  *      Allocate ATA host and initialize with info from @ppi.  If NULL
5590  *      terminated, @ppi may contain fewer entries than @n_ports.  The
5591  *      last entry will be used for the remaining ports.
5592  *
5593  *      RETURNS:
5594  *      Allocate ATA host on success, NULL on failure.
5595  *
5596  *      LOCKING:
5597  *      Inherited from calling layer (may sleep).
5598  */
5599 struct ata_host *ata_host_alloc_pinfo(struct device *dev,
5600                                       const struct ata_port_info * const * ppi,
5601                                       int n_ports)
5602 {
5603         const struct ata_port_info *pi = &ata_dummy_port_info;
5604         struct ata_host *host;
5605         int i, j;
5606
5607         host = ata_host_alloc(dev, n_ports);
5608         if (!host)
5609                 return NULL;
5610
5611         for (i = 0, j = 0; i < host->n_ports; i++) {
5612                 struct ata_port *ap = host->ports[i];
5613
5614                 if (ppi[j])
5615                         pi = ppi[j++];
5616
5617                 ap->pio_mask = pi->pio_mask;
5618                 ap->mwdma_mask = pi->mwdma_mask;
5619                 ap->udma_mask = pi->udma_mask;
5620                 ap->flags |= pi->flags;
5621                 ap->link.flags |= pi->link_flags;
5622                 ap->ops = pi->port_ops;
5623
5624                 if (!host->ops && (pi->port_ops != &ata_dummy_port_ops))
5625                         host->ops = pi->port_ops;
5626         }
5627
5628         return host;
5629 }
5630 EXPORT_SYMBOL_GPL(ata_host_alloc_pinfo);
5631
5632 static void ata_host_stop(struct device *gendev, void *res)
5633 {
5634         struct ata_host *host = dev_get_drvdata(gendev);
5635         int i;
5636
5637         WARN_ON(!(host->flags & ATA_HOST_STARTED));
5638
5639         for (i = 0; i < host->n_ports; i++) {
5640                 struct ata_port *ap = host->ports[i];
5641
5642                 if (ap->ops->port_stop)
5643                         ap->ops->port_stop(ap);
5644         }
5645
5646         if (host->ops->host_stop)
5647                 host->ops->host_stop(host);
5648 }
5649
5650 /**
5651  *      ata_finalize_port_ops - finalize ata_port_operations
5652  *      @ops: ata_port_operations to finalize
5653  *
5654  *      An ata_port_operations can inherit from another ops and that
5655  *      ops can again inherit from another.  This can go on as many
5656  *      times as necessary as long as there is no loop in the
5657  *      inheritance chain.
5658  *
5659  *      Ops tables are finalized when the host is started.  NULL or
5660  *      unspecified entries are inherited from the closet ancestor
5661  *      which has the method and the entry is populated with it.
5662  *      After finalization, the ops table directly points to all the
5663  *      methods and ->inherits is no longer necessary and cleared.
5664  *
5665  *      Using ATA_OP_NULL, inheriting ops can force a method to NULL.
5666  *
5667  *      LOCKING:
5668  *      None.
5669  */
5670 static void ata_finalize_port_ops(struct ata_port_operations *ops)
5671 {
5672         static DEFINE_SPINLOCK(lock);
5673         const struct ata_port_operations *cur;
5674         void **begin = (void **)ops;
5675         void **end = (void **)&ops->inherits;
5676         void **pp;
5677
5678         if (!ops || !ops->inherits)
5679                 return;
5680
5681         spin_lock(&lock);
5682
5683         for (cur = ops->inherits; cur; cur = cur->inherits) {
5684                 void **inherit = (void **)cur;
5685
5686                 for (pp = begin; pp < end; pp++, inherit++)
5687                         if (!*pp)
5688                                 *pp = *inherit;
5689         }
5690
5691         for (pp = begin; pp < end; pp++)
5692                 if (IS_ERR(*pp))
5693                         *pp = NULL;
5694
5695         ops->inherits = NULL;
5696
5697         spin_unlock(&lock);
5698 }
5699
5700 /**
5701  *      ata_host_start - start and freeze ports of an ATA host
5702  *      @host: ATA host to start ports for
5703  *
5704  *      Start and then freeze ports of @host.  Started status is
5705  *      recorded in host->flags, so this function can be called
5706  *      multiple times.  Ports are guaranteed to get started only
5707  *      once.  If host->ops is not initialized yet, it is set to the
5708  *      first non-dummy port ops.
5709  *
5710  *      LOCKING:
5711  *      Inherited from calling layer (may sleep).
5712  *
5713  *      RETURNS:
5714  *      0 if all ports are started successfully, -errno otherwise.
5715  */
5716 int ata_host_start(struct ata_host *host)
5717 {
5718         int have_stop = 0;
5719         void *start_dr = NULL;
5720         int i, rc;
5721
5722         if (host->flags & ATA_HOST_STARTED)
5723                 return 0;
5724
5725         ata_finalize_port_ops(host->ops);
5726
5727         for (i = 0; i < host->n_ports; i++) {
5728                 struct ata_port *ap = host->ports[i];
5729
5730                 ata_finalize_port_ops(ap->ops);
5731
5732                 if (!host->ops && !ata_port_is_dummy(ap))
5733                         host->ops = ap->ops;
5734
5735                 if (ap->ops->port_stop)
5736                         have_stop = 1;
5737         }
5738
5739         if (host->ops && host->ops->host_stop)
5740                 have_stop = 1;
5741
5742         if (have_stop) {
5743                 start_dr = devres_alloc(ata_host_stop, 0, GFP_KERNEL);
5744                 if (!start_dr)
5745                         return -ENOMEM;
5746         }
5747
5748         for (i = 0; i < host->n_ports; i++) {
5749                 struct ata_port *ap = host->ports[i];
5750
5751                 if (ap->ops->port_start) {
5752                         rc = ap->ops->port_start(ap);
5753                         if (rc) {
5754                                 if (rc != -ENODEV)
5755                                         dev_err(host->dev,
5756                                                 "failed to start port %d (errno=%d)\n",
5757                                                 i, rc);
5758                                 goto err_out;
5759                         }
5760                 }
5761                 ata_eh_freeze_port(ap);
5762         }
5763
5764         if (start_dr)
5765                 devres_add(host->dev, start_dr);
5766         host->flags |= ATA_HOST_STARTED;
5767         return 0;
5768
5769  err_out:
5770         while (--i >= 0) {
5771                 struct ata_port *ap = host->ports[i];
5772
5773                 if (ap->ops->port_stop)
5774                         ap->ops->port_stop(ap);
5775         }
5776         devres_free(start_dr);
5777         return rc;
5778 }
5779 EXPORT_SYMBOL_GPL(ata_host_start);
5780
5781 /**
5782  *      ata_host_init - Initialize a host struct for sas (ipr, libsas)
5783  *      @host:  host to initialize
5784  *      @dev:   device host is attached to
5785  *      @ops:   port_ops
5786  *
5787  */
5788 void ata_host_init(struct ata_host *host, struct device *dev,
5789                    struct ata_port_operations *ops)
5790 {
5791         spin_lock_init(&host->lock);
5792         mutex_init(&host->eh_mutex);
5793         host->n_tags = ATA_MAX_QUEUE;
5794         host->dev = dev;
5795         host->ops = ops;
5796         kref_init(&host->kref);
5797 }
5798 EXPORT_SYMBOL_GPL(ata_host_init);
5799
5800 void ata_port_probe(struct ata_port *ap)
5801 {
5802         struct ata_eh_info *ehi = &ap->link.eh_info;
5803         unsigned long flags;
5804
5805         /* kick EH for boot probing */
5806         spin_lock_irqsave(ap->lock, flags);
5807
5808         ehi->probe_mask |= ATA_ALL_DEVICES;
5809         ehi->action |= ATA_EH_RESET;
5810         ehi->flags |= ATA_EHI_NO_AUTOPSY | ATA_EHI_QUIET;
5811
5812         ap->pflags &= ~ATA_PFLAG_INITIALIZING;
5813         ap->pflags |= ATA_PFLAG_LOADING;
5814         ata_port_schedule_eh(ap);
5815
5816         spin_unlock_irqrestore(ap->lock, flags);
5817 }
5818 EXPORT_SYMBOL_GPL(ata_port_probe);
5819
5820 static void async_port_probe(void *data, async_cookie_t cookie)
5821 {
5822         struct ata_port *ap = data;
5823
5824         /*
5825          * If we're not allowed to scan this host in parallel,
5826          * we need to wait until all previous scans have completed
5827          * before going further.
5828          * Jeff Garzik says this is only within a controller, so we
5829          * don't need to wait for port 0, only for later ports.
5830          */
5831         if (!(ap->host->flags & ATA_HOST_PARALLEL_SCAN) && ap->port_no != 0)
5832                 async_synchronize_cookie(cookie);
5833
5834         ata_port_probe(ap);
5835         ata_port_wait_eh(ap);
5836
5837         /* in order to keep device order, we need to synchronize at this point */
5838         async_synchronize_cookie(cookie);
5839
5840         ata_scsi_scan_host(ap, 1);
5841 }
5842
5843 /**
5844  *      ata_host_register - register initialized ATA host
5845  *      @host: ATA host to register
5846  *      @sht: template for SCSI host
5847  *
5848  *      Register initialized ATA host.  @host is allocated using
5849  *      ata_host_alloc() and fully initialized by LLD.  This function
5850  *      starts ports, registers @host with ATA and SCSI layers and
5851  *      probe registered devices.
5852  *
5853  *      LOCKING:
5854  *      Inherited from calling layer (may sleep).
5855  *
5856  *      RETURNS:
5857  *      0 on success, -errno otherwise.
5858  */
5859 int ata_host_register(struct ata_host *host, const struct scsi_host_template *sht)
5860 {
5861         int i, rc;
5862
5863         host->n_tags = clamp(sht->can_queue, 1, ATA_MAX_QUEUE);
5864
5865         /* host must have been started */
5866         if (!(host->flags & ATA_HOST_STARTED)) {
5867                 dev_err(host->dev, "BUG: trying to register unstarted host\n");
5868                 WARN_ON(1);
5869                 return -EINVAL;
5870         }
5871
5872         /* Create associated sysfs transport objects  */
5873         for (i = 0; i < host->n_ports; i++) {
5874                 rc = ata_tport_add(host->dev,host->ports[i]);
5875                 if (rc) {
5876                         goto err_tadd;
5877                 }
5878         }
5879
5880         rc = ata_scsi_add_hosts(host, sht);
5881         if (rc)
5882                 goto err_tadd;
5883
5884         /* set cable, sata_spd_limit and report */
5885         for (i = 0; i < host->n_ports; i++) {
5886                 struct ata_port *ap = host->ports[i];
5887                 unsigned int xfer_mask;
5888
5889                 /* set SATA cable type if still unset */
5890                 if (ap->cbl == ATA_CBL_NONE && (ap->flags & ATA_FLAG_SATA))
5891                         ap->cbl = ATA_CBL_SATA;
5892
5893                 /* init sata_spd_limit to the current value */
5894                 sata_link_init_spd(&ap->link);
5895                 if (ap->slave_link)
5896                         sata_link_init_spd(ap->slave_link);
5897
5898                 /* print per-port info to dmesg */
5899                 xfer_mask = ata_pack_xfermask(ap->pio_mask, ap->mwdma_mask,
5900                                               ap->udma_mask);
5901
5902                 if (!ata_port_is_dummy(ap)) {
5903                         ata_port_info(ap, "%cATA max %s %s\n",
5904                                       (ap->flags & ATA_FLAG_SATA) ? 'S' : 'P',
5905                                       ata_mode_string(xfer_mask),
5906                                       ap->link.eh_info.desc);
5907                         ata_ehi_clear_desc(&ap->link.eh_info);
5908                 } else
5909                         ata_port_info(ap, "DUMMY\n");
5910         }
5911
5912         /* perform each probe asynchronously */
5913         for (i = 0; i < host->n_ports; i++) {
5914                 struct ata_port *ap = host->ports[i];
5915                 ap->cookie = async_schedule(async_port_probe, ap);
5916         }
5917
5918         return 0;
5919
5920  err_tadd:
5921         while (--i >= 0) {
5922                 ata_tport_delete(host->ports[i]);
5923         }
5924         return rc;
5925
5926 }
5927 EXPORT_SYMBOL_GPL(ata_host_register);
5928
5929 /**
5930  *      ata_host_activate - start host, request IRQ and register it
5931  *      @host: target ATA host
5932  *      @irq: IRQ to request
5933  *      @irq_handler: irq_handler used when requesting IRQ
5934  *      @irq_flags: irq_flags used when requesting IRQ
5935  *      @sht: scsi_host_template to use when registering the host
5936  *
5937  *      After allocating an ATA host and initializing it, most libata
5938  *      LLDs perform three steps to activate the host - start host,
5939  *      request IRQ and register it.  This helper takes necessary
5940  *      arguments and performs the three steps in one go.
5941  *
5942  *      An invalid IRQ skips the IRQ registration and expects the host to
5943  *      have set polling mode on the port. In this case, @irq_handler
5944  *      should be NULL.
5945  *
5946  *      LOCKING:
5947  *      Inherited from calling layer (may sleep).
5948  *
5949  *      RETURNS:
5950  *      0 on success, -errno otherwise.
5951  */
5952 int ata_host_activate(struct ata_host *host, int irq,
5953                       irq_handler_t irq_handler, unsigned long irq_flags,
5954                       const struct scsi_host_template *sht)
5955 {
5956         int i, rc;
5957         char *irq_desc;
5958
5959         rc = ata_host_start(host);
5960         if (rc)
5961                 return rc;
5962
5963         /* Special case for polling mode */
5964         if (!irq) {
5965                 WARN_ON(irq_handler);
5966                 return ata_host_register(host, sht);
5967         }
5968
5969         irq_desc = devm_kasprintf(host->dev, GFP_KERNEL, "%s[%s]",
5970                                   dev_driver_string(host->dev),
5971                                   dev_name(host->dev));
5972         if (!irq_desc)
5973                 return -ENOMEM;
5974
5975         rc = devm_request_irq(host->dev, irq, irq_handler, irq_flags,
5976                               irq_desc, host);
5977         if (rc)
5978                 return rc;
5979
5980         for (i = 0; i < host->n_ports; i++)
5981                 ata_port_desc_misc(host->ports[i], irq);
5982
5983         rc = ata_host_register(host, sht);
5984         /* if failed, just free the IRQ and leave ports alone */
5985         if (rc)
5986                 devm_free_irq(host->dev, irq, host);
5987
5988         return rc;
5989 }
5990 EXPORT_SYMBOL_GPL(ata_host_activate);
5991
5992 /**
5993  *      ata_dev_free_resources - Free a device resources
5994  *      @dev: Target ATA device
5995  *
5996  *      Free resources allocated to support a device features.
5997  *
5998  *      LOCKING:
5999  *      Kernel thread context (may sleep).
6000  */
6001 void ata_dev_free_resources(struct ata_device *dev)
6002 {
6003         if (zpodd_dev_enabled(dev))
6004                 zpodd_exit(dev);
6005
6006         ata_dev_cleanup_cdl_resources(dev);
6007 }
6008
6009 /**
6010  *      ata_port_detach - Detach ATA port in preparation of device removal
6011  *      @ap: ATA port to be detached
6012  *
6013  *      Detach all ATA devices and the associated SCSI devices of @ap;
6014  *      then, remove the associated SCSI host.  @ap is guaranteed to
6015  *      be quiescent on return from this function.
6016  *
6017  *      LOCKING:
6018  *      Kernel thread context (may sleep).
6019  */
6020 static void ata_port_detach(struct ata_port *ap)
6021 {
6022         unsigned long flags;
6023         struct ata_link *link;
6024         struct ata_device *dev;
6025
6026         /* Ensure ata_port probe has completed */
6027         async_synchronize_cookie(ap->cookie + 1);
6028
6029         /* Wait for any ongoing EH */
6030         ata_port_wait_eh(ap);
6031
6032         mutex_lock(&ap->scsi_scan_mutex);
6033         spin_lock_irqsave(ap->lock, flags);
6034
6035         /* Remove scsi devices */
6036         ata_for_each_link(link, ap, HOST_FIRST) {
6037                 ata_for_each_dev(dev, link, ALL) {
6038                         if (dev->sdev) {
6039                                 spin_unlock_irqrestore(ap->lock, flags);
6040                                 scsi_remove_device(dev->sdev);
6041                                 spin_lock_irqsave(ap->lock, flags);
6042                                 dev->sdev = NULL;
6043                         }
6044                 }
6045         }
6046
6047         /* Tell EH to disable all devices */
6048         ap->pflags |= ATA_PFLAG_UNLOADING;
6049         ata_port_schedule_eh(ap);
6050
6051         spin_unlock_irqrestore(ap->lock, flags);
6052         mutex_unlock(&ap->scsi_scan_mutex);
6053
6054         /* wait till EH commits suicide */
6055         ata_port_wait_eh(ap);
6056
6057         /* it better be dead now */
6058         WARN_ON(!(ap->pflags & ATA_PFLAG_UNLOADED));
6059
6060         cancel_delayed_work_sync(&ap->hotplug_task);
6061         cancel_delayed_work_sync(&ap->scsi_rescan_task);
6062
6063         /* Delete port multiplier link transport devices */
6064         if (ap->pmp_link) {
6065                 int i;
6066
6067                 for (i = 0; i < SATA_PMP_MAX_PORTS; i++)
6068                         ata_tlink_delete(&ap->pmp_link[i]);
6069         }
6070
6071         /* Remove the associated SCSI host */
6072         scsi_remove_host(ap->scsi_host);
6073         ata_tport_delete(ap);
6074 }
6075
6076 /**
6077  *      ata_host_detach - Detach all ports of an ATA host
6078  *      @host: Host to detach
6079  *
6080  *      Detach all ports of @host.
6081  *
6082  *      LOCKING:
6083  *      Kernel thread context (may sleep).
6084  */
6085 void ata_host_detach(struct ata_host *host)
6086 {
6087         int i;
6088
6089         for (i = 0; i < host->n_ports; i++)
6090                 ata_port_detach(host->ports[i]);
6091
6092         /* the host is dead now, dissociate ACPI */
6093         ata_acpi_dissociate(host);
6094 }
6095 EXPORT_SYMBOL_GPL(ata_host_detach);
6096
6097 #ifdef CONFIG_PCI
6098
6099 /**
6100  *      ata_pci_remove_one - PCI layer callback for device removal
6101  *      @pdev: PCI device that was removed
6102  *
6103  *      PCI layer indicates to libata via this hook that hot-unplug or
6104  *      module unload event has occurred.  Detach all ports.  Resource
6105  *      release is handled via devres.
6106  *
6107  *      LOCKING:
6108  *      Inherited from PCI layer (may sleep).
6109  */
6110 void ata_pci_remove_one(struct pci_dev *pdev)
6111 {
6112         struct ata_host *host = pci_get_drvdata(pdev);
6113
6114         ata_host_detach(host);
6115 }
6116 EXPORT_SYMBOL_GPL(ata_pci_remove_one);
6117
6118 void ata_pci_shutdown_one(struct pci_dev *pdev)
6119 {
6120         struct ata_host *host = pci_get_drvdata(pdev);
6121         int i;
6122
6123         for (i = 0; i < host->n_ports; i++) {
6124                 struct ata_port *ap = host->ports[i];
6125
6126                 ap->pflags |= ATA_PFLAG_FROZEN;
6127
6128                 /* Disable port interrupts */
6129                 if (ap->ops->freeze)
6130                         ap->ops->freeze(ap);
6131
6132                 /* Stop the port DMA engines */
6133                 if (ap->ops->port_stop)
6134                         ap->ops->port_stop(ap);
6135         }
6136 }
6137 EXPORT_SYMBOL_GPL(ata_pci_shutdown_one);
6138
6139 /* move to PCI subsystem */
6140 int pci_test_config_bits(struct pci_dev *pdev, const struct pci_bits *bits)
6141 {
6142         unsigned long tmp = 0;
6143
6144         switch (bits->width) {
6145         case 1: {
6146                 u8 tmp8 = 0;
6147                 pci_read_config_byte(pdev, bits->reg, &tmp8);
6148                 tmp = tmp8;
6149                 break;
6150         }
6151         case 2: {
6152                 u16 tmp16 = 0;
6153                 pci_read_config_word(pdev, bits->reg, &tmp16);
6154                 tmp = tmp16;
6155                 break;
6156         }
6157         case 4: {
6158                 u32 tmp32 = 0;
6159                 pci_read_config_dword(pdev, bits->reg, &tmp32);
6160                 tmp = tmp32;
6161                 break;
6162         }
6163
6164         default:
6165                 return -EINVAL;
6166         }
6167
6168         tmp &= bits->mask;
6169
6170         return (tmp == bits->val) ? 1 : 0;
6171 }
6172 EXPORT_SYMBOL_GPL(pci_test_config_bits);
6173
6174 #ifdef CONFIG_PM
6175 void ata_pci_device_do_suspend(struct pci_dev *pdev, pm_message_t mesg)
6176 {
6177         pci_save_state(pdev);
6178         pci_disable_device(pdev);
6179
6180         if (mesg.event & PM_EVENT_SLEEP)
6181                 pci_set_power_state(pdev, PCI_D3hot);
6182 }
6183 EXPORT_SYMBOL_GPL(ata_pci_device_do_suspend);
6184
6185 int ata_pci_device_do_resume(struct pci_dev *pdev)
6186 {
6187         int rc;
6188
6189         pci_set_power_state(pdev, PCI_D0);
6190         pci_restore_state(pdev);
6191
6192         rc = pcim_enable_device(pdev);
6193         if (rc) {
6194                 dev_err(&pdev->dev,
6195                         "failed to enable device after resume (%d)\n", rc);
6196                 return rc;
6197         }
6198
6199         pci_set_master(pdev);
6200         return 0;
6201 }
6202 EXPORT_SYMBOL_GPL(ata_pci_device_do_resume);
6203
6204 int ata_pci_device_suspend(struct pci_dev *pdev, pm_message_t mesg)
6205 {
6206         struct ata_host *host = pci_get_drvdata(pdev);
6207
6208         ata_host_suspend(host, mesg);
6209
6210         ata_pci_device_do_suspend(pdev, mesg);
6211
6212         return 0;
6213 }
6214 EXPORT_SYMBOL_GPL(ata_pci_device_suspend);
6215
6216 int ata_pci_device_resume(struct pci_dev *pdev)
6217 {
6218         struct ata_host *host = pci_get_drvdata(pdev);
6219         int rc;
6220
6221         rc = ata_pci_device_do_resume(pdev);
6222         if (rc == 0)
6223                 ata_host_resume(host);
6224         return rc;
6225 }
6226 EXPORT_SYMBOL_GPL(ata_pci_device_resume);
6227 #endif /* CONFIG_PM */
6228 #endif /* CONFIG_PCI */
6229
6230 /**
6231  *      ata_platform_remove_one - Platform layer callback for device removal
6232  *      @pdev: Platform device that was removed
6233  *
6234  *      Platform layer indicates to libata via this hook that hot-unplug or
6235  *      module unload event has occurred.  Detach all ports.  Resource
6236  *      release is handled via devres.
6237  *
6238  *      LOCKING:
6239  *      Inherited from platform layer (may sleep).
6240  */
6241 void ata_platform_remove_one(struct platform_device *pdev)
6242 {
6243         struct ata_host *host = platform_get_drvdata(pdev);
6244
6245         ata_host_detach(host);
6246 }
6247 EXPORT_SYMBOL_GPL(ata_platform_remove_one);
6248
6249 #ifdef CONFIG_ATA_FORCE
6250
6251 #define force_cbl(name, flag)                           \
6252         { #name,        .cbl            = (flag) }
6253
6254 #define force_spd_limit(spd, val)                       \
6255         { #spd, .spd_limit              = (val) }
6256
6257 #define force_xfer(mode, shift)                         \
6258         { #mode,        .xfer_mask      = (1UL << (shift)) }
6259
6260 #define force_lflag_on(name, flags)                     \
6261         { #name,        .lflags_on      = (flags) }
6262
6263 #define force_lflag_onoff(name, flags)                  \
6264         { "no" #name,   .lflags_on      = (flags) },    \
6265         { #name,        .lflags_off     = (flags) }
6266
6267 #define force_quirk_on(name, flag)                      \
6268         { #name,        .quirk_on       = (flag) }
6269
6270 #define force_quirk_onoff(name, flag)                   \
6271         { "no" #name,   .quirk_on       = (flag) },     \
6272         { #name,        .quirk_off      = (flag) }
6273
6274 static const struct ata_force_param force_tbl[] __initconst = {
6275         force_cbl(40c,                  ATA_CBL_PATA40),
6276         force_cbl(80c,                  ATA_CBL_PATA80),
6277         force_cbl(short40c,             ATA_CBL_PATA40_SHORT),
6278         force_cbl(unk,                  ATA_CBL_PATA_UNK),
6279         force_cbl(ign,                  ATA_CBL_PATA_IGN),
6280         force_cbl(sata,                 ATA_CBL_SATA),
6281
6282         force_spd_limit(1.5Gbps,        1),
6283         force_spd_limit(3.0Gbps,        2),
6284
6285         force_xfer(pio0,                ATA_SHIFT_PIO + 0),
6286         force_xfer(pio1,                ATA_SHIFT_PIO + 1),
6287         force_xfer(pio2,                ATA_SHIFT_PIO + 2),
6288         force_xfer(pio3,                ATA_SHIFT_PIO + 3),
6289         force_xfer(pio4,                ATA_SHIFT_PIO + 4),
6290         force_xfer(pio5,                ATA_SHIFT_PIO + 5),
6291         force_xfer(pio6,                ATA_SHIFT_PIO + 6),
6292         force_xfer(mwdma0,              ATA_SHIFT_MWDMA + 0),
6293         force_xfer(mwdma1,              ATA_SHIFT_MWDMA + 1),
6294         force_xfer(mwdma2,              ATA_SHIFT_MWDMA + 2),
6295         force_xfer(mwdma3,              ATA_SHIFT_MWDMA + 3),
6296         force_xfer(mwdma4,              ATA_SHIFT_MWDMA + 4),
6297         force_xfer(udma0,               ATA_SHIFT_UDMA + 0),
6298         force_xfer(udma16,              ATA_SHIFT_UDMA + 0),
6299         force_xfer(udma/16,             ATA_SHIFT_UDMA + 0),
6300         force_xfer(udma1,               ATA_SHIFT_UDMA + 1),
6301         force_xfer(udma25,              ATA_SHIFT_UDMA + 1),
6302         force_xfer(udma/25,             ATA_SHIFT_UDMA + 1),
6303         force_xfer(udma2,               ATA_SHIFT_UDMA + 2),
6304         force_xfer(udma33,              ATA_SHIFT_UDMA + 2),
6305         force_xfer(udma/33,             ATA_SHIFT_UDMA + 2),
6306         force_xfer(udma3,               ATA_SHIFT_UDMA + 3),
6307         force_xfer(udma44,              ATA_SHIFT_UDMA + 3),
6308         force_xfer(udma/44,             ATA_SHIFT_UDMA + 3),
6309         force_xfer(udma4,               ATA_SHIFT_UDMA + 4),
6310         force_xfer(udma66,              ATA_SHIFT_UDMA + 4),
6311         force_xfer(udma/66,             ATA_SHIFT_UDMA + 4),
6312         force_xfer(udma5,               ATA_SHIFT_UDMA + 5),
6313         force_xfer(udma100,             ATA_SHIFT_UDMA + 5),
6314         force_xfer(udma/100,            ATA_SHIFT_UDMA + 5),
6315         force_xfer(udma6,               ATA_SHIFT_UDMA + 6),
6316         force_xfer(udma133,             ATA_SHIFT_UDMA + 6),
6317         force_xfer(udma/133,            ATA_SHIFT_UDMA + 6),
6318         force_xfer(udma7,               ATA_SHIFT_UDMA + 7),
6319
6320         force_lflag_on(nohrst,          ATA_LFLAG_NO_HRST),
6321         force_lflag_on(nosrst,          ATA_LFLAG_NO_SRST),
6322         force_lflag_on(norst,           ATA_LFLAG_NO_HRST | ATA_LFLAG_NO_SRST),
6323         force_lflag_on(rstonce,         ATA_LFLAG_RST_ONCE),
6324         force_lflag_onoff(dbdelay,      ATA_LFLAG_NO_DEBOUNCE_DELAY),
6325
6326         force_quirk_onoff(ncq,          ATA_QUIRK_NONCQ),
6327         force_quirk_onoff(ncqtrim,      ATA_QUIRK_NO_NCQ_TRIM),
6328         force_quirk_onoff(ncqati,       ATA_QUIRK_NO_NCQ_ON_ATI),
6329
6330         force_quirk_onoff(trim,         ATA_QUIRK_NOTRIM),
6331         force_quirk_on(trim_zero,       ATA_QUIRK_ZERO_AFTER_TRIM),
6332         force_quirk_on(max_trim_128m,   ATA_QUIRK_MAX_TRIM_128M),
6333
6334         force_quirk_onoff(dma,          ATA_QUIRK_NODMA),
6335         force_quirk_on(atapi_dmadir,    ATA_QUIRK_ATAPI_DMADIR),
6336         force_quirk_on(atapi_mod16_dma, ATA_QUIRK_ATAPI_MOD16_DMA),
6337
6338         force_quirk_onoff(dmalog,       ATA_QUIRK_NO_DMA_LOG),
6339         force_quirk_onoff(iddevlog,     ATA_QUIRK_NO_ID_DEV_LOG),
6340         force_quirk_onoff(logdir,       ATA_QUIRK_NO_LOG_DIR),
6341
6342         force_quirk_on(max_sec_128,     ATA_QUIRK_MAX_SEC_128),
6343         force_quirk_on(max_sec_1024,    ATA_QUIRK_MAX_SEC_1024),
6344         force_quirk_on(max_sec_lba48,   ATA_QUIRK_MAX_SEC_LBA48),
6345
6346         force_quirk_onoff(lpm,          ATA_QUIRK_NOLPM),
6347         force_quirk_onoff(setxfer,      ATA_QUIRK_NOSETXFER),
6348         force_quirk_on(dump_id,         ATA_QUIRK_DUMP_ID),
6349         force_quirk_onoff(fua,          ATA_QUIRK_NO_FUA),
6350
6351         force_quirk_on(disable,         ATA_QUIRK_DISABLE),
6352 };
6353
6354 static int __init ata_parse_force_one(char **cur,
6355                                       struct ata_force_ent *force_ent,
6356                                       const char **reason)
6357 {
6358         char *start = *cur, *p = *cur;
6359         char *id, *val, *endp;
6360         const struct ata_force_param *match_fp = NULL;
6361         int nr_matches = 0, i;
6362
6363         /* find where this param ends and update *cur */
6364         while (*p != '\0' && *p != ',')
6365                 p++;
6366
6367         if (*p == '\0')
6368                 *cur = p;
6369         else
6370                 *cur = p + 1;
6371
6372         *p = '\0';
6373
6374         /* parse */
6375         p = strchr(start, ':');
6376         if (!p) {
6377                 val = strstrip(start);
6378                 goto parse_val;
6379         }
6380         *p = '\0';
6381
6382         id = strstrip(start);
6383         val = strstrip(p + 1);
6384
6385         /* parse id */
6386         p = strchr(id, '.');
6387         if (p) {
6388                 *p++ = '\0';
6389                 force_ent->device = simple_strtoul(p, &endp, 10);
6390                 if (p == endp || *endp != '\0') {
6391                         *reason = "invalid device";
6392                         return -EINVAL;
6393                 }
6394         }
6395
6396         force_ent->port = simple_strtoul(id, &endp, 10);
6397         if (id == endp || *endp != '\0') {
6398                 *reason = "invalid port/link";
6399                 return -EINVAL;
6400         }
6401
6402  parse_val:
6403         /* parse val, allow shortcuts so that both 1.5 and 1.5Gbps work */
6404         for (i = 0; i < ARRAY_SIZE(force_tbl); i++) {
6405                 const struct ata_force_param *fp = &force_tbl[i];
6406
6407                 if (strncasecmp(val, fp->name, strlen(val)))
6408                         continue;
6409
6410                 nr_matches++;
6411                 match_fp = fp;
6412
6413                 if (strcasecmp(val, fp->name) == 0) {
6414                         nr_matches = 1;
6415                         break;
6416                 }
6417         }
6418
6419         if (!nr_matches) {
6420                 *reason = "unknown value";
6421                 return -EINVAL;
6422         }
6423         if (nr_matches > 1) {
6424                 *reason = "ambiguous value";
6425                 return -EINVAL;
6426         }
6427
6428         force_ent->param = *match_fp;
6429
6430         return 0;
6431 }
6432
6433 static void __init ata_parse_force_param(void)
6434 {
6435         int idx = 0, size = 1;
6436         int last_port = -1, last_device = -1;
6437         char *p, *cur, *next;
6438
6439         /* Calculate maximum number of params and allocate ata_force_tbl */
6440         for (p = ata_force_param_buf; *p; p++)
6441                 if (*p == ',')
6442                         size++;
6443
6444         ata_force_tbl = kcalloc(size, sizeof(ata_force_tbl[0]), GFP_KERNEL);
6445         if (!ata_force_tbl) {
6446                 printk(KERN_WARNING "ata: failed to extend force table, "
6447                        "libata.force ignored\n");
6448                 return;
6449         }
6450
6451         /* parse and populate the table */
6452         for (cur = ata_force_param_buf; *cur != '\0'; cur = next) {
6453                 const char *reason = "";
6454                 struct ata_force_ent te = { .port = -1, .device = -1 };
6455
6456                 next = cur;
6457                 if (ata_parse_force_one(&next, &te, &reason)) {
6458                         printk(KERN_WARNING "ata: failed to parse force "
6459                                "parameter \"%s\" (%s)\n",
6460                                cur, reason);
6461                         continue;
6462                 }
6463
6464                 if (te.port == -1) {
6465                         te.port = last_port;
6466                         te.device = last_device;
6467                 }
6468
6469                 ata_force_tbl[idx++] = te;
6470
6471                 last_port = te.port;
6472                 last_device = te.device;
6473         }
6474
6475         ata_force_tbl_size = idx;
6476 }
6477
6478 static void ata_free_force_param(void)
6479 {
6480         kfree(ata_force_tbl);
6481 }
6482 #else
6483 static inline void ata_parse_force_param(void) { }
6484 static inline void ata_free_force_param(void) { }
6485 #endif
6486
6487 static int __init ata_init(void)
6488 {
6489         int rc;
6490
6491         ata_parse_force_param();
6492
6493         rc = ata_sff_init();
6494         if (rc) {
6495                 ata_free_force_param();
6496                 return rc;
6497         }
6498
6499         libata_transport_init();
6500         ata_scsi_transport_template = ata_attach_transport();
6501         if (!ata_scsi_transport_template) {
6502                 ata_sff_exit();
6503                 rc = -ENOMEM;
6504                 goto err_out;
6505         }
6506
6507         printk(KERN_DEBUG "libata version " DRV_VERSION " loaded.\n");
6508         return 0;
6509
6510 err_out:
6511         return rc;
6512 }
6513
6514 static void __exit ata_exit(void)
6515 {
6516         ata_release_transport(ata_scsi_transport_template);
6517         libata_transport_exit();
6518         ata_sff_exit();
6519         ata_free_force_param();
6520 }
6521
6522 subsys_initcall(ata_init);
6523 module_exit(ata_exit);
6524
6525 static DEFINE_RATELIMIT_STATE(ratelimit, HZ / 5, 1);
6526
6527 int ata_ratelimit(void)
6528 {
6529         return __ratelimit(&ratelimit);
6530 }
6531 EXPORT_SYMBOL_GPL(ata_ratelimit);
6532
6533 /**
6534  *      ata_msleep - ATA EH owner aware msleep
6535  *      @ap: ATA port to attribute the sleep to
6536  *      @msecs: duration to sleep in milliseconds
6537  *
6538  *      Sleeps @msecs.  If the current task is owner of @ap's EH, the
6539  *      ownership is released before going to sleep and reacquired
6540  *      after the sleep is complete.  IOW, other ports sharing the
6541  *      @ap->host will be allowed to own the EH while this task is
6542  *      sleeping.
6543  *
6544  *      LOCKING:
6545  *      Might sleep.
6546  */
6547 void ata_msleep(struct ata_port *ap, unsigned int msecs)
6548 {
6549         bool owns_eh = ap && ap->host->eh_owner == current;
6550
6551         if (owns_eh)
6552                 ata_eh_release(ap);
6553
6554         if (msecs < 20) {
6555                 unsigned long usecs = msecs * USEC_PER_MSEC;
6556                 usleep_range(usecs, usecs + 50);
6557         } else {
6558                 msleep(msecs);
6559         }
6560
6561         if (owns_eh)
6562                 ata_eh_acquire(ap);
6563 }
6564 EXPORT_SYMBOL_GPL(ata_msleep);
6565
6566 /**
6567  *      ata_wait_register - wait until register value changes
6568  *      @ap: ATA port to wait register for, can be NULL
6569  *      @reg: IO-mapped register
6570  *      @mask: Mask to apply to read register value
6571  *      @val: Wait condition
6572  *      @interval: polling interval in milliseconds
6573  *      @timeout: timeout in milliseconds
6574  *
6575  *      Waiting for some bits of register to change is a common
6576  *      operation for ATA controllers.  This function reads 32bit LE
6577  *      IO-mapped register @reg and tests for the following condition.
6578  *
6579  *      (*@reg & mask) != val
6580  *
6581  *      If the condition is met, it returns; otherwise, the process is
6582  *      repeated after @interval_msec until timeout.
6583  *
6584  *      LOCKING:
6585  *      Kernel thread context (may sleep)
6586  *
6587  *      RETURNS:
6588  *      The final register value.
6589  */
6590 u32 ata_wait_register(struct ata_port *ap, void __iomem *reg, u32 mask, u32 val,
6591                       unsigned int interval, unsigned int timeout)
6592 {
6593         unsigned long deadline;
6594         u32 tmp;
6595
6596         tmp = ioread32(reg);
6597
6598         /* Calculate timeout _after_ the first read to make sure
6599          * preceding writes reach the controller before starting to
6600          * eat away the timeout.
6601          */
6602         deadline = ata_deadline(jiffies, timeout);
6603
6604         while ((tmp & mask) == val && time_before(jiffies, deadline)) {
6605                 ata_msleep(ap, interval);
6606                 tmp = ioread32(reg);
6607         }
6608
6609         return tmp;
6610 }
6611 EXPORT_SYMBOL_GPL(ata_wait_register);
6612
6613 /*
6614  * Dummy port_ops
6615  */
6616 static unsigned int ata_dummy_qc_issue(struct ata_queued_cmd *qc)
6617 {
6618         return AC_ERR_SYSTEM;
6619 }
6620
6621 static void ata_dummy_error_handler(struct ata_port *ap)
6622 {
6623         /* truly dummy */
6624 }
6625
6626 struct ata_port_operations ata_dummy_port_ops = {
6627         .qc_issue               = ata_dummy_qc_issue,
6628         .error_handler          = ata_dummy_error_handler,
6629         .sched_eh               = ata_std_sched_eh,
6630         .end_eh                 = ata_std_end_eh,
6631 };
6632 EXPORT_SYMBOL_GPL(ata_dummy_port_ops);
6633
6634 const struct ata_port_info ata_dummy_port_info = {
6635         .port_ops               = &ata_dummy_port_ops,
6636 };
6637 EXPORT_SYMBOL_GPL(ata_dummy_port_info);
6638
6639 void ata_print_version(const struct device *dev, const char *version)
6640 {
6641         dev_printk(KERN_DEBUG, dev, "version %s\n", version);
6642 }
6643 EXPORT_SYMBOL(ata_print_version);
6644
6645 EXPORT_TRACEPOINT_SYMBOL_GPL(ata_tf_load);
6646 EXPORT_TRACEPOINT_SYMBOL_GPL(ata_exec_command);
6647 EXPORT_TRACEPOINT_SYMBOL_GPL(ata_bmdma_setup);
6648 EXPORT_TRACEPOINT_SYMBOL_GPL(ata_bmdma_start);
6649 EXPORT_TRACEPOINT_SYMBOL_GPL(ata_bmdma_status);
This page took 0.424502 seconds and 4 git commands to generate.