Merge branch 'next/cleanup2' of git://git.linaro.org/people/arnd/arm-soc
[pandora-kernel.git] / drivers / staging / rts5139 / rts51x.c
1 /* Driver for Realtek RTS51xx USB card reader
2  *
3  * Copyright(c) 2009 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  *   wwang (wei_wang@realsil.com.cn)
20  *   No. 450, Shenhu Road, Suzhou Industry Park, Suzhou, China
21  * Maintainer:
22  *   Edwin Rong (edwin_rong@realsil.com.cn)
23  *   No. 450, Shenhu Road, Suzhou Industry Park, Suzhou, China
24  */
25
26 #include <linux/blkdev.h>
27 #include <linux/kthread.h>
28 #include <linux/sched.h>
29 #include <linux/workqueue.h>
30 #include <linux/errno.h>
31 #include <linux/freezer.h>
32 #include <linux/module.h>
33 #include <linux/init.h>
34 #include <linux/slab.h>
35 #include <linux/mutex.h>
36 #include <linux/utsname.h>
37 #include <linux/usb.h>
38
39 #include <scsi/scsi.h>
40 #include <scsi/scsi_cmnd.h>
41 #include <scsi/scsi_device.h>
42 #include <scsi/scsi_devinfo.h>
43 #include <scsi/scsi_eh.h>
44 #include <scsi/scsi_host.h>
45
46 #include "debug.h"
47 #include "ms.h"
48 #include "rts51x.h"
49 #include "rts51x_chip.h"
50 #include "rts51x_card.h"
51 #include "rts51x_scsi.h"
52 #include "rts51x_transport.h"
53 #include "rts51x_fop.h"
54
55 MODULE_DESCRIPTION(RTS51X_DESC);
56 MODULE_LICENSE("GPL");
57 MODULE_VERSION(DRIVER_VERSION);
58
59 #ifdef SCSI_SCAN_DELAY
60 static unsigned int delay_use = 5;
61 module_param(delay_use, uint, S_IRUGO | S_IWUSR);
62 MODULE_PARM_DESC(delay_use, "seconds to delay before using a new device");
63 #endif
64
65 static int auto_delink_en;
66 module_param(auto_delink_en, int, S_IRUGO | S_IWUSR);
67 MODULE_PARM_DESC(auto_delink_en, "enable auto delink");
68
69 static int ss_en;
70 module_param(ss_en, int, S_IRUGO | S_IWUSR);
71 MODULE_PARM_DESC(ss_en, "enable selective suspend");
72
73 static int ss_delay = 50;
74 module_param(ss_delay, int, S_IRUGO | S_IWUSR);
75 MODULE_PARM_DESC(ss_delay,
76                  "seconds to delay before entering selective suspend");
77
78 static int needs_remote_wakeup;
79 module_param(needs_remote_wakeup, int, S_IRUGO | S_IWUSR);
80 MODULE_PARM_DESC(needs_remote_wakeup, "ss state needs remote wakeup supported");
81
82 #ifdef SUPPORT_FILE_OP
83 static const struct file_operations rts51x_fops = {
84         .owner = THIS_MODULE,
85         .read = rts51x_read,
86         .write = rts51x_write,
87         .unlocked_ioctl = rts51x_ioctl,
88         .open = rts51x_open,
89         .release = rts51x_release,
90 };
91
92 /*
93  * usb class driver info in order to get a minor number from the usb core,
94  * and to have the device registered with the driver core
95  */
96 static struct usb_class_driver rts51x_class = {
97         .name = "rts51x%d",
98         .fops = &rts51x_fops,
99         .minor_base = 192,
100 };
101 #endif
102
103 #ifdef CONFIG_PM                /* Minimal support for suspend and resume */
104
105 static inline void usb_autopm_enable(struct usb_interface *intf)
106 {
107         atomic_set(&intf->pm_usage_cnt, 1);
108         usb_autopm_put_interface(intf);
109 }
110
111 static inline void usb_autopm_disable(struct usb_interface *intf)
112 {
113         atomic_set(&intf->pm_usage_cnt, 0);
114         usb_autopm_get_interface(intf);
115 }
116
117 void rts51x_try_to_enter_ss(struct rts51x_chip *chip)
118 {
119         RTS51X_DEBUGP("Ready to enter SS state\n");
120         usb_autopm_enable(chip->usb->pusb_intf);
121 }
122
123 void rts51x_try_to_exit_ss(struct rts51x_chip *chip)
124 {
125         RTS51X_DEBUGP("Exit from SS state\n");
126         usb_autopm_disable(chip->usb->pusb_intf);
127 }
128
129 int rts51x_suspend(struct usb_interface *iface, pm_message_t message)
130 {
131         struct rts51x_chip *chip = usb_get_intfdata(iface);
132
133         RTS51X_DEBUGP("%s, message.event = 0x%x\n", __func__, message.event);
134
135         /* Wait until no command is running */
136         mutex_lock(&chip->usb->dev_mutex);
137
138         chip->fake_card_ready = chip->card_ready;
139         rts51x_do_before_power_down(chip);
140
141         if (message.event == PM_EVENT_AUTO_SUSPEND) {
142                 RTS51X_DEBUGP("Enter SS state");
143                 chip->resume_from_scsi = 0;
144                 RTS51X_SET_STAT(chip, STAT_SS);
145         } else {
146                 RTS51X_DEBUGP("Enter SUSPEND state");
147                 RTS51X_SET_STAT(chip, STAT_SUSPEND);
148         }
149
150         /* When runtime PM is working, we'll set a flag to indicate
151          * whether we should autoresume when a SCSI request arrives. */
152
153         mutex_unlock(&chip->usb->dev_mutex);
154         return 0;
155 }
156
157 int rts51x_resume(struct usb_interface *iface)
158 {
159         struct rts51x_chip *chip = usb_get_intfdata(iface);
160
161         RTS51X_DEBUGP("%s\n", __func__);
162
163         if (!RTS51X_CHK_STAT(chip, STAT_SS) || !chip->resume_from_scsi) {
164                 mutex_lock(&chip->usb->dev_mutex);
165
166                 if (chip->option.ss_en) {
167                         if (GET_PM_USAGE_CNT(chip) <= 0) {
168                                 /* Remote wake up, increase pm_usage_cnt */
169                                 RTS51X_DEBUGP("Incr pm_usage_cnt\n");
170                                 SET_PM_USAGE_CNT(chip, 1);
171                         }
172                 }
173
174                 RTS51X_SET_STAT(chip, STAT_RUN);
175
176                 rts51x_init_chip(chip);
177                 rts51x_init_cards(chip);
178
179                 mutex_unlock(&chip->usb->dev_mutex);
180         }
181
182         return 0;
183 }
184
185 int rts51x_reset_resume(struct usb_interface *iface)
186 {
187         struct rts51x_chip *chip = usb_get_intfdata(iface);
188
189         RTS51X_DEBUGP("%s\n", __func__);
190
191         mutex_lock(&chip->usb->dev_mutex);
192
193         RTS51X_SET_STAT(chip, STAT_RUN);
194
195         if (chip->option.ss_en)
196                 SET_PM_USAGE_CNT(chip, 1);
197
198         rts51x_init_chip(chip);
199         rts51x_init_cards(chip);
200
201         mutex_unlock(&chip->usb->dev_mutex);
202
203         /* FIXME: Notify the subdrivers that they need to reinitialize
204          * the device */
205         return 0;
206 }
207
208 #else /* CONFIG_PM */
209
210 void rts51x_try_to_enter_ss(struct rts51x_chip *chip)
211 {
212 }
213
214 void rts51x_try_to_exit_ss(struct rts51x_chip *chip)
215 {
216 }
217
218 #endif /* CONFIG_PM */
219
220 /*
221  * The next two routines get called just before and just after
222  * a USB port reset, whether from this driver or a different one.
223  */
224
225 int rts51x_pre_reset(struct usb_interface *iface)
226 {
227         struct rts51x_chip *chip = usb_get_intfdata(iface);
228
229         RTS51X_DEBUGP("%s\n", __func__);
230
231         /* Make sure no command runs during the reset */
232         mutex_lock(&chip->usb->dev_mutex);
233         return 0;
234 }
235
236 int rts51x_post_reset(struct usb_interface *iface)
237 {
238         struct rts51x_chip *chip = usb_get_intfdata(iface);
239
240         RTS51X_DEBUGP("%s\n", __func__);
241
242         /* Report the reset to the SCSI core */
243         /* usb_stor_report_bus_reset(us); */
244
245         /* FIXME: Notify the subdrivers that they need to reinitialize
246          * the device */
247
248         mutex_unlock(&chip->usb->dev_mutex);
249         return 0;
250 }
251
252 static int rts51x_control_thread(void *__chip)
253 {
254         struct rts51x_chip *chip = (struct rts51x_chip *)__chip;
255         struct Scsi_Host *host = rts51x_to_host(chip);
256
257         for (;;) {
258                 if (wait_for_completion_interruptible(&chip->usb->cmnd_ready))
259                         break;
260
261                 if (test_bit(FLIDX_DISCONNECTING, &chip->usb->dflags)) {
262                         RTS51X_DEBUGP("-- exiting from rts51x-control\n");
263                         break;
264                 }
265
266                 /* lock the device pointers */
267                 mutex_lock(&(chip->usb->dev_mutex));
268
269                 /* lock access to the state */
270                 scsi_lock(host);
271
272                 /* When we are called with no command pending, we're done */
273                 if (chip->srb == NULL) {
274                         scsi_unlock(host);
275                         mutex_unlock(&chip->usb->dev_mutex);
276                         RTS51X_DEBUGP("-- exiting from control thread\n");
277                         break;
278                 }
279
280                 /* has the command timed out *already* ? */
281                 if (test_bit(FLIDX_TIMED_OUT, &chip->usb->dflags)) {
282                         chip->srb->result = DID_ABORT << 16;
283                         goto SkipForAbort;
284                 }
285
286                 scsi_unlock(host);
287
288                 /* reject the command if the direction indicator
289                  * is UNKNOWN
290                  */
291                 if (chip->srb->sc_data_direction == DMA_BIDIRECTIONAL) {
292                         RTS51X_DEBUGP("UNKNOWN data direction\n");
293                         chip->srb->result = DID_ERROR << 16;
294                 }
295
296                 /* reject if target != 0 or if LUN is higher than
297                  * the maximum known LUN
298                  */
299                 else if (chip->srb->device->id) {
300                         RTS51X_DEBUGP("Bad target number (%d:%d)\n",
301                                        chip->srb->device->id,
302                                        chip->srb->device->lun);
303                         chip->srb->result = DID_BAD_TARGET << 16;
304                 }
305
306                 else if (chip->srb->device->lun > chip->max_lun) {
307                         RTS51X_DEBUGP("Bad LUN (%d:%d)\n",
308                                        chip->srb->device->id,
309                                        chip->srb->device->lun);
310                         chip->srb->result = DID_BAD_TARGET << 16;
311                 }
312
313                 /* we've got a command, let's do it! */
314                 else {
315                         RTS51X_DEBUG(scsi_show_command(chip->srb));
316                         rts51x_invoke_transport(chip->srb, chip);
317                 }
318
319                 /* lock access to the state */
320                 scsi_lock(host);
321
322                 /* indicate that the command is done */
323                 if (chip->srb->result != DID_ABORT << 16)
324                         chip->srb->scsi_done(chip->srb);
325                 else
326 SkipForAbort :
327                         RTS51X_DEBUGP("scsi command aborted\n");
328
329                 /* If an abort request was received we need to signal that
330                  * the abort has finished.  The proper test for this is
331                  * the TIMED_OUT flag, not srb->result == DID_ABORT, because
332                  * the timeout might have occurred after the command had
333                  * already completed with a different result code. */
334                 if (test_bit(FLIDX_TIMED_OUT, &chip->usb->dflags)) {
335                         complete(&(chip->usb->notify));
336
337                         /* Allow USB transfers to resume */
338                         clear_bit(FLIDX_ABORTING, &chip->usb->dflags);
339                         clear_bit(FLIDX_TIMED_OUT, &chip->usb->dflags);
340                 }
341
342                 /* finished working on this command */
343                 chip->srb = NULL;
344                 scsi_unlock(host);
345
346                 /* unlock the device pointers */
347                 mutex_unlock(&chip->usb->dev_mutex);
348         }                       /* for (;;) */
349
350         complete(&chip->usb->control_exit);
351
352         /* Wait until we are told to stop */
353 /*      for (;;) {
354                 set_current_state(TASK_INTERRUPTIBLE);
355                 if (kthread_should_stop())
356                         break;
357                 schedule();
358         }
359         __set_current_state(TASK_RUNNING);*/
360         return 0;
361 }
362
363 static int rts51x_polling_thread(void *__chip)
364 {
365         struct rts51x_chip *chip = (struct rts51x_chip *)__chip;
366
367 #ifdef SCSI_SCAN_DELAY
368         /* Wait until SCSI scan finished */
369         wait_timeout((delay_use + 5) * HZ);
370 #endif
371
372         for (;;) {
373                 wait_timeout(POLLING_INTERVAL);
374
375                 /* if the device has disconnected, we are free to exit */
376                 if (test_bit(FLIDX_DISCONNECTING, &chip->usb->dflags)) {
377                         RTS51X_DEBUGP("-- exiting from rts51x-polling\n");
378                         break;
379                 }
380
381                 /* if the device has disconnected, we are free to exit */
382                 /* if (kthread_should_stop()) {
383                         printk(KERN_INFO "Stop polling thread!\n");
384                         break;
385                 } */
386
387 #ifdef CONFIG_PM
388                 if (RTS51X_CHK_STAT(chip, STAT_SS) ||
389                     RTS51X_CHK_STAT(chip, STAT_SS_PRE) ||
390                     RTS51X_CHK_STAT(chip, STAT_SUSPEND)) {
391                         continue;
392                 }
393
394                 if (ss_en) {
395                         if (RTS51X_CHK_STAT(chip, STAT_IDLE)) {
396                                 if (chip->ss_counter <
397                                     (ss_delay * 1000 / POLLING_INTERVAL)) {
398                                         chip->ss_counter++;
399                                 } else {
400                                         /* Prepare SS state */
401                                         RTS51X_SET_STAT(chip, STAT_SS_PRE);
402                                         rts51x_try_to_enter_ss(chip);
403                                         continue;
404                                 }
405                         } else {
406                                 chip->ss_counter = 0;
407                         }
408                 }
409 #endif
410
411                 mspro_polling_format_status(chip);
412
413                 /* lock the device pointers */
414                 mutex_lock(&(chip->usb->dev_mutex));
415
416                 rts51x_polling_func(chip);
417
418                 /* unlock the device pointers */
419                 mutex_unlock(&chip->usb->dev_mutex);
420         }                       /* for (;;) */
421
422         complete(&chip->usb->polling_exit);
423
424         /* Wait until we are told to stop */
425         /* for (;;) {
426                 set_current_state(TASK_INTERRUPTIBLE);
427                 if (kthread_should_stop())
428                 break;
429                 schedule();
430                 }
431         __set_current_state(TASK_RUNNING); */
432         return 0;
433 }
434
435 #ifdef SCSI_SCAN_DELAY
436 /* Thread to carry out delayed SCSI-device scanning */
437 static int rts51x_scan_thread(void *__chip)
438 {
439         struct rts51x_chip *chip = (struct rts51x_chip *)__chip;
440
441         printk(KERN_DEBUG
442                "rts51x: device found at %d\n", chip->usb->pusb_dev->devnum);
443
444         set_freezable();
445         /* Wait for the timeout to expire or for a disconnect */
446         if (delay_use > 0) {
447                 printk(KERN_DEBUG "rts51x: waiting for device "
448                        "to settle before scanning\n");
449                 wait_event_freezable_timeout(chip->usb->delay_wait,
450                                              test_bit(FLIDX_DONT_SCAN,
451                                                       &chip->usb->dflags),
452                                              delay_use * HZ);
453         }
454
455         /* If the device is still connected, perform the scanning */
456         if (!test_bit(FLIDX_DONT_SCAN, &chip->usb->dflags)) {
457                 scsi_scan_host(rts51x_to_host(chip));
458                 printk(KERN_DEBUG "rts51x: device scan complete\n");
459
460                 /* Should we unbind if no devices were detected? */
461         }
462
463         complete_and_exit(&chip->usb->scanning_done, 0);
464 }
465 #endif
466
467 /* Associate our private data with the USB device */
468 static int associate_dev(struct rts51x_chip *chip, struct usb_interface *intf)
469 {
470         struct rts51x_usb *rts51x = chip->usb;
471 #ifdef SUPPORT_FILE_OP
472         int retval;
473 #endif
474
475         /* Fill in the device-related fields */
476         rts51x->pusb_dev = interface_to_usbdev(intf);
477         rts51x->pusb_intf = intf;
478         rts51x->ifnum = intf->cur_altsetting->desc.bInterfaceNumber;
479         RTS51X_DEBUGP("Vendor: 0x%04x, Product: 0x%04x, Revision: 0x%04x\n",
480                        le16_to_cpu(rts51x->pusb_dev->descriptor.idVendor),
481                        le16_to_cpu(rts51x->pusb_dev->descriptor.idProduct),
482                        le16_to_cpu(rts51x->pusb_dev->descriptor.bcdDevice));
483         RTS51X_DEBUGP("Interface Subclass: 0x%02x, Protocol: 0x%02x\n",
484                        intf->cur_altsetting->desc.bInterfaceSubClass,
485                        intf->cur_altsetting->desc.bInterfaceProtocol);
486
487         /* Store our private data in the interface */
488         usb_set_intfdata(intf, chip);
489
490 #ifdef SUPPORT_FILE_OP
491         /* we can register the device now, as it is ready */
492         retval = usb_register_dev(intf, &rts51x_class);
493         if (retval) {
494                 /* something prevented us from registering this driver */
495                 RTS51X_DEBUGP("Not able to get a minor for this device.");
496                 usb_set_intfdata(intf, NULL);
497                 return -ENOMEM;
498         }
499 #endif
500
501         /* Allocate the device-related DMA-mapped buffers */
502         rts51x->cr = usb_buffer_alloc(rts51x->pusb_dev, sizeof(*rts51x->cr),
503                                       GFP_KERNEL, &rts51x->cr_dma);
504         if (!rts51x->cr) {
505                 RTS51X_DEBUGP("usb_ctrlrequest allocation failed\n");
506                 usb_set_intfdata(intf, NULL);
507                 return -ENOMEM;
508         }
509
510         rts51x->iobuf = usb_buffer_alloc(rts51x->pusb_dev, RTS51X_IOBUF_SIZE,
511                                          GFP_KERNEL, &rts51x->iobuf_dma);
512         if (!rts51x->iobuf) {
513                 RTS51X_DEBUGP("I/O buffer allocation failed\n");
514                 usb_set_intfdata(intf, NULL);
515                 return -ENOMEM;
516         }
517         return 0;
518 }
519
520 static void rts51x_init_options(struct rts51x_chip *chip)
521 {
522         struct rts51x_option *option = &(chip->option);
523
524         option->led_blink_speed = 7;
525         option->mspro_formatter_enable = 1;
526
527         option->fpga_sd_sdr104_clk = CLK_100;
528         option->fpga_sd_sdr50_clk = CLK_100;
529         option->fpga_sd_ddr50_clk = CLK_100;
530         option->fpga_sd_hs_clk = CLK_100;
531         option->fpga_mmc_52m_clk = CLK_80;
532         option->fpga_ms_hg_clk = CLK_80;
533         option->fpga_ms_4bit_clk = CLK_80;
534
535         option->asic_sd_sdr104_clk = 98;
536         option->asic_sd_sdr50_clk = 98;
537         option->asic_sd_ddr50_clk = 98;
538         option->asic_sd_hs_clk = 97;
539         option->asic_mmc_52m_clk = 95;
540         option->asic_ms_hg_clk = 116;
541         option->asic_ms_4bit_clk = 77;
542
543         option->sd_ddr_tx_phase = 0;
544         option->mmc_ddr_tx_phase = 1;
545
546         option->sd_speed_prior = 0;
547         option->sd_ctl =
548             SD_PUSH_POINT_AUTO | SD_SAMPLE_POINT_AUTO | SUPPORT_UHS50_MMC44;
549
550         option->ss_en = ss_en;
551         option->ss_delay = ss_delay;
552         option->needs_remote_wakeup = needs_remote_wakeup;
553
554         option->auto_delink_en = auto_delink_en;
555
556         option->FT2_fast_mode = 0;
557         option->pwr_delay = 800;
558         option->xd_rw_step = 0;
559         option->D3318_off_delay = 50;
560         option->delink_delay = 100;
561         option->rts5129_D3318_off_enable = 0;
562         option->sd20_pad_drive = 0;
563         option->reset_or_rw_fail_set_pad_drive = 1;
564         option->rcc_fail_flag = 0;
565         option->rcc_bug_fix_en = 1;
566         option->debounce_num = 2;
567         option->polling_time = 100;
568         option->led_toggle_interval = 6;
569         option->xd_rwn_step = 0;
570         option->sd_send_status_en = 0;
571         option->sdr50_tx_phase = 0x01;
572         option->sdr50_rx_phase = 0x05;
573         option->ddr50_tx_phase = 0x09;
574         option->ddr50_rx_phase = 0x06;
575         option->sdr50_phase_sel = 0;
576         option->sd30_pad_drive = 1;
577         option->ms_errreg_fix = 0;
578         option->reset_mmc_first = 0;
579         option->speed_mmc = 1;
580         option->led_always_on = 0;
581 }
582
583 /* Get the pipe settings */
584 static int get_pipes(struct rts51x_chip *chip)
585 {
586         struct rts51x_usb *rts51x = chip->usb;
587         struct usb_host_interface *altsetting =
588             rts51x->pusb_intf->cur_altsetting;
589         int i;
590         struct usb_endpoint_descriptor *ep;
591         struct usb_endpoint_descriptor *ep_in = NULL;
592         struct usb_endpoint_descriptor *ep_out = NULL;
593         struct usb_endpoint_descriptor *ep_int = NULL;
594
595         /*
596          * Find the first endpoint of each type we need.
597          * We are expecting a minimum of 2 endpoints - in and out (bulk).
598          * An optional interrupt-in is OK (necessary for CBI protocol).
599          * We will ignore any others.
600          */
601         for (i = 0; i < altsetting->desc.bNumEndpoints; i++) {
602                 ep = &altsetting->endpoint[i].desc;
603
604                 if (usb_endpoint_xfer_bulk(ep)) {
605                         if (usb_endpoint_dir_in(ep)) {
606                                 if (!ep_in)
607                                         ep_in = ep;
608                         } else {
609                                 if (!ep_out)
610                                         ep_out = ep;
611                         }
612                 }
613
614                 else if (usb_endpoint_is_int_in(ep)) {
615                         if (!ep_int)
616                                 ep_int = ep;
617                 }
618         }
619
620         if (!ep_in || !ep_out) {
621                 RTS51X_DEBUGP("Endpoint sanity check failed!"
622                                         "Rejecting dev.\n");
623                 return -EIO;
624         }
625
626         /* Calculate and store the pipe values */
627         rts51x->send_ctrl_pipe = usb_sndctrlpipe(rts51x->pusb_dev, 0);
628         rts51x->recv_ctrl_pipe = usb_rcvctrlpipe(rts51x->pusb_dev, 0);
629         rts51x->send_bulk_pipe = usb_sndbulkpipe(rts51x->pusb_dev,
630                                                  usb_endpoint_num(ep_out));
631         rts51x->recv_bulk_pipe = usb_rcvbulkpipe(rts51x->pusb_dev,
632                                                  usb_endpoint_num(ep_in));
633         if (ep_int) {
634                 rts51x->recv_intr_pipe = usb_rcvintpipe(rts51x->pusb_dev,
635                                                         usb_endpoint_num
636                                                         (ep_int));
637                 rts51x->ep_bInterval = ep_int->bInterval;
638         }
639         return 0;
640 }
641
642 /* Initialize all the dynamic resources we need */
643 static int rts51x_acquire_resources(struct rts51x_chip *chip)
644 {
645         struct rts51x_usb *rts51x = chip->usb;
646         int retval;
647
648         rts51x->current_urb = usb_alloc_urb(0, GFP_KERNEL);
649         if (!rts51x->current_urb) {
650                 RTS51X_DEBUGP("URB allocation failed\n");
651                 return -ENOMEM;
652         }
653
654         rts51x->intr_urb = usb_alloc_urb(0, GFP_KERNEL);
655         if (!rts51x->intr_urb) {
656                 RTS51X_DEBUGP("URB allocation failed\n");
657                 return -ENOMEM;
658         }
659
660         chip->cmd_buf = chip->rsp_buf = rts51x->iobuf;
661
662         rts51x_init_options(chip);
663
664         /* Init rts51xx device */
665         retval = rts51x_init_chip(chip);
666         if (retval != STATUS_SUCCESS)
667                 return -EIO;
668
669         return 0;
670 }
671
672 /* Release all our dynamic resources */
673 static void rts51x_release_resources(struct rts51x_chip *chip)
674 {
675         RTS51X_DEBUGP("-- %s\n", __func__);
676
677         /* Tell the control thread to exit.  The SCSI host must
678          * already have been removed and the DISCONNECTING flag set
679          * so that we won't accept any more commands.
680          */
681         RTS51X_DEBUGP("-- sending exit command to thread\n");
682         complete(&chip->usb->cmnd_ready);
683         if (chip->usb->ctl_thread)
684                 wait_for_completion(&chip->usb->control_exit);
685                 /* kthread_stop(chip->usb->ctl_thread); */
686         if (chip->usb->polling_thread)
687                 wait_for_completion(&chip->usb->polling_exit);
688
689         /* if (chip->usb->polling_thread)
690                 kthread_stop(chip->usb->polling_thread); */
691
692         wait_timeout(200);
693
694         /* Release rts51xx device here */
695         rts51x_release_chip(chip);
696
697         usb_free_urb(chip->usb->current_urb);
698         usb_free_urb(chip->usb->intr_urb);
699 }
700
701 /* Dissociate from the USB device */
702 static void dissociate_dev(struct rts51x_chip *chip)
703 {
704         struct rts51x_usb *rts51x = chip->usb;
705
706         RTS51X_DEBUGP("-- %s\n", __func__);
707
708         /* Free the device-related DMA-mapped buffers */
709         if (rts51x->cr)
710                 usb_buffer_free(rts51x->pusb_dev, sizeof(*rts51x->cr),
711                                 rts51x->cr, rts51x->cr_dma);
712         if (rts51x->iobuf)
713                 usb_buffer_free(rts51x->pusb_dev, RTS51X_IOBUF_SIZE,
714                                 rts51x->iobuf, rts51x->iobuf_dma);
715
716         /* Remove our private data from the interface */
717         usb_set_intfdata(rts51x->pusb_intf, NULL);
718
719 #ifdef SUPPORT_FILE_OP
720         /* give back our minor */
721         usb_deregister_dev(rts51x->pusb_intf, &rts51x_class);
722 #endif
723
724         kfree(rts51x);
725         chip->usb = NULL;
726 }
727
728 /* First stage of disconnect processing: stop SCSI scanning,
729  * remove the host, and stop accepting new commands
730  */
731 static void quiesce_and_remove_host(struct rts51x_chip *chip)
732 {
733         struct rts51x_usb *rts51x = chip->usb;
734         struct Scsi_Host *host = rts51x_to_host(chip);
735
736         /* If the device is really gone, cut short reset delays */
737         if (rts51x->pusb_dev->state == USB_STATE_NOTATTACHED)
738                 set_bit(FLIDX_DISCONNECTING, &rts51x->dflags);
739
740 #ifdef SCSI_SCAN_DELAY
741         /* Prevent SCSI-scanning (if it hasn't started yet)
742          * and wait for the SCSI-scanning thread to stop.
743          */
744         set_bit(FLIDX_DONT_SCAN, &rts51x->dflags);
745         wake_up(&rts51x->delay_wait);
746         wait_for_completion(&rts51x->scanning_done);
747 #endif
748
749         /* Removing the host will perform an orderly shutdown: caches
750          * synchronized, disks spun down, etc.
751          */
752         scsi_remove_host(host);
753
754         /* Prevent any new commands from being accepted and cut short
755          * reset delays.
756          */
757         scsi_lock(host);
758         set_bit(FLIDX_DISCONNECTING, &rts51x->dflags);
759         scsi_unlock(host);
760 #ifdef SCSI_SCAN_DELAY
761         wake_up(&rts51x->delay_wait);
762 #endif
763 }
764
765 /* Second stage of disconnect processing: deallocate all resources */
766 static void release_everything(struct rts51x_chip *chip)
767 {
768         rts51x_release_resources(chip);
769         dissociate_dev(chip);
770
771         /* Drop our reference to the host; the SCSI core will free it
772          * (and "chip" along with it) when the refcount becomes 0. */
773         scsi_host_put(rts51x_to_host(chip));
774 }
775
776 static int rts51x_probe(struct usb_interface *intf,
777                         const struct usb_device_id *id)
778 {
779         struct Scsi_Host *host;
780         struct rts51x_chip *chip;
781         struct rts51x_usb *rts51x;
782         int result;
783         struct task_struct *th;
784
785         RTS51X_DEBUGP("%s detected\n", RTS51X_NAME);
786
787         rts51x = kzalloc(sizeof(struct rts51x_usb), GFP_KERNEL);
788         if (!rts51x) {
789                 printk(KERN_WARNING RTS51X_TIP
790                        "Unable to allocate rts51x_usb\n");
791                 return -ENOMEM;
792         }
793
794         /*
795          * Ask the SCSI layer to allocate a host structure, with extra
796          * space at the end for our private us_data structure.
797          */
798         host = scsi_host_alloc(&rts51x_host_template, sizeof(*chip));
799         if (!host) {
800                 printk(KERN_WARNING RTS51X_TIP
801                        "Unable to allocate the scsi host\n");
802                 kfree(rts51x);
803                 return -ENOMEM;
804         }
805
806         /*
807          * Allow 16-byte CDBs and thus > 2TB
808          */
809         host->max_cmd_len = 16;
810         chip = host_to_rts51x(host);
811         memset(chip, 0, sizeof(struct rts51x_chip));
812
813         chip->vendor_id = id->idVendor;
814         chip->product_id = id->idProduct;
815
816         mutex_init(&(rts51x->dev_mutex));
817         init_completion(&rts51x->cmnd_ready);
818         init_completion(&rts51x->control_exit);
819         init_completion(&rts51x->polling_exit);
820         init_completion(&(rts51x->notify));
821 #ifdef SCSI_SCAN_DELAY
822         init_waitqueue_head(&rts51x->delay_wait);
823         init_completion(&rts51x->scanning_done);
824 #endif
825
826         chip->usb = rts51x;
827
828         /* Associate the us_data structure with the USB device */
829         result = associate_dev(chip, intf);
830         if (result)
831                 goto BadDevice;
832
833         /* Find the endpoints and calculate pipe values */
834         result = get_pipes(chip);
835         if (result)
836                 goto BadDevice;
837
838         /* Acquire all the other resources and add the host */
839         result = rts51x_acquire_resources(chip);
840         if (result)
841                 goto BadDevice;
842
843         /* Start up our control thread */
844         th = kthread_run(rts51x_control_thread, chip, RTS51X_CTL_THREAD);
845         if (IS_ERR(th)) {
846                 printk(KERN_WARNING RTS51X_TIP
847                        "Unable to start control thread\n");
848                 result = PTR_ERR(th);
849                 goto BadDevice;
850         }
851         rts51x->ctl_thread = th;
852
853         result = scsi_add_host(rts51x_to_host(chip), &rts51x->pusb_intf->dev);
854         if (result) {
855                 printk(KERN_WARNING RTS51X_TIP "Unable to add the scsi host\n");
856                 goto BadDevice;
857         }
858 #ifdef SCSI_SCAN_DELAY
859         /* Start up the thread for delayed SCSI-device scanning */
860         th = kthread_create(rts51x_scan_thread, chip, RTS51X_SCAN_THREAD);
861         if (IS_ERR(th)) {
862                 printk(KERN_WARNING RTS51X_TIP
863                        "Unable to start the device-scanning thread\n");
864                 complete(&rts51x->scanning_done);
865                 quiesce_and_remove_host(chip);
866                 result = PTR_ERR(th);
867                 goto BadDevice;
868         }
869
870         wake_up_process(th);
871 #else
872         scsi_scan_host(rts51x_to_host(chip));
873 #endif
874
875         /* Start up our polling thread */
876         th = kthread_run(rts51x_polling_thread, chip, RTS51X_POLLING_THREAD);
877         if (IS_ERR(th)) {
878                 printk(KERN_WARNING RTS51X_TIP
879                        "Unable to start polling thread\n");
880                 result = PTR_ERR(th);
881                 goto BadDevice;
882         }
883         rts51x->polling_thread = th;
884
885 #ifdef CONFIG_PM
886         if (ss_en) {
887                 rts51x->pusb_intf->needs_remote_wakeup = needs_remote_wakeup;
888                 SET_PM_USAGE_CNT(chip, 1);
889                 RTS51X_DEBUGP("pm_usage_cnt = %d\n", GET_PM_USAGE_CNT(chip));
890         }
891 #endif
892
893         return 0;
894
895         /* We come here if there are any problems */
896 BadDevice:
897         RTS51X_DEBUGP("rts51x_probe() failed\n");
898         release_everything(chip);
899         return result;
900 }
901
902 static void rts51x_disconnect(struct usb_interface *intf)
903 {
904         struct rts51x_chip *chip = (struct rts51x_chip *)usb_get_intfdata(intf);
905
906         RTS51X_DEBUGP("rts51x_disconnect() called\n");
907         quiesce_and_remove_host(chip);
908         release_everything(chip);
909 }
910
911 /***********************************************************************
912  * Initialization and registration
913  ***********************************************************************/
914
915 struct usb_device_id rts5139_usb_ids[] = {
916         {USB_DEVICE(0x0BDA, 0x0139)},
917         {USB_DEVICE(0x0BDA, 0x0129)},
918         {}                      /* Terminating entry */
919 };
920 EXPORT_SYMBOL_GPL(rts5139_usb_ids);
921
922 MODULE_DEVICE_TABLE(usb, rts5139_usb_ids);
923
924 struct usb_driver rts51x_driver = {
925         .name = RTS51X_NAME,
926         .probe = rts51x_probe,
927         .disconnect = rts51x_disconnect,
928         .suspend = rts51x_suspend,
929         .resume = rts51x_resume,
930         .reset_resume = rts51x_reset_resume,
931         .pre_reset = rts51x_pre_reset,
932         .post_reset = rts51x_post_reset,
933         .id_table = rts5139_usb_ids,
934         .soft_unbind = 1,
935 };
936
937 static int __init rts51x_init(void)
938 {
939         int retval;
940
941         printk(KERN_INFO "Initializing %s USB card reader driver...\n",
942                RTS51X_NAME);
943
944         /* register the driver, return usb_register return code if error */
945         retval = usb_register(&rts51x_driver);
946         if (retval == 0) {
947                 printk(KERN_INFO
948                        "Realtek %s USB card reader support registered.\n",
949                        RTS51X_NAME);
950         }
951         return retval;
952 }
953
954 static void __exit rts51x_exit(void)
955 {
956         RTS51X_DEBUGP("rts51x_exit() called\n");
957
958         /* Deregister the driver
959          * This will cause disconnect() to be called for each
960          * attached unit
961          */
962         RTS51X_DEBUGP("-- calling usb_deregister()\n");
963         usb_deregister(&rts51x_driver);
964 }
965
966 module_init(rts51x_init);
967 module_exit(rts51x_exit);