Merge tag 'scsi-misc' of git://git.kernel.org/pub/scm/linux/kernel/git/jejb/scsi
[cascardo/linux.git] / drivers / staging / rts5208 / rtsx.c
1 /* Driver for Realtek PCI-Express card reader
2  *
3  * Copyright(c) 2009-2013 Realtek Semiconductor Corp. All rights reserved.
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License as published by the
7  * Free Software Foundation; either version 2, or (at your option) any
8  * later version.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License along
16  * with this program; if not, see <http://www.gnu.org/licenses/>.
17  *
18  * Author:
19  *   Wei WANG (wei_wang@realsil.com.cn)
20  *   Micky Ching (micky_ching@realsil.com.cn)
21  */
22
23 #include <linux/blkdev.h>
24 #include <linux/kthread.h>
25 #include <linux/sched.h>
26 #include <linux/workqueue.h>
27
28 #include "rtsx.h"
29 #include "rtsx_chip.h"
30 #include "rtsx_transport.h"
31 #include "rtsx_scsi.h"
32 #include "rtsx_card.h"
33 #include "general.h"
34
35 #include "ms.h"
36 #include "sd.h"
37 #include "xd.h"
38
39 MODULE_DESCRIPTION("Realtek PCI-Express card reader rts5208/rts5288 driver");
40 MODULE_LICENSE("GPL");
41
42 static unsigned int delay_use = 1;
43 module_param(delay_use, uint, S_IRUGO | S_IWUSR);
44 MODULE_PARM_DESC(delay_use, "seconds to delay before using a new device");
45
46 static int ss_en;
47 module_param(ss_en, int, S_IRUGO | S_IWUSR);
48 MODULE_PARM_DESC(ss_en, "enable selective suspend");
49
50 static int ss_interval = 50;
51 module_param(ss_interval, int, S_IRUGO | S_IWUSR);
52 MODULE_PARM_DESC(ss_interval, "Interval to enter ss state in seconds");
53
54 static int auto_delink_en;
55 module_param(auto_delink_en, int, S_IRUGO | S_IWUSR);
56 MODULE_PARM_DESC(auto_delink_en, "enable auto delink");
57
58 static unsigned char aspm_l0s_l1_en;
59 module_param(aspm_l0s_l1_en, byte, S_IRUGO | S_IWUSR);
60 MODULE_PARM_DESC(aspm_l0s_l1_en, "enable device aspm");
61
62 static int msi_en;
63 module_param(msi_en, int, S_IRUGO | S_IWUSR);
64 MODULE_PARM_DESC(msi_en, "enable msi");
65
66 static irqreturn_t rtsx_interrupt(int irq, void *dev_id);
67
68 /***********************************************************************
69  * Host functions
70  ***********************************************************************/
71
72 static const char *host_info(struct Scsi_Host *host)
73 {
74         return "SCSI emulation for PCI-Express Mass Storage devices";
75 }
76
77 static int slave_alloc(struct scsi_device *sdev)
78 {
79         /*
80          * Set the INQUIRY transfer length to 36.  We don't use any of
81          * the extra data and many devices choke if asked for more or
82          * less than 36 bytes.
83          */
84         sdev->inquiry_len = 36;
85         return 0;
86 }
87
88 static int slave_configure(struct scsi_device *sdev)
89 {
90         /* Scatter-gather buffers (all but the last) must have a length
91          * divisible by the bulk maxpacket size.  Otherwise a data packet
92          * would end up being short, causing a premature end to the data
93          * transfer.  Since high-speed bulk pipes have a maxpacket size
94          * of 512, we'll use that as the scsi device queue's DMA alignment
95          * mask.  Guaranteeing proper alignment of the first buffer will
96          * have the desired effect because, except at the beginning and
97          * the end, scatter-gather buffers follow page boundaries. */
98         blk_queue_dma_alignment(sdev->request_queue, (512 - 1));
99
100         /* Set the SCSI level to at least 2.  We'll leave it at 3 if that's
101          * what is originally reported.  We need this to avoid confusing
102          * the SCSI layer with devices that report 0 or 1, but need 10-byte
103          * commands (ala ATAPI devices behind certain bridges, or devices
104          * which simply have broken INQUIRY data).
105          *
106          * NOTE: This means /dev/sg programs (ala cdrecord) will get the
107          * actual information.  This seems to be the preference for
108          * programs like that.
109          *
110          * NOTE: This also means that /proc/scsi/scsi and sysfs may report
111          * the actual value or the modified one, depending on where the
112          * data comes from.
113          */
114         if (sdev->scsi_level < SCSI_2)
115                 sdev->scsi_level = sdev->sdev_target->scsi_level = SCSI_2;
116
117         return 0;
118 }
119
120
121 /***********************************************************************
122  * /proc/scsi/ functions
123  ***********************************************************************/
124
125 /* we use this macro to help us write into the buffer */
126 #undef SPRINTF
127 #define SPRINTF(args...) \
128         do { if (pos < buffer+length) pos += sprintf(pos, ## args); } while (0)
129
130 /* queue a command */
131 /* This is always called with scsi_lock(host) held */
132 static int queuecommand_lck(struct scsi_cmnd *srb,
133                         void (*done)(struct scsi_cmnd *))
134 {
135         struct rtsx_dev *dev = host_to_rtsx(srb->device->host);
136         struct rtsx_chip *chip = dev->chip;
137
138         /* check for state-transition errors */
139         if (chip->srb != NULL) {
140                 dev_err(&dev->pci->dev, "Error in %s: chip->srb = %p\n",
141                         __func__, chip->srb);
142                 return SCSI_MLQUEUE_HOST_BUSY;
143         }
144
145         /* fail the command if we are disconnecting */
146         if (rtsx_chk_stat(chip, RTSX_STAT_DISCONNECT)) {
147                 dev_info(&dev->pci->dev, "Fail command during disconnect\n");
148                 srb->result = DID_NO_CONNECT << 16;
149                 done(srb);
150                 return 0;
151         }
152
153         /* enqueue the command and wake up the control thread */
154         srb->scsi_done = done;
155         chip->srb = srb;
156         complete(&dev->cmnd_ready);
157
158         return 0;
159 }
160
161 static DEF_SCSI_QCMD(queuecommand)
162
163 /***********************************************************************
164  * Error handling functions
165  ***********************************************************************/
166
167 /* Command timeout and abort */
168 static int command_abort(struct scsi_cmnd *srb)
169 {
170         struct Scsi_Host *host = srb->device->host;
171         struct rtsx_dev *dev = host_to_rtsx(host);
172         struct rtsx_chip *chip = dev->chip;
173
174         dev_info(&dev->pci->dev, "%s called\n", __func__);
175
176         scsi_lock(host);
177
178         /* Is this command still active? */
179         if (chip->srb != srb) {
180                 scsi_unlock(host);
181                 dev_info(&dev->pci->dev, "-- nothing to abort\n");
182                 return FAILED;
183         }
184
185         rtsx_set_stat(chip, RTSX_STAT_ABORT);
186
187         scsi_unlock(host);
188
189         /* Wait for the aborted command to finish */
190         wait_for_completion(&dev->notify);
191
192         return SUCCESS;
193 }
194
195 /* This invokes the transport reset mechanism to reset the state of the
196  * device */
197 static int device_reset(struct scsi_cmnd *srb)
198 {
199         int result = 0;
200         struct rtsx_dev *dev = host_to_rtsx(srb->device->host);
201
202         dev_info(&dev->pci->dev, "%s called\n", __func__);
203
204         return result < 0 ? FAILED : SUCCESS;
205 }
206
207 /* Simulate a SCSI bus reset by resetting the device's USB port. */
208 static int bus_reset(struct scsi_cmnd *srb)
209 {
210         int result = 0;
211         struct rtsx_dev *dev = host_to_rtsx(srb->device->host);
212
213         dev_info(&dev->pci->dev, "%s called\n", __func__);
214
215         return result < 0 ? FAILED : SUCCESS;
216 }
217
218
219 /*
220  * this defines our host template, with which we'll allocate hosts
221  */
222
223 static struct scsi_host_template rtsx_host_template = {
224         /* basic userland interface stuff */
225         .name =                         CR_DRIVER_NAME,
226         .proc_name =                    CR_DRIVER_NAME,
227         .info =                         host_info,
228
229         /* command interface -- queued only */
230         .queuecommand =                 queuecommand,
231
232         /* error and abort handlers */
233         .eh_abort_handler =             command_abort,
234         .eh_device_reset_handler =      device_reset,
235         .eh_bus_reset_handler =         bus_reset,
236
237         /* queue commands only, only one command per LUN */
238         .can_queue =                    1,
239         .cmd_per_lun =                  1,
240
241         /* unknown initiator id */
242         .this_id =                      -1,
243
244         .slave_alloc =                  slave_alloc,
245         .slave_configure =              slave_configure,
246
247         /* lots of sg segments can be handled */
248         .sg_tablesize =                 SG_ALL,
249
250         /* limit the total size of a transfer to 120 KB */
251         .max_sectors =                  240,
252
253         /* merge commands... this seems to help performance, but
254          * periodically someone should test to see which setting is more
255          * optimal.
256          */
257         .use_clustering =               1,
258
259         /* emulated HBA */
260         .emulated =                     1,
261
262         /* we do our own delay after a device or bus reset */
263         .skip_settle_delay =            1,
264
265         /* module management */
266         .module =                       THIS_MODULE
267 };
268
269
270 static int rtsx_acquire_irq(struct rtsx_dev *dev)
271 {
272         struct rtsx_chip *chip = dev->chip;
273
274         dev_info(&dev->pci->dev, "%s: chip->msi_en = %d, pci->irq = %d\n",
275                  __func__, chip->msi_en, dev->pci->irq);
276
277         if (request_irq(dev->pci->irq, rtsx_interrupt,
278                         chip->msi_en ? 0 : IRQF_SHARED,
279                         CR_DRIVER_NAME, dev)) {
280                 dev_err(&dev->pci->dev,
281                         "rtsx: unable to grab IRQ %d, disabling device\n",
282                         dev->pci->irq);
283                 return -1;
284         }
285
286         dev->irq = dev->pci->irq;
287         pci_intx(dev->pci, !chip->msi_en);
288
289         return 0;
290 }
291
292
293 int rtsx_read_pci_cfg_byte(u8 bus, u8 dev, u8 func, u8 offset, u8 *val)
294 {
295         struct pci_dev *pdev;
296         u8 data;
297         u8 devfn = (dev << 3) | func;
298
299         pdev = pci_get_bus_and_slot(bus, devfn);
300         if (!pdev)
301                 return -1;
302
303         pci_read_config_byte(pdev, offset, &data);
304         if (val)
305                 *val = data;
306
307         return 0;
308 }
309
310 #ifdef CONFIG_PM
311 /*
312  * power management
313  */
314 static int rtsx_suspend(struct pci_dev *pci, pm_message_t state)
315 {
316         struct rtsx_dev *dev = (struct rtsx_dev *)pci_get_drvdata(pci);
317         struct rtsx_chip *chip;
318
319         if (!dev)
320                 return 0;
321
322         /* lock the device pointers */
323         mutex_lock(&(dev->dev_mutex));
324
325         chip = dev->chip;
326
327         rtsx_do_before_power_down(chip, PM_S3);
328
329         if (dev->irq >= 0) {
330                 synchronize_irq(dev->irq);
331                 free_irq(dev->irq, (void *)dev);
332                 dev->irq = -1;
333         }
334
335         if (chip->msi_en)
336                 pci_disable_msi(pci);
337
338         pci_save_state(pci);
339         pci_enable_wake(pci, pci_choose_state(pci, state), 1);
340         pci_disable_device(pci);
341         pci_set_power_state(pci, pci_choose_state(pci, state));
342
343         /* unlock the device pointers */
344         mutex_unlock(&dev->dev_mutex);
345
346         return 0;
347 }
348
349 static int rtsx_resume(struct pci_dev *pci)
350 {
351         struct rtsx_dev *dev = (struct rtsx_dev *)pci_get_drvdata(pci);
352         struct rtsx_chip *chip;
353
354         if (!dev)
355                 return 0;
356
357         chip = dev->chip;
358
359         /* lock the device pointers */
360         mutex_lock(&(dev->dev_mutex));
361
362         pci_set_power_state(pci, PCI_D0);
363         pci_restore_state(pci);
364         if (pci_enable_device(pci) < 0) {
365                 dev_err(&dev->pci->dev,
366                         "%s: pci_enable_device failed, disabling device\n",
367                         CR_DRIVER_NAME);
368                 /* unlock the device pointers */
369                 mutex_unlock(&dev->dev_mutex);
370                 return -EIO;
371         }
372         pci_set_master(pci);
373
374         if (chip->msi_en) {
375                 if (pci_enable_msi(pci) < 0)
376                         chip->msi_en = 0;
377         }
378
379         if (rtsx_acquire_irq(dev) < 0) {
380                 /* unlock the device pointers */
381                 mutex_unlock(&dev->dev_mutex);
382                 return -EIO;
383         }
384
385         rtsx_write_register(chip, HOST_SLEEP_STATE, 0x03, 0x00);
386         rtsx_init_chip(chip);
387
388         /* unlock the device pointers */
389         mutex_unlock(&dev->dev_mutex);
390
391         return 0;
392 }
393 #endif /* CONFIG_PM */
394
395 static void rtsx_shutdown(struct pci_dev *pci)
396 {
397         struct rtsx_dev *dev = (struct rtsx_dev *)pci_get_drvdata(pci);
398         struct rtsx_chip *chip;
399
400         if (!dev)
401                 return;
402
403         chip = dev->chip;
404
405         rtsx_do_before_power_down(chip, PM_S1);
406
407         if (dev->irq >= 0) {
408                 synchronize_irq(dev->irq);
409                 free_irq(dev->irq, (void *)dev);
410                 dev->irq = -1;
411         }
412
413         if (chip->msi_en)
414                 pci_disable_msi(pci);
415
416         pci_disable_device(pci);
417
418         return;
419 }
420
421 static int rtsx_control_thread(void *__dev)
422 {
423         struct rtsx_dev *dev = (struct rtsx_dev *)__dev;
424         struct rtsx_chip *chip = dev->chip;
425         struct Scsi_Host *host = rtsx_to_host(dev);
426
427         for (;;) {
428                 if (wait_for_completion_interruptible(&dev->cmnd_ready))
429                         break;
430
431                 /* lock the device pointers */
432                 mutex_lock(&(dev->dev_mutex));
433
434                 /* if the device has disconnected, we are free to exit */
435                 if (rtsx_chk_stat(chip, RTSX_STAT_DISCONNECT)) {
436                         dev_info(&dev->pci->dev, "-- rtsx-control exiting\n");
437                         mutex_unlock(&dev->dev_mutex);
438                         break;
439                 }
440
441                 /* lock access to the state */
442                 scsi_lock(host);
443
444                 /* has the command aborted ? */
445                 if (rtsx_chk_stat(chip, RTSX_STAT_ABORT)) {
446                         chip->srb->result = DID_ABORT << 16;
447                         goto SkipForAbort;
448                 }
449
450                 scsi_unlock(host);
451
452                 /* reject the command if the direction indicator
453                  * is UNKNOWN
454                  */
455                 if (chip->srb->sc_data_direction == DMA_BIDIRECTIONAL) {
456                         dev_err(&dev->pci->dev, "UNKNOWN data direction\n");
457                         chip->srb->result = DID_ERROR << 16;
458                 }
459
460                 /* reject if target != 0 or if LUN is higher than
461                  * the maximum known LUN
462                  */
463                 else if (chip->srb->device->id) {
464                         dev_err(&dev->pci->dev, "Bad target number (%d:%d)\n",
465                                 chip->srb->device->id,
466                                 (u8)chip->srb->device->lun);
467                         chip->srb->result = DID_BAD_TARGET << 16;
468                 }
469
470                 else if (chip->srb->device->lun > chip->max_lun) {
471                         dev_err(&dev->pci->dev, "Bad LUN (%d:%d)\n",
472                                 chip->srb->device->id,
473                                 (u8)chip->srb->device->lun);
474                         chip->srb->result = DID_BAD_TARGET << 16;
475                 }
476
477                 /* we've got a command, let's do it! */
478                 else {
479                         scsi_show_command(chip);
480                         rtsx_invoke_transport(chip->srb, chip);
481                 }
482
483                 /* lock access to the state */
484                 scsi_lock(host);
485
486                 /* did the command already complete because of a disconnect? */
487                 if (!chip->srb)
488                         ;               /* nothing to do */
489
490                 /* indicate that the command is done */
491                 else if (chip->srb->result != DID_ABORT << 16) {
492                         chip->srb->scsi_done(chip->srb);
493                 } else {
494 SkipForAbort:
495                         dev_err(&dev->pci->dev, "scsi command aborted\n");
496                 }
497
498                 if (rtsx_chk_stat(chip, RTSX_STAT_ABORT)) {
499                         complete(&(dev->notify));
500
501                         rtsx_set_stat(chip, RTSX_STAT_IDLE);
502                 }
503
504                 /* finished working on this command */
505                 chip->srb = NULL;
506                 scsi_unlock(host);
507
508                 /* unlock the device pointers */
509                 mutex_unlock(&dev->dev_mutex);
510         } /* for (;;) */
511
512         /* notify the exit routine that we're actually exiting now
513          *
514          * complete()/wait_for_completion() is similar to up()/down(),
515          * except that complete() is safe in the case where the structure
516          * is getting deleted in a parallel mode of execution (i.e. just
517          * after the down() -- that's necessary for the thread-shutdown
518          * case.
519          *
520          * complete_and_exit() goes even further than this -- it is safe in
521          * the case that the thread of the caller is going away (not just
522          * the structure) -- this is necessary for the module-remove case.
523          * This is important in preemption kernels, which transfer the flow
524          * of execution immediately upon a complete().
525          */
526         complete_and_exit(&dev->control_exit, 0);
527 }
528
529
530 static int rtsx_polling_thread(void *__dev)
531 {
532         struct rtsx_dev *dev = (struct rtsx_dev *)__dev;
533         struct rtsx_chip *chip = dev->chip;
534         struct sd_info *sd_card = &(chip->sd_card);
535         struct xd_info *xd_card = &(chip->xd_card);
536         struct ms_info *ms_card = &(chip->ms_card);
537
538         sd_card->cleanup_counter = 0;
539         xd_card->cleanup_counter = 0;
540         ms_card->cleanup_counter = 0;
541
542         /* Wait until SCSI scan finished */
543         wait_timeout((delay_use + 5) * 1000);
544
545         for (;;) {
546
547                 set_current_state(TASK_INTERRUPTIBLE);
548                 schedule_timeout(POLLING_INTERVAL);
549
550                 /* lock the device pointers */
551                 mutex_lock(&(dev->dev_mutex));
552
553                 /* if the device has disconnected, we are free to exit */
554                 if (rtsx_chk_stat(chip, RTSX_STAT_DISCONNECT)) {
555                         dev_info(&dev->pci->dev, "-- rtsx-polling exiting\n");
556                         mutex_unlock(&dev->dev_mutex);
557                         break;
558                 }
559
560                 mutex_unlock(&dev->dev_mutex);
561
562                 mspro_polling_format_status(chip);
563
564                 /* lock the device pointers */
565                 mutex_lock(&(dev->dev_mutex));
566
567                 rtsx_polling_func(chip);
568
569                 /* unlock the device pointers */
570                 mutex_unlock(&dev->dev_mutex);
571         }
572
573         complete_and_exit(&dev->polling_exit, 0);
574 }
575
576 /*
577  * interrupt handler
578  */
579 static irqreturn_t rtsx_interrupt(int irq, void *dev_id)
580 {
581         struct rtsx_dev *dev = dev_id;
582         struct rtsx_chip *chip;
583         int retval;
584         u32 status;
585
586         if (dev)
587                 chip = dev->chip;
588         else
589                 return IRQ_NONE;
590
591         if (!chip)
592                 return IRQ_NONE;
593
594         spin_lock(&dev->reg_lock);
595
596         retval = rtsx_pre_handle_interrupt(chip);
597         if (retval == STATUS_FAIL) {
598                 spin_unlock(&dev->reg_lock);
599                 if (chip->int_reg == 0xFFFFFFFF)
600                         return IRQ_HANDLED;
601                 else
602                         return IRQ_NONE;
603         }
604
605         status = chip->int_reg;
606
607         if (dev->check_card_cd) {
608                 if (!(dev->check_card_cd & status)) {
609                         /* card not exist, return TRANS_RESULT_FAIL */
610                         dev->trans_result = TRANS_RESULT_FAIL;
611                         if (dev->done)
612                                 complete(dev->done);
613                         goto Exit;
614                 }
615         }
616
617         if (status & (NEED_COMPLETE_INT | DELINK_INT)) {
618                 if (status & (TRANS_FAIL_INT | DELINK_INT)) {
619                         if (status & DELINK_INT)
620                                 RTSX_SET_DELINK(chip);
621                         dev->trans_result = TRANS_RESULT_FAIL;
622                         if (dev->done)
623                                 complete(dev->done);
624                 } else if (status & TRANS_OK_INT) {
625                         dev->trans_result = TRANS_RESULT_OK;
626                         if (dev->done)
627                                 complete(dev->done);
628                 } else if (status & DATA_DONE_INT) {
629                         dev->trans_result = TRANS_NOT_READY;
630                         if (dev->done && (dev->trans_state == STATE_TRANS_SG))
631                                 complete(dev->done);
632                 }
633         }
634
635 Exit:
636         spin_unlock(&dev->reg_lock);
637         return IRQ_HANDLED;
638 }
639
640
641 /* Release all our dynamic resources */
642 static void rtsx_release_resources(struct rtsx_dev *dev)
643 {
644         dev_info(&dev->pci->dev, "-- %s\n", __func__);
645
646         /* Tell the control thread to exit.  The SCSI host must
647          * already have been removed so it won't try to queue
648          * any more commands.
649          */
650         dev_info(&dev->pci->dev, "-- sending exit command to thread\n");
651         complete(&dev->cmnd_ready);
652         if (dev->ctl_thread)
653                 wait_for_completion(&dev->control_exit);
654         if (dev->polling_thread)
655                 wait_for_completion(&dev->polling_exit);
656
657         wait_timeout(200);
658
659         if (dev->rtsx_resv_buf) {
660                 dma_free_coherent(&(dev->pci->dev), RTSX_RESV_BUF_LEN,
661                                 dev->rtsx_resv_buf, dev->rtsx_resv_buf_addr);
662                 dev->chip->host_cmds_ptr = NULL;
663                 dev->chip->host_sg_tbl_ptr = NULL;
664         }
665
666         if (dev->irq > 0)
667                 free_irq(dev->irq, (void *)dev);
668         if (dev->chip->msi_en)
669                 pci_disable_msi(dev->pci);
670         if (dev->remap_addr)
671                 iounmap(dev->remap_addr);
672
673         pci_disable_device(dev->pci);
674         pci_release_regions(dev->pci);
675
676         rtsx_release_chip(dev->chip);
677         kfree(dev->chip);
678 }
679
680 /* First stage of disconnect processing: stop all commands and remove
681  * the host */
682 static void quiesce_and_remove_host(struct rtsx_dev *dev)
683 {
684         struct Scsi_Host *host = rtsx_to_host(dev);
685         struct rtsx_chip *chip = dev->chip;
686
687         /* Prevent new transfers, stop the current command, and
688          * interrupt a SCSI-scan or device-reset delay */
689         mutex_lock(&dev->dev_mutex);
690         scsi_lock(host);
691         rtsx_set_stat(chip, RTSX_STAT_DISCONNECT);
692         scsi_unlock(host);
693         mutex_unlock(&dev->dev_mutex);
694         wake_up(&dev->delay_wait);
695         wait_for_completion(&dev->scanning_done);
696
697         /* Wait some time to let other threads exist */
698         wait_timeout(100);
699
700         /* queuecommand won't accept any new commands and the control
701          * thread won't execute a previously-queued command.  If there
702          * is such a command pending, complete it with an error. */
703         mutex_lock(&dev->dev_mutex);
704         if (chip->srb) {
705                 chip->srb->result = DID_NO_CONNECT << 16;
706                 scsi_lock(host);
707                 chip->srb->scsi_done(dev->chip->srb);
708                 chip->srb = NULL;
709                 scsi_unlock(host);
710         }
711         mutex_unlock(&dev->dev_mutex);
712
713         /* Now we own no commands so it's safe to remove the SCSI host */
714         scsi_remove_host(host);
715 }
716
717 /* Second stage of disconnect processing: deallocate all resources */
718 static void release_everything(struct rtsx_dev *dev)
719 {
720         rtsx_release_resources(dev);
721
722         /* Drop our reference to the host; the SCSI core will free it
723          * when the refcount becomes 0. */
724         scsi_host_put(rtsx_to_host(dev));
725 }
726
727 /* Thread to carry out delayed SCSI-device scanning */
728 static int rtsx_scan_thread(void *__dev)
729 {
730         struct rtsx_dev *dev = (struct rtsx_dev *)__dev;
731         struct rtsx_chip *chip = dev->chip;
732
733         /* Wait for the timeout to expire or for a disconnect */
734         if (delay_use > 0) {
735                 dev_info(&dev->pci->dev,
736                          "%s: waiting for device to settle before scanning\n",
737                          CR_DRIVER_NAME);
738                 wait_event_interruptible_timeout(dev->delay_wait,
739                                 rtsx_chk_stat(chip, RTSX_STAT_DISCONNECT),
740                                 delay_use * HZ);
741         }
742
743         /* If the device is still connected, perform the scanning */
744         if (!rtsx_chk_stat(chip, RTSX_STAT_DISCONNECT)) {
745                 scsi_scan_host(rtsx_to_host(dev));
746                 dev_info(&dev->pci->dev, "%s: device scan complete\n",
747                          CR_DRIVER_NAME);
748
749                 /* Should we unbind if no devices were detected? */
750         }
751
752         complete_and_exit(&dev->scanning_done, 0);
753 }
754
755 static void rtsx_init_options(struct rtsx_chip *chip)
756 {
757         chip->vendor_id = chip->rtsx->pci->vendor;
758         chip->product_id = chip->rtsx->pci->device;
759         chip->adma_mode = 1;
760         chip->lun_mc = 0;
761         chip->driver_first_load = 1;
762 #ifdef HW_AUTO_SWITCH_SD_BUS
763         chip->sdio_in_charge = 0;
764 #endif
765
766         chip->mspro_formatter_enable = 1;
767         chip->ignore_sd = 0;
768         chip->use_hw_setting = 0;
769         chip->lun_mode = DEFAULT_SINGLE;
770         chip->auto_delink_en = auto_delink_en;
771         chip->ss_en = ss_en;
772         chip->ss_idle_period = ss_interval * 1000;
773         chip->remote_wakeup_en = 0;
774         chip->aspm_l0s_l1_en = aspm_l0s_l1_en;
775         chip->dynamic_aspm = 1;
776         chip->fpga_sd_sdr104_clk = CLK_200;
777         chip->fpga_sd_ddr50_clk = CLK_100;
778         chip->fpga_sd_sdr50_clk = CLK_100;
779         chip->fpga_sd_hs_clk = CLK_100;
780         chip->fpga_mmc_52m_clk = CLK_80;
781         chip->fpga_ms_hg_clk = CLK_80;
782         chip->fpga_ms_4bit_clk = CLK_80;
783         chip->fpga_ms_1bit_clk = CLK_40;
784         chip->asic_sd_sdr104_clk = 203;
785         chip->asic_sd_sdr50_clk = 98;
786         chip->asic_sd_ddr50_clk = 98;
787         chip->asic_sd_hs_clk = 98;
788         chip->asic_mmc_52m_clk = 98;
789         chip->asic_ms_hg_clk = 117;
790         chip->asic_ms_4bit_clk = 78;
791         chip->asic_ms_1bit_clk = 39;
792         chip->ssc_depth_sd_sdr104 = SSC_DEPTH_2M;
793         chip->ssc_depth_sd_sdr50 = SSC_DEPTH_2M;
794         chip->ssc_depth_sd_ddr50 = SSC_DEPTH_1M;
795         chip->ssc_depth_sd_hs = SSC_DEPTH_1M;
796         chip->ssc_depth_mmc_52m = SSC_DEPTH_1M;
797         chip->ssc_depth_ms_hg = SSC_DEPTH_1M;
798         chip->ssc_depth_ms_4bit = SSC_DEPTH_512K;
799         chip->ssc_depth_low_speed = SSC_DEPTH_512K;
800         chip->ssc_en = 1;
801         chip->sd_speed_prior = 0x01040203;
802         chip->sd_current_prior = 0x00010203;
803         chip->sd_ctl = SD_PUSH_POINT_AUTO |
804                        SD_SAMPLE_POINT_AUTO |
805                        SUPPORT_MMC_DDR_MODE;
806         chip->sd_ddr_tx_phase = 0;
807         chip->mmc_ddr_tx_phase = 1;
808         chip->sd_default_tx_phase = 15;
809         chip->sd_default_rx_phase = 15;
810         chip->pmos_pwr_on_interval = 200;
811         chip->sd_voltage_switch_delay = 1000;
812         chip->ms_power_class_en = 3;
813
814         chip->sd_400mA_ocp_thd = 1;
815         chip->sd_800mA_ocp_thd = 5;
816         chip->ms_ocp_thd = 2;
817
818         chip->card_drive_sel = 0x55;
819         chip->sd30_drive_sel_1v8 = 0x03;
820         chip->sd30_drive_sel_3v3 = 0x01;
821
822         chip->do_delink_before_power_down = 1;
823         chip->auto_power_down = 1;
824         chip->polling_config = 0;
825
826         chip->force_clkreq_0 = 1;
827         chip->ft2_fast_mode = 0;
828
829         chip->sdio_retry_cnt = 1;
830
831         chip->xd_timeout = 2000;
832         chip->sd_timeout = 10000;
833         chip->ms_timeout = 2000;
834         chip->mspro_timeout = 15000;
835
836         chip->power_down_in_ss = 1;
837
838         chip->sdr104_en = 1;
839         chip->sdr50_en = 1;
840         chip->ddr50_en = 1;
841
842         chip->delink_stage1_step = 100;
843         chip->delink_stage2_step = 40;
844         chip->delink_stage3_step = 20;
845
846         chip->auto_delink_in_L1 = 1;
847         chip->blink_led = 1;
848         chip->msi_en = msi_en;
849         chip->hp_watch_bios_hotplug = 0;
850         chip->max_payload = 0;
851         chip->phy_voltage = 0;
852
853         chip->support_ms_8bit = 1;
854         chip->s3_pwr_off_delay = 1000;
855 }
856
857 static int rtsx_probe(struct pci_dev *pci,
858                                 const struct pci_device_id *pci_id)
859 {
860         struct Scsi_Host *host;
861         struct rtsx_dev *dev;
862         int err = 0;
863         struct task_struct *th;
864
865         dev_dbg(&pci->dev, "Realtek PCI-E card reader detected\n");
866
867         err = pci_enable_device(pci);
868         if (err < 0) {
869                 dev_err(&pci->dev, "PCI enable device failed!\n");
870                 return err;
871         }
872
873         err = pci_request_regions(pci, CR_DRIVER_NAME);
874         if (err < 0) {
875                 dev_err(&pci->dev, "PCI request regions for %s failed!\n",
876                         CR_DRIVER_NAME);
877                 pci_disable_device(pci);
878                 return err;
879         }
880
881         /*
882          * Ask the SCSI layer to allocate a host structure, with extra
883          * space at the end for our private rtsx_dev structure.
884          */
885         host = scsi_host_alloc(&rtsx_host_template, sizeof(*dev));
886         if (!host) {
887                 dev_err(&pci->dev, "Unable to allocate the scsi host\n");
888                 pci_release_regions(pci);
889                 pci_disable_device(pci);
890                 return -ENOMEM;
891         }
892
893         dev = host_to_rtsx(host);
894         memset(dev, 0, sizeof(struct rtsx_dev));
895
896         dev->chip = kzalloc(sizeof(struct rtsx_chip), GFP_KERNEL);
897         if (dev->chip == NULL) {
898                 err = -ENOMEM;
899                 goto errout;
900         }
901
902         spin_lock_init(&dev->reg_lock);
903         mutex_init(&(dev->dev_mutex));
904         init_completion(&dev->cmnd_ready);
905         init_completion(&dev->control_exit);
906         init_completion(&dev->polling_exit);
907         init_completion(&(dev->notify));
908         init_completion(&dev->scanning_done);
909         init_waitqueue_head(&dev->delay_wait);
910
911         dev->pci = pci;
912         dev->irq = -1;
913
914         dev_info(&pci->dev, "Resource length: 0x%x\n",
915                  (unsigned int)pci_resource_len(pci, 0));
916         dev->addr = pci_resource_start(pci, 0);
917         dev->remap_addr = ioremap_nocache(dev->addr, pci_resource_len(pci, 0));
918         if (dev->remap_addr == NULL) {
919                 dev_err(&pci->dev, "ioremap error\n");
920                 err = -ENXIO;
921                 goto errout;
922         }
923
924         /*
925          * Using "unsigned long" cast here to eliminate gcc warning in
926          * 64-bit system
927          */
928         dev_info(&pci->dev, "Original address: 0x%lx, remapped address: 0x%lx\n",
929                  (unsigned long)(dev->addr), (unsigned long)(dev->remap_addr));
930
931         dev->rtsx_resv_buf = dma_alloc_coherent(&(pci->dev), RTSX_RESV_BUF_LEN,
932                         &(dev->rtsx_resv_buf_addr), GFP_KERNEL);
933         if (dev->rtsx_resv_buf == NULL) {
934                 dev_err(&pci->dev, "alloc dma buffer fail\n");
935                 err = -ENXIO;
936                 goto errout;
937         }
938         dev->chip->host_cmds_ptr = dev->rtsx_resv_buf;
939         dev->chip->host_cmds_addr = dev->rtsx_resv_buf_addr;
940         dev->chip->host_sg_tbl_ptr = dev->rtsx_resv_buf + HOST_CMDS_BUF_LEN;
941         dev->chip->host_sg_tbl_addr = dev->rtsx_resv_buf_addr +
942                                       HOST_CMDS_BUF_LEN;
943
944         dev->chip->rtsx = dev;
945
946         rtsx_init_options(dev->chip);
947
948         dev_info(&pci->dev, "pci->irq = %d\n", pci->irq);
949
950         if (dev->chip->msi_en) {
951                 if (pci_enable_msi(pci) < 0)
952                         dev->chip->msi_en = 0;
953         }
954
955         if (rtsx_acquire_irq(dev) < 0) {
956                 err = -EBUSY;
957                 goto errout;
958         }
959
960         pci_set_master(pci);
961         synchronize_irq(dev->irq);
962
963         rtsx_init_chip(dev->chip);
964
965         /* set the supported max_lun and max_id for the scsi host
966          * NOTE: the minimal value of max_id is 1 */
967         host->max_id = 1;
968         host->max_lun = dev->chip->max_lun;
969
970         /* Start up our control thread */
971         th = kthread_run(rtsx_control_thread, dev, CR_DRIVER_NAME);
972         if (IS_ERR(th)) {
973                 dev_err(&pci->dev, "Unable to start control thread\n");
974                 err = PTR_ERR(th);
975                 goto errout;
976         }
977         dev->ctl_thread = th;
978
979         err = scsi_add_host(host, &pci->dev);
980         if (err) {
981                 dev_err(&pci->dev, "Unable to add the scsi host\n");
982                 goto errout;
983         }
984
985         /* Start up the thread for delayed SCSI-device scanning */
986         th = kthread_run(rtsx_scan_thread, dev, "rtsx-scan");
987         if (IS_ERR(th)) {
988                 dev_err(&pci->dev, "Unable to start the device-scanning thread\n");
989                 complete(&dev->scanning_done);
990                 quiesce_and_remove_host(dev);
991                 err = PTR_ERR(th);
992                 goto errout;
993         }
994
995         /* Start up the thread for polling thread */
996         th = kthread_run(rtsx_polling_thread, dev, "rtsx-polling");
997         if (IS_ERR(th)) {
998                 dev_err(&pci->dev, "Unable to start the device-polling thread\n");
999                 quiesce_and_remove_host(dev);
1000                 err = PTR_ERR(th);
1001                 goto errout;
1002         }
1003         dev->polling_thread = th;
1004
1005         pci_set_drvdata(pci, dev);
1006
1007         return 0;
1008
1009         /* We come here if there are any problems */
1010 errout:
1011         dev_err(&pci->dev, "rtsx_probe() failed\n");
1012         release_everything(dev);
1013
1014         return err;
1015 }
1016
1017
1018 static void rtsx_remove(struct pci_dev *pci)
1019 {
1020         struct rtsx_dev *dev = (struct rtsx_dev *)pci_get_drvdata(pci);
1021
1022         dev_info(&pci->dev, "rtsx_remove() called\n");
1023
1024         quiesce_and_remove_host(dev);
1025         release_everything(dev);
1026
1027         pci_set_drvdata(pci, NULL);
1028 }
1029
1030 /* PCI IDs */
1031 static const struct pci_device_id rtsx_ids[] = {
1032         { PCI_DEVICE(PCI_VENDOR_ID_REALTEK, 0x5208),
1033                 PCI_CLASS_OTHERS << 16, 0xFF0000 },
1034         { PCI_DEVICE(PCI_VENDOR_ID_REALTEK, 0x5288),
1035                 PCI_CLASS_OTHERS << 16, 0xFF0000 },
1036         { 0, },
1037 };
1038
1039 MODULE_DEVICE_TABLE(pci, rtsx_ids);
1040
1041 /* pci_driver definition */
1042 static struct pci_driver driver = {
1043         .name = CR_DRIVER_NAME,
1044         .id_table = rtsx_ids,
1045         .probe = rtsx_probe,
1046         .remove = rtsx_remove,
1047 #ifdef CONFIG_PM
1048         .suspend = rtsx_suspend,
1049         .resume = rtsx_resume,
1050 #endif
1051         .shutdown = rtsx_shutdown,
1052 };
1053
1054 static int __init rtsx_init(void)
1055 {
1056         pr_info("Initializing Realtek PCIE storage driver...\n");
1057
1058         return pci_register_driver(&driver);
1059 }
1060
1061 static void __exit rtsx_exit(void)
1062 {
1063         pr_info("rtsx_exit() called\n");
1064
1065         pci_unregister_driver(&driver);
1066
1067         pr_info("%s module exit\n", CR_DRIVER_NAME);
1068 }
1069
1070 module_init(rtsx_init)
1071 module_exit(rtsx_exit)